Ejemplo n.º 1
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();
  }
Ejemplo n.º 2
0
 /** Same as above except uses a default of now for the timestamp. */
 public static boolean createNewPartyToRelationship(
     String partyIdTo,
     String partyIdFrom,
     String roleTypeIdFrom,
     String partyRelationshipTypeId,
     String securityGroupId,
     List<String> validToPartyRoles,
     boolean expireExistingRelationships,
     GenericValue userLogin,
     Delegator delegator,
     LocalDispatcher dispatcher)
     throws GenericEntityException, GenericServiceException {
   return createNewPartyToRelationship(
       partyIdTo,
       partyIdFrom,
       roleTypeIdFrom,
       partyRelationshipTypeId,
       securityGroupId,
       validToPartyRoles,
       UtilDateTime.nowTimestamp(),
       expireExistingRelationships,
       userLogin,
       delegator,
       dispatcher);
 }
Ejemplo n.º 3
0
  public static Map<String, Object> assembleCrmsfaGenericFormMergeContext(
      TimeZone timeZone, Locale locale) {
    Map<String, Object> templateContext = new HashMap<String, Object>();

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

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

    return templateContext;
  }
Ejemplo n.º 4
0
 public Timestamp getReceivedDate() {
   MimeMessage message = getMessage();
   try {
     return UtilDateTime.toTimestamp(message.getReceivedDate());
   } catch (MessagingException e) {
     Debug.logError(e, module);
     return null;
   }
 }
Ejemplo n.º 5
0
  /** Method to get a condition that checks that the given fieldName is in a given timePeriod. */
  public static EntityCondition getFilterByPeriodExpr(String fieldName, GenericValue timePeriod) {
    Timestamp fromDate;
    Timestamp thruDate;
    if (timePeriod.get("fromDate") instanceof Timestamp) {
      fromDate = timePeriod.getTimestamp("fromDate");
      thruDate = timePeriod.getTimestamp("thruDate");
    } else {
      fromDate = UtilDateTime.toTimestamp(timePeriod.getDate("fromDate"));
      thruDate = UtilDateTime.toTimestamp(timePeriod.getDate("thruDate"));
    }

    EntityConditionList betweenCondition =
        EntityCondition.makeCondition(
            EntityCondition.makeCondition(fieldName, EntityOperator.GREATER_THAN, fromDate),
            EntityCondition.makeCondition(fieldName, EntityOperator.LESS_THAN_EQUAL_TO, thruDate));
    return EntityCondition.makeCondition(
        EntityCondition.makeCondition(fieldName, EntityOperator.NOT_EQUAL, null), betweenCondition);
  }
  private static EntityCondition buildCountCondition(String fieldName, String fieldValue) {
    List<EntityCondition> orCondList = FastList.newInstance();
    orCondList.add(
        EntityCondition.makeCondition(
            "thruDate", EntityOperator.GREATER_THAN, UtilDateTime.nowTimestamp()));
    orCondList.add(EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null));
    EntityCondition orCond = EntityCondition.makeCondition(orCondList, EntityOperator.OR);

    List<EntityCondition> andCondList = FastList.newInstance();
    andCondList.add(
        EntityCondition.makeCondition(
            "fromDate", EntityOperator.LESS_THAN, UtilDateTime.nowTimestamp()));
    andCondList.add(EntityCondition.makeCondition(fieldName, EntityOperator.EQUALS, fieldValue));
    andCondList.add(orCond);
    EntityCondition andCond = EntityCondition.makeCondition(andCondList, EntityOperator.AND);

    return andCond;
  }
Ejemplo n.º 7
0
 /** Method to get the current lead owner of a lead. */
 public static GenericValue getCurrentLeadOwner(String leadPartyId, Delegator delegator)
     throws GenericEntityException {
   return getActivePartyByRole(
       "RESPONSIBLE_FOR",
       leadPartyId,
       "PROSPECT",
       "LEAD_OWNER",
       UtilDateTime.nowTimestamp(),
       delegator);
 }
Ejemplo n.º 8
0
    public String getValue(Map<String, Object> context) {
      if (this.value != null) {
        return this.value.expandString(context);
      }

      Object retVal = null;
      if (this.fromField != null && this.fromField.get(context) != null) {
        retVal = this.fromField.get(context);
      } else {
        retVal = context.get(this.name);
      }

      if (retVal != null) {
        TimeZone timeZone = (TimeZone) context.get("timeZone");
        if (timeZone == null) timeZone = TimeZone.getDefault();

        String returnValue = null;
        // format string based on the user's time zone (not locale because these are parameters)
        if (retVal instanceof Double || retVal instanceof Float || retVal instanceof BigDecimal) {
          returnValue = retVal.toString();
        } else if (retVal instanceof java.sql.Date) {
          DateFormat df = UtilDateTime.toDateFormat(UtilDateTime.DATE_FORMAT, timeZone, null);
          returnValue = df.format((java.util.Date) retVal);
        } else if (retVal instanceof java.sql.Time) {
          DateFormat df = UtilDateTime.toTimeFormat(UtilDateTime.TIME_FORMAT, timeZone, null);
          returnValue = df.format((java.util.Date) retVal);
        } else if (retVal instanceof java.sql.Timestamp) {
          DateFormat df =
              UtilDateTime.toDateTimeFormat(UtilDateTime.DATE_TIME_FORMAT, timeZone, null);
          returnValue = df.format((java.util.Date) retVal);
        } else if (retVal instanceof java.util.Date) {
          DateFormat df =
              UtilDateTime.toDateTimeFormat("EEE MMM dd hh:mm:ss z yyyy", timeZone, null);
          returnValue = df.format((java.util.Date) retVal);
        } else {
          returnValue = retVal.toString();
        }
        return returnValue;
      } else {
        return null;
      }
    }
Ejemplo n.º 9
0
  public static Map<String, Object> deactivateContact(
      DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Security security = dctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = UtilCommon.getLocale(context);

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

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

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

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

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

      delegator.create(
          "PartyDeactivation",
          UtilMisc.toMap("partyId", contactPartyId, "deactivationTimestamp", expireDate));
    } catch (GenericEntityException e) {
      return UtilMessage.createAndLogServiceError(
          e, "CrmErrorDeactivateAccountFail", locale, MODULE);
    }
    return ServiceUtil.returnSuccess();
  }
 private static TimeZone getTimeZone(TimeZone timeZone, Map<String, ? extends Object> context) {
   if (timeZone == null) {
     timeZone = (TimeZone) context.get("timeZone");
     if (timeZone == null && context.containsKey("autoUserLogin")) {
       Map<String, String> autoUserLogin = UtilGenerics.cast(context.get("autoUserLogin"));
       timeZone = UtilDateTime.toTimeZone(autoUserLogin.get("lastTimeZone"));
     }
     if (timeZone == null) {
       timeZone = TimeZone.getDefault();
     }
   }
   return timeZone;
 }
Ejemplo n.º 11
0
  /**
   * Create Note Record
   *
   * @param ctx The DispatchContext that this service is operating in
   * @param context Map containing the input parameters
   * @return Map with the result of the service, the output parameters
   */
  public static Map<String, Object> createNote(DispatchContext ctx, Map<String, ?> context) {
    Delegator delegator = ctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Timestamp noteDate = (Timestamp) context.get("noteDate");
    String partyId = (String) context.get("partyId");
    String noteName = (String) context.get("noteName");
    String note = (String) context.get("note");
    String noteId = delegator.getNextSeqId("NoteData");
    Locale locale = (Locale) context.get("locale");
    if (noteDate == null) {
      noteDate = UtilDateTime.nowTimestamp();
    }

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

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

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

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

    result.put("noteId", noteId);
    result.put("partyId", partyId);
    return result;
  }
Ejemplo n.º 12
0
  public static Map<String, Object> reassignContactResponsibleParty(
      DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Security security = dctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = UtilCommon.getLocale(context);

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

    // ensure reassign permission on this contact
    if (!CrmsfaSecurity.hasPartyRelationSecurity(
        security, "CRMSFA_CONTACT", "_REASSIGN", userLogin, contactPartyId)) {
      return UtilMessage.createAndLogServiceError("CrmErrorPermissionDenied", locale, MODULE);
    }
    try {
      // we need to expire all the active ASSIGNED_TO relationships from the contact party to the
      // new owner party
      List<GenericValue> activeAssignedToRelationships =
          EntityUtil.filterByDate(
              delegator.findByAnd(
                  "PartyRelationship",
                  UtilMisc.toMap(
                      "partyIdFrom",
                      contactPartyId,
                      "roleTypeIdFrom",
                      "CONTACT",
                      "partyIdTo",
                      newPartyId,
                      "partyRelationshipTypeId",
                      "ASSIGNED_TO")));
      PartyHelper.expirePartyRelationships(
          activeAssignedToRelationships, UtilDateTime.nowTimestamp(), dispatcher, userLogin);

      // reassign relationship using a helper method
      boolean result =
          createResponsibleContactRelationshipForParty(
              newPartyId, contactPartyId, userLogin, delegator, dispatcher);
      if (!result) {
        return UtilMessage.createAndLogServiceError("CrmErrorReassignFail", locale, MODULE);
      }
    } catch (GenericServiceException e) {
      return UtilMessage.createAndLogServiceError(e, "CrmErrorReassignFail", locale, MODULE);
    } catch (GenericEntityException e) {
      return UtilMessage.createAndLogServiceError(e, "CrmErrorReassignFail", locale, MODULE);
    }
    return ServiceUtil.returnSuccess();
  }
Ejemplo n.º 13
0
 /**
  * @param elem Will save a browser's screenshot in runtime/logs Need to be called with
  *     captureEntirePageScreenshot and the name of the test case example :
  *     <captureEntirePageScreenshot value="CommEventCreateOpportunity"/>
  */
 private void captureEntirePageScreenshotCmd(Element elem) {
   Long now = UtilDateTime.nowTimestamp().getTime();
   String imageName = replaceParam(elem.getAttributeValue("value")) + "-" + now.toString();
   logger.debug("captureEntirePageScreenshot: " + imageName);
   imagePath = "runtime/logs/" + imageName + ".png";
   try {
     String base64Screenshot = sel.captureEntirePageScreenshotToString("");
     byte[] decodedScreenshot = Base64.decodeBase64(base64Screenshot.getBytes());
     FileOutputStream fos = new FileOutputStream(new File(imagePath));
     fos.write(decodedScreenshot);
     fos.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 14
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;
  }
 public static Map<String, Object> updateEPaketConfig(
     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.findByPrimaryKey(
           "EPaketConfig", UtilMisc.toMap("epaketConfigId", epaketConfigId));
   if (UtilValidate.isNotEmpty(gv)) {
     gv.setNonPKFields(context);
     gv.set("lastModifiedDate", now);
     gv.set("lastModifiedByUserLogin", userLogin.getString("userLoginId"));
     gv.store();
     createEPaketConfigStatus(delegator, gv, "updateEPaketConfig");
   }
   return ServiceUtil.returnSuccess();
 }
Ejemplo n.º 16
0
  public static Map<String, Object> removeContactFromAccount(
      DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Security security = dctx.getSecurity();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = UtilCommon.getLocale(context);

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

    // ensure update permission on account
    if (!CrmsfaSecurity.hasPartyRelationSecurity(
        security, "CRMSFA_ACCOUNT", "_UPDATE", userLogin, accountPartyId)) {
      return UtilMessage.createAndLogServiceError("CrmErrorPermissionDenied", locale, MODULE);
    }
    try {
      // find and expire all contact relationships between the contact and account
      List<GenericValue> relations =
          delegator.findByAnd(
              "PartyRelationship",
              UtilMisc.toMap(
                  "partyIdTo",
                  accountPartyId,
                  "partyIdFrom",
                  contactPartyId,
                  "partyRelationshipTypeId",
                  PartyRelationshipTypeConstants.CONTACT_REL_INV));
      PartyHelper.expirePartyRelationships(
          relations, UtilDateTime.nowTimestamp(), dispatcher, userLogin);
    } catch (GenericServiceException e) {
      return UtilMessage.createAndLogServiceError(e, "CrmErrorRemoveContactFail", locale, MODULE);
    } catch (GenericEntityException e) {
      return UtilMessage.createAndLogServiceError(e, "CrmErrorRemoveContactFail", locale, MODULE);
    }
    return ServiceUtil.returnSuccess();
  }
  /**
   * 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;
  }
Ejemplo n.º 18
0
  // base payment integration services
  public static Map<String, Object> finAccountPreAuth(
      DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
    String finAccountCode = (String) context.get("finAccountCode");
    String finAccountPin = (String) context.get("finAccountPin");
    String finAccountId = (String) context.get("finAccountId");
    String orderId = (String) context.get("orderId");
    BigDecimal amount = (BigDecimal) context.get("processAmount");

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

      return result;
    } catch (GenericEntityException ex) {
      Debug.logError(ex, "Cannot authorize financial account", module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resourceError,
              "AccountingFinAccountCannotBeAuthorized",
              UtilMisc.toMap("errorString", ex.getMessage()),
              locale));
    } catch (GenericServiceException ex) {
      Debug.logError(ex, "Cannot authorize financial account", module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resourceError,
              "AccountingFinAccountCannotBeAuthorized",
              UtilMisc.toMap("errorString", ex.getMessage()),
              locale));
    }
  }
Ejemplo n.º 19
0
 /**
  * Method to get the current non-expired party responsible for the given account/contact/lead.
  *
  * @param partyIdFrom The partyId of the account/contact/lead
  * @param roleTypeIdFrom The role of the account/contact/lead (e.g., ACCOUNT, CONTACT, LEAD)
  * @return First non-expired PartySummaryCRMView or null if none found
  */
 public static GenericValue getCurrentResponsibleParty(
     String partyIdFrom, String roleTypeIdFrom, Delegator delegator)
     throws GenericEntityException {
   return getActivePartyByRole(
       "RESPONSIBLE_FOR", partyIdFrom, roleTypeIdFrom, UtilDateTime.nowTimestamp(), delegator);
 }
Ejemplo n.º 20
0
  // base account transaction services
  public static Map<String, Object> finAccountWithdraw(
      DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");

    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String productStoreId = (String) context.get("productStoreId");
    String finAccountId = (String) context.get("finAccountId");
    String orderItemSeqId = (String) context.get("orderItemSeqId");
    String reasonEnumId = (String) context.get("reasonEnumId");
    String orderId = (String) context.get("orderId");
    Boolean requireBalance = (Boolean) context.get("requireBalance");
    BigDecimal amount = (BigDecimal) context.get("amount");
    if (requireBalance == null) requireBalance = Boolean.TRUE;

    final String WITHDRAWAL = "WITHDRAWAL";

    String partyId = (String) context.get("partyId");
    if (UtilValidate.isEmpty(partyId)) {
      partyId = "_NA_";
    }
    String currencyUom = (String) context.get("currency");
    if (UtilValidate.isEmpty(currencyUom)) {
      currencyUom =
          EntityUtilProperties.getPropertyValue(
              "general.properties", "currency.uom.id.default", "USD", delegator);
    }

    // validate the amount
    if (amount.compareTo(BigDecimal.ZERO) < 0) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resourceError, "AccountingFinAccountMustBePositive", locale));
    }

    GenericValue finAccount;
    try {
      finAccount =
          EntityQuery.use(delegator)
              .from("FinAccount")
              .where("finAccountId", finAccountId)
              .queryOne();
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }

    // verify we have a financial account
    if (finAccount == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resourceError,
              "AccountingFinAccountNotFound",
              UtilMisc.toMap("finAccountId", ""),
              locale));
    }

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

    // check the actual balance (excluding authorized amounts) and create the transaction if it is
    // sufficient
    BigDecimal previousBalance = finAccount.getBigDecimal("actualBalance");
    if (previousBalance == null) {
      previousBalance = FinAccountHelper.ZERO;
    }

    BigDecimal balance;
    String refNum;
    Boolean procResult;
    if (requireBalance && previousBalance.compareTo(amount) < 0) {
      procResult = Boolean.FALSE;
      balance = previousBalance;
      refNum = "N/A";
    } else {
      try {
        refNum =
            FinAccountPaymentServices.createFinAcctPaymentTransaction(
                delegator,
                dispatcher,
                userLogin,
                amount,
                productStoreId,
                partyId,
                orderId,
                orderItemSeqId,
                currencyUom,
                WITHDRAWAL,
                finAccountId,
                reasonEnumId);
        finAccount.refresh();
        balance = finAccount.getBigDecimal("actualBalance");
        procResult = Boolean.TRUE;
      } catch (GeneralException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
      }
    }

    // make sure balance is not null
    if (balance == null) {
      balance = FinAccountHelper.ZERO;
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("previousBalance", previousBalance);
    result.put("balance", balance);
    result.put("amount", amount);
    result.put("processResult", procResult);
    result.put("referenceNum", refNum);
    return result;
  }
Ejemplo n.º 21
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;
  }
Ejemplo n.º 22
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_:";
  }
Ejemplo n.º 23
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";
  }
Ejemplo n.º 24
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";
  }
Ejemplo n.º 25
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";
    }
  }
Ejemplo n.º 26
0
  public void sessionDestroyed(HttpSessionEvent event) {
    HttpSession session = event.getSession();

    // Finalize the Visit
    boolean beganTransaction = false;
    try {
      beganTransaction = TransactionUtil.begin();

      // instead of using this message, get directly from session attribute so it won't create a new
      // one: GenericValue visit = VisitHandler.getVisit(session);
      GenericValue visit = (GenericValue) session.getAttribute("visit");
      if (visit != null) {
        visit.set("thruDate", new Timestamp(session.getLastAccessedTime()));
        visit.store();
      } else {
        Debug.logWarning(
            "Could not find visit value object in session ["
                + session.getId()
                + "] that is being destroyed",
            module);
      }

      // Store the UserLoginSession
      String userLoginSessionString = getUserLoginSession(session);
      GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
      if (userLogin != null && userLoginSessionString != null) {
        GenericValue userLoginSession = null;
        userLoginSession = userLogin.getRelatedOne("UserLoginSession");

        if (userLoginSession == null) {
          userLoginSession =
              userLogin
                  .getDelegator()
                  .makeValue(
                      "UserLoginSession",
                      UtilMisc.toMap("userLoginId", userLogin.getString("userLoginId")));
          userLogin.getDelegator().create(userLoginSession);
        }
        userLoginSession.set("savedDate", UtilDateTime.nowTimestamp());
        userLoginSession.set("sessionData", userLoginSessionString);
        userLoginSession.store();
      }

      countDestroySession();
      Debug.logInfo("Destroying session: " + session.getId(), module);
      this.logStats(session, visit);
    } catch (GenericEntityException e) {
      try {
        // only rollback the transaction if we started one...
        TransactionUtil.rollback(
            beganTransaction, "Error saving information about closed HttpSession", e);
      } catch (GenericEntityException e2) {
        Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
      }

      Debug.logError(e, "Error in session destuction information persistence", 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 update visit for session destuction", module);
      }
    }
  }
Ejemplo n.º 27
0
  // base deposit service
  public static Map<String, Object> finAccountDeposit(
      DispatchContext dctx, Map<String, Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    Locale locale = (Locale) context.get("locale");

    GenericValue userLogin = (GenericValue) context.get("userLogin");
    String productStoreId = (String) context.get("productStoreId");
    String finAccountId = (String) context.get("finAccountId");
    String orderItemSeqId = (String) context.get("orderItemSeqId");
    String reasonEnumId = (String) context.get("reasonEnumId");
    String orderId = (String) context.get("orderId");
    Boolean isRefund = (Boolean) context.get("isRefund");
    BigDecimal amount = (BigDecimal) context.get("amount");

    final String DEPOSIT = isRefund == null || !isRefund ? "DEPOSIT" : "ADJUSTMENT";

    String partyId = (String) context.get("partyId");
    if (UtilValidate.isEmpty(partyId)) {
      partyId = "_NA_";
    }
    String currencyUom = (String) context.get("currency");
    if (UtilValidate.isEmpty(currencyUom)) {
      currencyUom =
          EntityUtilProperties.getPropertyValue(
              "general.properties", "currency.uom.id.default", "USD", delegator);
    }

    GenericValue finAccount;
    try {
      finAccount =
          EntityQuery.use(delegator)
              .from("FinAccount")
              .where("finAccountId", finAccountId)
              .queryOne();
    } catch (GenericEntityException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resourceError,
              "AccountingFinAccountNotFound",
              UtilMisc.toMap("finAccountId", finAccountId),
              locale));
    }

    // verify we have a financial account
    if (finAccount == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resourceError,
              "AccountingFinAccountNotFound",
              UtilMisc.toMap("finAccountId", ""),
              locale));
    }

    // make sure the fin account itself has not expired
    if ((finAccount.getTimestamp("thruDate") != null)
        && (finAccount.getTimestamp("thruDate").before(UtilDateTime.nowTimestamp()))) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resourceError,
              "AccountingFinAccountExpired",
              UtilMisc.toMap("thruDate", finAccount.getTimestamp("thruDate")),
              locale));
    }
    Debug.logInfo("Deposit into financial account #" + finAccountId + " [" + amount + "]", module);

    // get the previous balance
    BigDecimal previousBalance = finAccount.getBigDecimal("actualBalance");
    if (previousBalance == null) {
      previousBalance = FinAccountHelper.ZERO;
    }

    // create the transaction
    BigDecimal actualBalance;
    String refNum;
    try {
      refNum =
          FinAccountPaymentServices.createFinAcctPaymentTransaction(
              delegator,
              dispatcher,
              userLogin,
              amount,
              productStoreId,
              partyId,
              orderId,
              orderItemSeqId,
              currencyUom,
              DEPOSIT,
              finAccountId,
              reasonEnumId);
      finAccount.refresh();
      actualBalance = finAccount.getBigDecimal("actualBalance");
    } catch (GeneralException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }

    // make sure balance is not null
    if (actualBalance == null) {
      actualBalance = FinAccountHelper.ZERO;
    } else {
      if (actualBalance.compareTo(BigDecimal.ZERO) < 0) {
        // balance went below zero, set negative pending replenishment status so that no more auths
        // or captures will go through until it is replenished
        try {
          Map<String, Object> rollbackCtx =
              UtilMisc.toMap(
                  "userLogin",
                  userLogin,
                  "finAccountId",
                  finAccountId,
                  "statusId",
                  "FNACT_NEGPENDREPL");
          dispatcher.addRollbackService("updateFinAccount", rollbackCtx, true);
        } catch (GenericServiceException e) {
          Debug.logError(e, module);
          return ServiceUtil.returnError(e.getMessage());
        }
      }
    }

    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("previousBalance", previousBalance);
    result.put("balance", actualBalance);
    result.put("amount", amount);
    result.put("processResult", Boolean.TRUE);
    result.put("referenceNum", refNum);
    return result;
  }
Ejemplo n.º 28
0
  public static Map<String, Object> getExpressCheckout(
      DispatchContext dctx, Map<String, Object> context) {
    Locale locale = (Locale) context.get("locale");
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();

    ShoppingCart cart = (ShoppingCart) context.get("cart");
    GenericValue payPalConfig = getPaymentMethodGatewayPayPal(dctx, context, null);
    if (payPalConfig == null) {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(
              resource, "AccountingPayPalPaymentGatewayConfigCannotFind", locale));
    }

    NVPEncoder encoder = new NVPEncoder();
    encoder.add("METHOD", "GetExpressCheckoutDetails");
    String token = (String) cart.getAttribute("payPalCheckoutToken");
    if (UtilValidate.isNotEmpty(token)) {
      encoder.add("TOKEN", token);
    } else {
      return ServiceUtil.returnError(
          UtilProperties.getMessage(resource, "AccountingPayPalTokenNotFound", locale));
    }

    NVPDecoder decoder;
    try {
      decoder = sendNVPRequest(payPalConfig, encoder);
    } catch (PayPalException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }

    if (UtilValidate.isNotEmpty(decoder.get("NOTE"))) {
      cart.addOrderNote(decoder.get("NOTE"));
    }

    if (cart.getUserLogin() == null) {
      try {
        GenericValue userLogin =
            EntityQuery.use(delegator)
                .from("UserLogin")
                .where("userLoginId", "anonymous")
                .queryOne();
        try {
          cart.setUserLogin(userLogin, dispatcher);
        } catch (CartItemModifyException e) {
          Debug.logError(e, module);
          return ServiceUtil.returnError(e.getMessage());
        }
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
      }
    }
    boolean anon = "anonymous".equals(cart.getUserLogin().getString("userLoginId"));
    // Even if anon, a party could already have been created
    String partyId = cart.getOrderPartyId();
    if (partyId == null && anon) {
      // Check nothing has been set on the anon userLogin either
      partyId = cart.getUserLogin() != null ? cart.getUserLogin().getString("partyId") : null;
      cart.setOrderPartyId(partyId);
    }
    if (partyId != null) {
      GenericValue party = null;
      try {
        party = EntityQuery.use(delegator).from("Party").where("partyId", partyId).queryOne();
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
      }
      if (party == null) {
        partyId = null;
      }
    }

    Map<String, Object> inMap = FastMap.newInstance();
    Map<String, Object> outMap = null;
    // Create the person if necessary
    boolean newParty = false;
    if (partyId == null) {
      newParty = true;
      inMap.put("userLogin", cart.getUserLogin());
      inMap.put("personalTitle", decoder.get("SALUTATION"));
      inMap.put("firstName", decoder.get("FIRSTNAME"));
      inMap.put("middleName", decoder.get("MIDDLENAME"));
      inMap.put("lastName", decoder.get("LASTNAME"));
      inMap.put("suffix", decoder.get("SUFFIX"));
      try {
        outMap = dispatcher.runSync("createPerson", inMap);
        partyId = (String) outMap.get("partyId");
        cart.setOrderPartyId(partyId);
        cart.getUserLogin().setString("partyId", partyId);
        inMap.clear();
        inMap.put("userLogin", cart.getUserLogin());
        inMap.put("partyId", partyId);
        inMap.put("roleTypeId", "CUSTOMER");
        dispatcher.runSync("createPartyRole", inMap);
      } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
      }
    }
    // Create a new email address if necessary
    String emailContactMechId = null;
    String emailContactPurposeTypeId = "PRIMARY_EMAIL";
    String emailAddress = decoder.get("EMAIL");
    if (!newParty) {
      EntityCondition cond =
          EntityCondition.makeCondition(
              UtilMisc.toList(
                  EntityCondition.makeCondition(
                      UtilMisc.toMap("partyId", partyId, "contactMechTypeId", "EMAIL_ADDRESS")),
                  EntityCondition.makeCondition(
                      EntityFunction.UPPER_FIELD("infoString"),
                      EntityComparisonOperator.EQUALS,
                      EntityFunction.UPPER(emailAddress))));

      try {
        GenericValue matchingEmail =
            EntityQuery.use(delegator)
                .from("PartyAndContactMech")
                .where(cond)
                .orderBy("fromDate")
                .filterByDate()
                .queryFirst();
        if (matchingEmail != null) {
          emailContactMechId = matchingEmail.getString("contactMechId");
        } else {
          // No email found so we'll need to create one but first check if it should be PRIMARY or
          // just BILLING
          long primaryEmails =
              EntityQuery.use(delegator)
                  .from("PartyContactWithPurpose")
                  .where(
                      "partyId",
                      partyId,
                      "contactMechTypeId",
                      "EMAIL_ADDRESS",
                      "contactMechPurposeTypeId",
                      "PRIMARY_EMAIL")
                  .filterByDate(
                      "contactFromDate", "contactThruDate", "purposeFromDate", "purposeThruDate")
                  .queryCount();
          if (primaryEmails > 0) emailContactPurposeTypeId = "BILLING_EMAIL";
        }
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
      }
    }
    if (emailContactMechId == null) {
      inMap.clear();
      inMap.put("userLogin", cart.getUserLogin());
      inMap.put("contactMechPurposeTypeId", emailContactPurposeTypeId);
      inMap.put("emailAddress", emailAddress);
      inMap.put("partyId", partyId);
      inMap.put("roleTypeId", "CUSTOMER");
      inMap.put("verified", "Y"); // Going to assume PayPal has taken care of this for us
      inMap.put("fromDate", UtilDateTime.nowTimestamp());
      try {
        outMap = dispatcher.runSync("createPartyEmailAddress", inMap);
        emailContactMechId = (String) outMap.get("contactMechId");
      } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
      }
    }
    cart.addContactMech("ORDER_EMAIL", emailContactMechId);

    // Phone number
    String phoneNumber = decoder.get("PHONENUM");
    String phoneContactId = null;
    if (phoneNumber != null) {
      inMap.clear();
      if (phoneNumber.startsWith("+")) {
        // International, format is +XXX XXXXXXXX which we'll split into countryCode + contactNumber
        String[] phoneNumbers = phoneNumber.split(" ");
        inMap.put("countryCode", StringUtil.removeNonNumeric(phoneNumbers[0]));
        inMap.put("contactNumber", phoneNumbers[1]);
      } else {
        // U.S., format is XXX-XXX-XXXX which we'll split into areaCode + contactNumber
        inMap.put("countryCode", "1");
        String[] phoneNumbers = phoneNumber.split("-");
        inMap.put("areaCode", phoneNumbers[0]);
        inMap.put("contactNumber", phoneNumbers[1] + phoneNumbers[2]);
      }
      inMap.put("userLogin", cart.getUserLogin());
      inMap.put("partyId", partyId);
      try {
        outMap = dispatcher.runSync("createUpdatePartyTelecomNumber", inMap);
        phoneContactId = (String) outMap.get("contactMechId");
        cart.addContactMech("PHONE_BILLING", phoneContactId);
      } catch (GenericServiceException e) {
        Debug.logError(e, module);
      }
    }
    // Create a new Postal Address if necessary
    String postalContactId = null;
    boolean needsShippingPurpose = true;
    // if the cart for some reason already has a billing address, we'll leave it be
    boolean needsBillingPurpose = (cart.getContactMech("BILLING_LOCATION") == null);
    Map<String, Object> postalMap = FastMap.newInstance();
    postalMap.put("toName", decoder.get("SHIPTONAME"));
    postalMap.put("address1", decoder.get("SHIPTOSTREET"));
    postalMap.put("address2", decoder.get("SHIPTOSTREET2"));
    postalMap.put("city", decoder.get("SHIPTOCITY"));
    String countryGeoId =
        PayPalServices.getCountryGeoIdFromGeoCode(decoder.get("SHIPTOCOUNTRYCODE"), delegator);
    postalMap.put("countryGeoId", countryGeoId);
    postalMap.put(
        "stateProvinceGeoId",
        parseStateProvinceGeoId(decoder.get("SHIPTOSTATE"), countryGeoId, delegator));
    postalMap.put("postalCode", decoder.get("SHIPTOZIP"));
    if (!newParty) {
      // We want an exact match only
      EntityCondition cond =
          EntityCondition.makeCondition(
              UtilMisc.toList(
                  EntityCondition.makeCondition(postalMap),
                  EntityCondition.makeCondition(
                      UtilMisc.toMap(
                          "attnName",
                          null,
                          "directions",
                          null,
                          "postalCodeExt",
                          null,
                          "postalCodeGeoId",
                          null)),
                  EntityCondition.makeCondition("partyId", partyId)));
      try {
        GenericValue postalMatch =
            EntityQuery.use(delegator)
                .from("PartyAndPostalAddress")
                .where(cond)
                .orderBy("fromDate")
                .filterByDate()
                .queryFirst();
        if (postalMatch != null) {
          postalContactId = postalMatch.getString("contactMechId");
          List<GenericValue> postalPurposes =
              EntityQuery.use(delegator)
                  .from("PartyContactMechPurpose")
                  .where("partyId", partyId, "contactMechId", postalContactId)
                  .filterByDate()
                  .queryList();
          List<Object> purposeStrings =
              EntityUtil.getFieldListFromEntityList(
                  postalPurposes, "contactMechPurposeTypeId", false);
          if (UtilValidate.isNotEmpty(purposeStrings)
              && purposeStrings.contains("SHIPPING_LOCATION")) {
            needsShippingPurpose = false;
          }
          if (needsBillingPurpose
              && UtilValidate.isNotEmpty(purposeStrings)
              && purposeStrings.contains("BILLING_LOCATION")) {
            needsBillingPurpose = false;
          }
        }
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
      }
    }
    if (postalContactId == null) {
      postalMap.put("userLogin", cart.getUserLogin());
      postalMap.put("fromDate", UtilDateTime.nowTimestamp());
      try {
        outMap = dispatcher.runSync("createPartyPostalAddress", postalMap);
        postalContactId = (String) outMap.get("contactMechId");
      } catch (GenericServiceException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
      }
    }
    if (needsShippingPurpose || needsBillingPurpose) {
      inMap.clear();
      inMap.put("userLogin", cart.getUserLogin());
      inMap.put("contactMechId", postalContactId);
      inMap.put("partyId", partyId);
      try {
        if (needsShippingPurpose) {
          inMap.put("contactMechPurposeTypeId", "SHIPPING_LOCATION");
          dispatcher.runSync("createPartyContactMechPurpose", inMap);
        }
        if (needsBillingPurpose) {
          inMap.put("contactMechPurposeTypeId", "BILLING_LOCATION");
          dispatcher.runSync("createPartyContactMechPurpose", inMap);
        }
      } catch (GenericServiceException e) {
        // Not the end of the world, we'll carry on
        Debug.logInfo(e.getMessage(), module);
      }
    }

    // Load the selected shipping method - thanks to PayPal's less than sane API all we've to work
    // with is the shipping option label
    // that was shown to the customer
    String shipMethod = decoder.get("SHIPPINGOPTIONNAME");
    if ("Calculated Offline".equals(shipMethod)) {
      cart.setAllCarrierPartyId("_NA_");
      cart.setAllShipmentMethodTypeId("NO_SHIPPING");
    } else {
      String[] shipMethodSplit = shipMethod.split(" - ");
      cart.setAllCarrierPartyId(shipMethodSplit[0]);
      String shippingMethodTypeDesc =
          StringUtils.join(shipMethodSplit, " - ", 1, shipMethodSplit.length);
      try {
        GenericValue shipmentMethod =
            EntityQuery.use(delegator)
                .from("ProductStoreShipmentMethView")
                .where(
                    "productStoreId",
                    cart.getProductStoreId(),
                    "partyId",
                    shipMethodSplit[0],
                    "roleTypeId",
                    "CARRIER",
                    "description",
                    shippingMethodTypeDesc)
                .queryFirst();
        cart.setAllShipmentMethodTypeId(shipmentMethod.getString("shipmentMethodTypeId"));
      } catch (GenericEntityException e1) {
        Debug.logError(e1, module);
      }
    }
    // Get rid of any excess ship groups
    List<CartShipInfo> shipGroups = cart.getShipGroups();
    for (int i = 1; i < shipGroups.size(); i++) {
      Map<ShoppingCartItem, BigDecimal> items = cart.getShipGroupItems(i);
      for (Map.Entry<ShoppingCartItem, BigDecimal> entry : items.entrySet()) {
        cart.positionItemToGroup(entry.getKey(), entry.getValue(), i, 0, false);
      }
    }
    cart.cleanUpShipGroups();
    cart.setAllShippingContactMechId(postalContactId);
    Map<String, Object> result =
        ShippingEvents.getShipGroupEstimate(dispatcher, delegator, cart, 0);
    if (result.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR)) {
      return ServiceUtil.returnError((String) result.get(ModelService.ERROR_MESSAGE));
    }

    BigDecimal shippingTotal = (BigDecimal) result.get("shippingTotal");
    if (shippingTotal == null) {
      shippingTotal = BigDecimal.ZERO;
    }
    cart.setItemShipGroupEstimate(shippingTotal, 0);
    CheckOutHelper cho = new CheckOutHelper(dispatcher, delegator, cart);
    try {
      cho.calcAndAddTax();
    } catch (GeneralException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }

    // Create the PayPal payment method
    inMap.clear();
    inMap.put("userLogin", cart.getUserLogin());
    inMap.put("partyId", partyId);
    inMap.put("contactMechId", postalContactId);
    inMap.put("fromDate", UtilDateTime.nowTimestamp());
    inMap.put("payerId", decoder.get("PAYERID"));
    inMap.put("expressCheckoutToken", token);
    inMap.put("payerStatus", decoder.get("PAYERSTATUS"));

    try {
      outMap = dispatcher.runSync("createPayPalPaymentMethod", inMap);
    } catch (GenericServiceException e) {
      Debug.logError(e, module);
      return ServiceUtil.returnError(e.getMessage());
    }
    String paymentMethodId = (String) outMap.get("paymentMethodId");

    cart.clearPayments();
    BigDecimal maxAmount = cart.getGrandTotal().setScale(2, BigDecimal.ROUND_HALF_UP);
    cart.addPaymentAmount(paymentMethodId, maxAmount, true);

    return ServiceUtil.returnSuccess();
  }
  @SuppressWarnings("unchecked")
  public Writer getWriter(final Writer out, Map args) {
    final StringBuilder buf = new StringBuilder();
    final Environment env = Environment.getCurrentEnvironment();
    final Map<String, Object> templateCtx = FreeMarkerWorker.getWrappedObject("context", env);
    // FreeMarkerWorker.convertContext(templateCtx);
    final Map<String, Object> savedValues = FreeMarkerWorker.saveValues(templateCtx, saveKeyNames);
    FreeMarkerWorker.overrideWithArgs(templateCtx, args);
    final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env);
    /*
            final String editTemplate = FreeMarkerWorker.getArg(args, "editTemplate", ctx);
            final String wrapTemplateId = FreeMarkerWorker.getArg(args, "wrapTemplateId", ctx);
            //final String mapKey = FreeMarkerWorker.getArg(args, "mapKey", ctx);
            final String templateContentId = FreeMarkerWorker.getArg(args, "templateContentId", ctx);
            final String subDataResourceTypeId = FreeMarkerWorker.getArg(args, "subDataResourceTypeId", ctx);
            final String contentId = FreeMarkerWorker.getArg(args, "contentId", ctx);
            final String subContentId = FreeMarkerWorker.getArg(args, "subContentId", ctx);
            final String rootDir = FreeMarkerWorker.getArg(args, "rootDir", ctx);
            final String webSiteId = FreeMarkerWorker.getArg(args, "webSiteId", ctx);
            final String https = FreeMarkerWorker.getArg(args, "https", ctx);
            final String viewSize = FreeMarkerWorker.getArg(args, "viewSize", ctx);
            final String viewIndex = FreeMarkerWorker.getArg(args, "viewIndex", ctx);
            final String listSize = FreeMarkerWorker.getArg(args, "listSize", ctx);
            final String highIndex = FreeMarkerWorker.getArg(args, "highIndex", ctx);
            final String lowIndex = FreeMarkerWorker.getArg(args, "lowIndex", ctx);
            final String queryString = FreeMarkerWorker.getArg(args, "queryString", ctx);
            final Locale locale = FreeMarkerWorker.getWrappedObject("locale", env);
            final String mimeTypeId = FreeMarkerWorker.getArg(args, "mimeTypeId", ctx);
    */
    final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env);
    // final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env);
    GenericValue view = FreeMarkerWorker.getWrappedObject("subContentDataResourceView", env);
    final Integer indent =
        (templateCtx.get("indent") == null)
            ? Integer.valueOf(0)
            : (Integer) templateCtx.get("indent");

    String contentId = (String) templateCtx.get("contentId");
    String subContentId = (String) templateCtx.get("subContentId");
    if (view == null) {
      String thisContentId = subContentId;
      if (UtilValidate.isEmpty(thisContentId)) {
        thisContentId = contentId;
      }
      if (UtilValidate.isNotEmpty(thisContentId)) {
        try {
          view = delegator.findByPrimaryKey("Content", UtilMisc.toMap("contentId", thisContentId));
        } catch (GenericEntityException e) {
          Debug.logError(e, "Error getting sub-content", module);
          throw new RuntimeException(e.getMessage());
        }
      }
    }

    final GenericValue subContentDataResourceView = view;
    final Map<String, Object> traverseContext = FastMap.newInstance();
    traverseContext.put("delegator", delegator);
    Map<String, Object> whenMap = FastMap.newInstance();
    whenMap.put("followWhen", templateCtx.get("followWhen"));
    whenMap.put("pickWhen", templateCtx.get("pickWhen"));
    whenMap.put("returnBeforePickWhen", templateCtx.get("returnBeforePickWhen"));
    whenMap.put("returnAfterPickWhen", templateCtx.get("returnAfterPickWhen"));
    traverseContext.put("whenMap", whenMap);
    String fromDateStr = (String) templateCtx.get("fromDateStr");
    String thruDateStr = (String) templateCtx.get("thruDateStr");
    Timestamp fromDate = null;
    if (UtilValidate.isNotEmpty(fromDateStr)) {
      fromDate = UtilDateTime.toTimestamp(fromDateStr);
    }
    traverseContext.put("fromDate", fromDate);
    Timestamp thruDate = null;
    if (UtilValidate.isNotEmpty(thruDateStr)) {
      thruDate = UtilDateTime.toTimestamp(thruDateStr);
    }
    traverseContext.put("thruDate", thruDate);
    String startContentAssocTypeId = (String) templateCtx.get("contentAssocTypeId");
    if (startContentAssocTypeId != null) startContentAssocTypeId = "SUB_CONTENT";
    traverseContext.put("contentAssocTypeId", startContentAssocTypeId);
    String direction = (String) templateCtx.get("direction");
    if (UtilValidate.isEmpty(direction)) direction = "From";
    traverseContext.put("direction", direction);

    return new LoopWriter(out) {

      @Override
      public void write(char cbuf[], int off, int len) {
        // StringBuilder ctxBuf = (StringBuilder) templateContext.get("buf");
        // ctxBuf.append(cbuf, off, len);
        buf.append(cbuf, off, len);
      }

      @Override
      public void flush() throws IOException {
        out.flush();
      }

      @Override
      public int onStart() throws TemplateModelException, IOException {
        // templateContext.put("buf", new StringBuilder());
        List<Map<String, Object>> nodeTrail = FastList.newInstance();
        traverseContext.put("nodeTrail", nodeTrail);
        // GenericValue content = null;
        /*
                        if (UtilValidate.isNotEmpty(contentId)) {
                            try {
                                content = delegator.findByPrimaryKey("Content", UtilMisc.toMap("contentId", contentId));
                            } catch (GenericEntityException e) {
                                // TODO: Not sure what to put here.
                                throw new RuntimeException(e.getMessage());
                            }
                        }
        */
        Map<String, Object> rootNode = ContentWorker.makeNode(subContentDataResourceView);
        ContentWorker.traceNodeTrail("1", nodeTrail);
        ContentWorker.selectKids(rootNode, traverseContext);
        ContentWorker.traceNodeTrail("2", nodeTrail);
        nodeTrail.add(rootNode);
        boolean isPick =
            checkWhen(
                subContentDataResourceView, (String) traverseContext.get("contentAssocTypeId"));
        rootNode.put("isPick", Boolean.valueOf(isPick));
        if (!isPick) {
          ContentWorker.traceNodeTrail("3", nodeTrail);
          isPick = ContentWorker.traverseSubContent(traverseContext);
          ContentWorker.traceNodeTrail("4", nodeTrail);
        }
        if (isPick) {
          populateContext(traverseContext, templateCtx);
          ContentWorker.traceNodeTrail("5", nodeTrail);
          return TransformControl.EVALUATE_BODY;
        } else {
          return TransformControl.SKIP_BODY;
        }
      }

      @Override
      public int afterBody() throws TemplateModelException, IOException {
        // out.write(buf.toString());
        // buf.setLength(0);
        // templateContext.put("buf", new StringBuilder());
        List<Map<String, Object>> nodeTrail =
            UtilGenerics.checkList(traverseContext.get("nodeTrail"));
        ContentWorker.traceNodeTrail("6", nodeTrail);
        boolean inProgress = ContentWorker.traverseSubContent(traverseContext);
        ContentWorker.traceNodeTrail("7", nodeTrail);
        if (inProgress) {
          populateContext(traverseContext, templateCtx);
          ContentWorker.traceNodeTrail("8", nodeTrail);
          return TransformControl.REPEAT_EVALUATION;
        } else return TransformControl.END_EVALUATION;
      }

      @Override
      public void close() throws IOException {
        String wrappedFTL = buf.toString();
        String encloseWrappedText = (String) templateCtx.get("encloseWrappedText");
        if (UtilValidate.isEmpty(encloseWrappedText)
            || encloseWrappedText.equalsIgnoreCase("false")) {
          out.write(wrappedFTL);
          wrappedFTL = null; // So it won't get written again below.
        }
        String wrapTemplateId = (String) templateCtx.get("wrapTemplateId");
        if (UtilValidate.isNotEmpty(wrapTemplateId)) {
          templateCtx.put("wrappedFTL", wrappedFTL);
          Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env);
          /*
                              templateRoot.put("viewSize", viewSize);
                              templateRoot.put("viewIndex", viewIndex);
                              templateRoot.put("listSize", listSize);
                              templateRoot.put("highIndex", highIndex);
                              templateRoot.put("lowIndex", lowIndex);
                              templateRoot.put("queryString", queryString);
                              templateRoot.put("wrapDataResourceTypeId", subDataResourceTypeId);
                              templateRoot.put("wrapContentIdTo", contentId);
                              templateRoot.put("wrapMimeTypeId", mimeTypeId);
                              //templateRoot.put("wrapMapKey", mapKey);

          */
          templateRoot.put("context", templateCtx);
          String mimeTypeId = (String) templateCtx.get("mimeTypeId");
          Locale locale = (Locale) templateCtx.get("locale");
          if (locale == null) locale = Locale.getDefault();
          try {
            ContentWorker.renderContentAsText(
                dispatcher,
                delegator,
                wrapTemplateId,
                out,
                templateRoot,
                locale,
                mimeTypeId,
                null,
                null,
                true);
          } catch (GeneralException e) {
            Debug.logError(e, "Error rendering content", module);
            throw new IOException("Error rendering content" + e.toString());
          }
          /*
                              Map resultsCtx = FreeMarkerWorker.getWrappedObject("context", env);
                              templateContext.put("contentId", contentId);
                              templateContext.put("locale", locale);
                              templateContext.put("mapKey", null);
                              templateContext.put("subContentId", null);
                              templateContext.put("templateContentId", null);
                              templateContext.put("subDataResourceTypeId", null);
                              templateContext.put("mimeTypeId", null);
          */
        } else {
          if (UtilValidate.isNotEmpty(wrappedFTL)) out.write(wrappedFTL);
        }
        FreeMarkerWorker.removeValues(templateCtx, removeKeyNames);
        FreeMarkerWorker.reloadValues(templateCtx, savedValues, env);
      }

      private boolean checkWhen(GenericValue thisContent, String contentAssocTypeId) {
        boolean isPick = false;
        Map<String, Object> assocContext = FastMap.newInstance();
        if (UtilValidate.isEmpty(contentAssocTypeId)) {
          contentAssocTypeId = "";
        }
        assocContext.put("contentAssocTypeId", contentAssocTypeId);
        // assocContext.put("contentTypeId", assocValue.get("contentTypeId"));
        // String assocRelation = null;
        String thisDirection = (String) templateCtx.get("direction");
        String thisContentId = (String) templateCtx.get("thisContentId");
        // String relatedDirection = null;
        if (thisDirection != null && thisDirection.equalsIgnoreCase("From")) {
          assocContext.put("contentIdFrom", thisContentId);
          // assocRelation = "FromContent";
          // relatedDirection = "From";
        } else {
          assocContext.put("contentIdTo", thisContentId);
          // assocRelation = "ToContent";
          // relatedDirection = "To";
        }
        assocContext.put("content", thisContent);
        List<Object> purposes = ContentWorker.getPurposes(thisContent);
        assocContext.put("purposes", purposes);
        List<String> contentTypeAncestry = FastList.newInstance();
        String contentTypeId = (String) thisContent.get("contentTypeId");
        try {
          ContentWorker.getContentTypeAncestry(delegator, contentTypeId, contentTypeAncestry);
        } catch (GenericEntityException e) {
          return false;
        }
        assocContext.put("typeAncestry", contentTypeAncestry);
        Map<String, Object> whenMap = UtilGenerics.checkMap(traverseContext.get("whenMap"));
        // String pickWhen = (String)whenMap.get("pickWhen");
        List<Map<String, ? extends Object>> nodeTrail =
            UtilGenerics.checkList(traverseContext.get("nodeTrail"));
        int indentSz = indent.intValue() + nodeTrail.size();
        assocContext.put("indentObj", Integer.valueOf(indentSz));
        isPick = ContentWorker.checkWhen(assocContext, (String) whenMap.get("pickWhen"));
        return isPick;
      }

      public void populateContext(
          Map<String, Object> traverseContext, Map<String, Object> templateContext) {
        List<Map<String, Object>> nodeTrail =
            UtilGenerics.checkList(traverseContext.get("nodeTrail"));
        int sz = nodeTrail.size();
        Map<String, Object> node = nodeTrail.get(sz - 1);
        // GenericValue content = (GenericValue)node.get("value");
        String contentId = (String) node.get("contentId");
        // String subContentId = (String)node.get("subContentId");
        templateContext.put("subContentId", contentId);
        templateContext.put("subContentDataResourceView", null);
        int indentSz = indent.intValue() + nodeTrail.size();
        templateContext.put("indent", Integer.valueOf(indentSz));
        if (sz >= 2) {
          Map<String, Object> parentNode = nodeTrail.get(sz - 2);
          GenericValue parentContent = (GenericValue) parentNode.get("value");
          String parentContentId = (String) parentNode.get("contentId");
          templateContext.put("parentContentId", parentContentId);
          templateContext.put("parentContent", parentContent);
          templateContext.put("nodeTrail", nodeTrail);
        }
      }
    };
  }
Ejemplo n.º 30
0
  /** Restores the specialized (auto-save) shopping list back into the shopping cart */
  public static String restoreAutoSaveList(
      HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
    GenericValue productStore = ProductStoreWorker.getProductStore(request);

    if (!ProductStoreWorker.autoSaveCart(productStore)) {
      // if auto-save is disabled just return here
      return "success";
    }

    HttpSession session = request.getSession();
    ShoppingCart cart = ShoppingCartEvents.getCartObject(request);

    // safety check for missing required parameter.
    if (cart.getWebSiteId() == null) {
      cart.setWebSiteId(WebSiteWorker.getWebSiteId(request));
    }

    // locate the user's identity
    GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
    if (userLogin == null) {
      userLogin = (GenericValue) session.getAttribute("autoUserLogin");
    }

    // find the list ID
    String autoSaveListId = cart.getAutoSaveListId();
    if (autoSaveListId == null) {
      try {
        autoSaveListId =
            getAutoSaveListId(delegator, dispatcher, null, userLogin, cart.getProductStoreId());
      } catch (GeneralException e) {
        Debug.logError(e, module);
      }
      cart.setAutoSaveListId(autoSaveListId);
    } else if (userLogin != null) {
      String existingAutoSaveListId = null;
      try {
        existingAutoSaveListId =
            getAutoSaveListId(delegator, dispatcher, null, userLogin, cart.getProductStoreId());
      } catch (GeneralException e) {
        Debug.logError(e, module);
      }
      if (existingAutoSaveListId != null) {
        if (!existingAutoSaveListId.equals(autoSaveListId)) {
          // Replace with existing shopping list
          cart.setAutoSaveListId(existingAutoSaveListId);
          autoSaveListId = existingAutoSaveListId;
          cart.setLastListRestore(null);
        } else {
          // CASE: User first login and logout and then re-login again. This condition does not
          // require a restore at all
          // because at this point items in the cart and the items in the shopping list are same so
          // just return.
          return "success";
        }
      }
    }

    // check to see if we are okay to load this list
    java.sql.Timestamp lastLoad = cart.getLastListRestore();
    boolean okayToLoad = autoSaveListId == null ? false : (lastLoad == null ? true : false);
    if (!okayToLoad && lastLoad != null) {
      GenericValue shoppingList = null;
      try {
        shoppingList =
            EntityQuery.use(delegator)
                .from("ShoppingList")
                .where("shoppingListId", autoSaveListId)
                .queryOne();
      } catch (GenericEntityException e) {
        Debug.logError(e, module);
      }
      if (shoppingList != null) {
        java.sql.Timestamp lastModified = shoppingList.getTimestamp("lastAdminModified");
        if (lastModified != null) {
          if (lastModified.after(lastLoad)) {
            okayToLoad = true;
          }
          if (cart.size() == 0 && lastModified.after(cart.getCartCreatedTime())) {
            okayToLoad = true;
          }
        }
      }
    }

    // load (restore) the list of we have determined it is okay to load
    if (okayToLoad) {
      String prodCatalogId = CatalogWorker.getCurrentCatalogId(request);
      try {
        addListToCart(
            delegator,
            dispatcher,
            cart,
            prodCatalogId,
            autoSaveListId,
            false,
            false,
            userLogin != null ? true : false);
        cart.setLastListRestore(UtilDateTime.nowTimestamp());
      } catch (IllegalArgumentException e) {
        Debug.logError(e, module);
      }
    }

    return "success";
  }