protected void validate(MemberRequest memberRequest, long userId) throws PortalException {

    if (memberRequest.getStatus() != InviteMembersConstants.STATUS_PENDING) {

      throw new MemberRequestAlreadyUsedException();
    } else if (memberRequest.getReceiverUserId() != userId) {
      throw new MemberRequestInvalidUserException();
    }
  }
  public MemberRequest updateMemberRequest(String key, long receiverUserId)
      throws PortalException, SystemException {

    MemberRequest memberRequest = memberRequestPersistence.findByKey(key);

    validate(memberRequest, 0);

    memberRequest.setModifiedDate(new Date());
    memberRequest.setReceiverUserId(receiverUserId);

    memberRequestPersistence.update(memberRequest, false);

    return memberRequest;
  }
  /**
   * Adds the member request to the database. Also notifies the appropriate model listeners.
   *
   * @param memberRequest the member request
   * @return the member request that was added
   */
  @Indexable(type = IndexableType.REINDEX)
  @Override
  public MemberRequest addMemberRequest(MemberRequest memberRequest) {
    memberRequest.setNew(true);

    return memberRequestPersistence.update(memberRequest);
  }
  protected void sendNotificationEvent(MemberRequest memberRequest)
      throws PortalException, SystemException {

    JSONObject notificationEventJSONObject = JSONFactoryUtil.createJSONObject();

    notificationEventJSONObject.put("groupId", memberRequest.getGroupId());
    notificationEventJSONObject.put("memberRequestId", memberRequest.getMemberRequestId());
    notificationEventJSONObject.put("portletId", PortletKeys.SO_INVITE_MEMBERS);
    notificationEventJSONObject.put("title", "x-invited-you-to-join-x");
    notificationEventJSONObject.put("userId", memberRequest.getUserId());

    NotificationEvent notificationEvent =
        NotificationEventFactoryUtil.createNotificationEvent(
            System.currentTimeMillis(), PortletKeys.SO_NOTIFICATION, notificationEventJSONObject);

    notificationEvent.setDeliveryRequired(0);

    ChannelHubManagerUtil.sendNotificationEvent(
        memberRequest.getCompanyId(), memberRequest.getReceiverUserId(), notificationEvent);
  }
  @Override
  public boolean equals(Object obj) {
    if (obj == null) {
      return false;
    }

    MemberRequest memberRequest = null;

    try {
      memberRequest = (MemberRequest) obj;
    } catch (ClassCastException cce) {
      return false;
    }

    long primaryKey = memberRequest.getPrimaryKey();

    if (getPrimaryKey() == primaryKey) {
      return true;
    } else {
      return false;
    }
  }
  public int compareTo(MemberRequest memberRequest) {
    int value = 0;

    value = DateUtil.compareTo(getCreateDate(), memberRequest.getCreateDate());

    value = value * -1;

    if (value != 0) {
      return value;
    }

    return 0;
  }
  public MemberRequest addMemberRequest(
      long userId,
      long groupId,
      long receiverUserId,
      String receiverEmailAddress,
      long invitedRoleId,
      long invitedTeamId,
      ThemeDisplay themeDisplay)
      throws PortalException, SystemException {

    User user = userLocalService.getUserById(userId);

    Date now = new Date();

    long memberRequestId = counterLocalService.increment();

    MemberRequest memberRequest = memberRequestPersistence.create(memberRequestId);

    memberRequest.setGroupId(groupId);
    memberRequest.setCompanyId(user.getCompanyId());
    memberRequest.setUserId(userId);
    memberRequest.setUserName(user.getFullName());
    memberRequest.setCreateDate(now);
    memberRequest.setModifiedDate(now);
    memberRequest.setKey(PortalUUIDUtil.generate());
    memberRequest.setReceiverUserId(receiverUserId);
    memberRequest.setInvitedRoleId(invitedRoleId);
    memberRequest.setInvitedTeamId(invitedTeamId);
    memberRequest.setStatus(InviteMembersConstants.STATUS_PENDING);

    memberRequestPersistence.update(memberRequest, false);

    // Email

    try {
      sendEmail(receiverEmailAddress, memberRequest, themeDisplay);
    } catch (Exception e) {
      throw new SystemException(e);
    }

    return memberRequest;
  }
  protected void sendEmail(
      String emailAddress, MemberRequest memberRequest, ThemeDisplay themeDisplay)
      throws Exception {

    long companyId = memberRequest.getCompanyId();

    Group group = groupLocalService.getGroup(memberRequest.getGroupId());

    User user = userLocalService.getUser(memberRequest.getUserId());

    User receiverUser = null;

    if (memberRequest.getReceiverUserId() > 0) {
      receiverUser = userLocalService.getUser(memberRequest.getReceiverUserId());
    }

    String fromName = PrefsPropsUtil.getString(companyId, "admin.email.from.name");
    String fromAddress = PrefsPropsUtil.getString(companyId, "admin.email.from.address");

    String toName = StringPool.BLANK;
    String toAddress = emailAddress;

    if (receiverUser != null) {
      toName = receiverUser.getFullName();
    }

    ClassLoader classLoader = getClass().getClassLoader();

    String subject =
        StringUtil.read(classLoader, "com/liferay/so/invitemembers/dependencies/subject.tmpl");

    String body = StringPool.BLANK;

    if (memberRequest.getReceiverUserId() > 0) {
      body =
          StringUtil.read(
              classLoader,
              "com/liferay/so/invitemembers/dependencies/" + "existing_user_body.tmpl");
    } else {
      body =
          StringUtil.read(
              classLoader, "com/liferay/so/invitemembers/dependencies/" + "new_user_body.tmpl");
    }

    String createAccountURL = getCreateAccountURL(memberRequest.getKey(), themeDisplay);
    String loginURL = getLoginURL(memberRequest.getKey(), themeDisplay);

    subject =
        StringUtil.replace(
            subject,
            new String[] {"[$MEMBER_REQUEST_GROUP$]", "[$MEMBER_REQUEST_USER$]"},
            new String[] {group.getDescriptiveName(), user.getFullName()});

    body =
        StringUtil.replace(
            body,
            new String[] {
              "[$ADMIN_ADDRESS$]",
              "[$ADMIN_NAME$]",
              "[$MEMBER_REQUEST_CREATE_ACCOUNT_URL$]",
              "[$MEMBER_REQUEST_GROUP$]",
              "[$MEMBER_REQUEST_LOGIN_URL$]",
              "[$MEMBER_REQUEST_USER$]"
            },
            new String[] {
              fromAddress,
              fromName,
              createAccountURL,
              group.getDescriptiveName(),
              loginURL,
              user.getFullName()
            });

    InternetAddress from = new InternetAddress(fromAddress, fromName);

    InternetAddress to = new InternetAddress(toAddress, toName);

    MailMessage mailMessage = new MailMessage(from, to, subject, body, true);

    MailServiceUtil.sendEmail(mailMessage);
  }
  public MemberRequest updateMemberRequest(long userId, long memberRequestId, int status)
      throws Exception {

    MemberRequest memberRequest = memberRequestPersistence.findByPrimaryKey(memberRequestId);

    validate(memberRequest, userId);

    memberRequest.setModifiedDate(new Date());
    memberRequest.setStatus(status);

    memberRequestPersistence.update(memberRequest, false);

    if (status == InviteMembersConstants.STATUS_ACCEPTED) {
      userLocalService.addGroupUsers(
          memberRequest.getGroupId(), new long[] {memberRequest.getReceiverUserId()});

      if (memberRequest.getInvitedRoleId() > 0) {
        userGroupRoleLocalService.addUserGroupRoles(
            new long[] {memberRequest.getReceiverUserId()},
            memberRequest.getGroupId(),
            memberRequest.getInvitedRoleId());
      }

      if (memberRequest.getInvitedTeamId() > 0) {
        userLocalService.addTeamUsers(
            memberRequest.getInvitedTeamId(), new long[] {memberRequest.getReceiverUserId()});
      }
    }

    return memberRequest;
  }
  protected void sendEmail(
      String emailAddress, MemberRequest memberRequest, ServiceContext serviceContext)
      throws Exception {

    long companyId = memberRequest.getCompanyId();

    Group group = groupLocalService.getGroup(memberRequest.getGroupId());

    User user = userLocalService.getUser(memberRequest.getUserId());

    User receiverUser = null;

    if (memberRequest.getReceiverUserId() > 0) {
      receiverUser = userLocalService.getUser(memberRequest.getReceiverUserId());
    }

    String fromName = PrefsPropsUtil.getString(companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
    String fromAddress = PrefsPropsUtil.getString(companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);

    String toName = StringPool.BLANK;
    String toAddress = emailAddress;

    if (receiverUser != null) {
      toName = receiverUser.getFullName();
    }

    String subject =
        StringUtil.read(getClassLoader(), "com/liferay/so/invitemembers/dependencies/subject.tmpl");

    String body = StringPool.BLANK;

    if (memberRequest.getReceiverUserId() > 0) {
      body =
          StringUtil.read(
              getClassLoader(),
              "com/liferay/so/invitemembers/dependencies/" + "existing_user_body.tmpl");
    } else {
      body =
          StringUtil.read(
              getClassLoader(),
              "com/liferay/so/invitemembers/dependencies/" + "new_user_body.tmpl");
    }

    subject =
        StringUtil.replace(
            subject,
            new String[] {"[$MEMBER_REQUEST_GROUP$]", "[$MEMBER_REQUEST_USER$]"},
            new String[] {
              group.getDescriptiveName(serviceContext.getLocale()), user.getFullName()
            });

    String createAccountURL = (String) serviceContext.getAttribute("createAccountURL");

    if (Validator.isNull(createAccountURL)) {
      createAccountURL = serviceContext.getPortalURL();
    }

    createAccountURL = HttpUtil.addParameter(createAccountURL, "key", memberRequest.getKey());

    String loginURL = (String) serviceContext.getAttribute("loginURL");

    if (Validator.isNull(loginURL)) {
      loginURL = serviceContext.getPortalURL();
    }

    loginURL = HttpUtil.addParameter(loginURL, "key", memberRequest.getKey());

    body =
        StringUtil.replace(
            body,
            new String[] {
              "[$ADMIN_ADDRESS$]",
              "[$ADMIN_NAME$]",
              "[$MEMBER_REQUEST_CREATE_ACCOUNT_URL$]",
              "[$MEMBER_REQUEST_GROUP$]",
              "[$MEMBER_REQUEST_LOGIN_URL$]",
              "[$MEMBER_REQUEST_USER$]"
            },
            new String[] {
              fromAddress,
              fromName,
              createAccountURL,
              group.getDescriptiveName(serviceContext.getLocale()),
              loginURL,
              user.getFullName()
            });

    InternetAddress from = new InternetAddress(fromAddress, fromName);

    InternetAddress to = new InternetAddress(toAddress, toName);

    MailMessage mailMessage = new MailMessage(from, to, subject, body, true);

    MailServiceUtil.sendEmail(mailMessage);
  }