public List <Attendee> Attendees(int locationId) { try { RockContext rockContext = new RockContext(); AttendanceService attendanceService = new AttendanceService(rockContext); PersonAliasService personAliasService = new PersonAliasService(rockContext); List <Attendee> attendees = attendanceService .Queryable().AsNoTracking() .Where(a => a.LocationId == locationId && a.StartDateTime >= Rock.RockDateTime.Today) .Join(personAliasService.Queryable(), a => a.PersonAliasId, pa => pa.Id, (a, pa) => new Attendee() { AttendanceGuid = a.Guid, DidAttend = a.DidAttend ?? false, CheckedOut = a.EndDateTime != null, PersonId = pa.PersonId, PersonName = pa.Person.FullName }) .OrderBy(a => a.PersonName) .ToList(); return(attendees); } catch (Exception e) { ExceptionLogService.LogException(e, System.Web.HttpContext.Current); return(new List <Attendee>()); } }
/// <summary> /// Handles the Delete event of the gFollowings control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param> protected void gFollowings_Delete(object sender, RowEventArgs e) { var rockContext = new RockContext(); var personAliasService = new PersonAliasService(rockContext); var followingService = new FollowingService(rockContext); var paQry = personAliasService.Queryable() .Where(p => p.PersonId == e.RowKeyId) .Select(p => p.Id); int personAliasEntityTypeId = EntityTypeCache.Read("Rock.Model.PersonAlias").Id; foreach (var following in followingService.Queryable() .Where(f => f.EntityTypeId == personAliasEntityTypeId && paQry.Contains(f.EntityId) && f.PersonAliasId == CurrentPersonAlias.Id)) { followingService.Delete(following); } rockContext.SaveChanges(); BindGrid(); }
/// <summary> /// Gets the interaction dates. /// </summary> /// <param name="achievementTypeCache">The achievementTypeCache.</param> /// <param name="personAliasId">The person alias identifier.</param> /// <param name="minDate">The minimum date.</param> /// <param name="maxDate">The maximum date.</param> /// <returns></returns> private List <DateTime> GetInteractionDatesByPerson(AchievementTypeCache achievementTypeCache, int personAliasId, DateTime minDate, DateTime maxDate) { var rockContext = new RockContext(); var query = GetSourceEntitiesQuery(achievementTypeCache, rockContext) as IQueryable <Interaction>; var dayAfterMaxDate = maxDate.AddDays(1); var personAliasService = new PersonAliasService(rockContext); var personAliasQuery = personAliasService .Queryable() .AsNoTracking() .Where(pa => pa.Id == personAliasId) .SelectMany(pa => pa.Person.Aliases) .Select(pa => pa.Id); return(query .AsNoTracking() .Where(i => i.PersonAliasId.HasValue && personAliasQuery.Contains(i.PersonAliasId.Value) && i.InteractionDateTime >= minDate && i.InteractionDateTime < dayAfterMaxDate) .Select(i => i.InteractionDateTime) .ToList() .OrderBy(d => d) .ToList()); }
/// <summary> /// Handles the Click event of the lbUnfollow control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> void lbUnfollow_Click(object sender, EventArgs e) { var itemsSelected = new List <int>(); gFollowings.SelectedKeys.ToList().ForEach(f => itemsSelected.Add(f.ToString().AsInteger())); if (itemsSelected.Any()) { var rockContext = new RockContext(); var personAliasService = new PersonAliasService(rockContext); var followingService = new FollowingService(rockContext); var paQry = personAliasService.Queryable() .Where(p => itemsSelected.Contains(p.PersonId)) .Select(p => p.Id); int personAliasEntityTypeId = EntityTypeCache.Get("Rock.Model.PersonAlias").Id; foreach (var following in followingService.Queryable() .Where(f => f.EntityTypeId == personAliasEntityTypeId && paQry.Contains(f.EntityId) && f.PersonAliasId == CurrentPersonAlias.Id)) { followingService.Delete(following); } rockContext.SaveChanges(); } BindGrid(); }
private void SetFollowing() { var personAliasEntityType = EntityTypeCache.Read("Rock.Model.PersonAlias"); if (Person != null && CurrentPersonId.HasValue && CurrentPersonAlias != null && personAliasEntityType != null) { using (var rockContext = new RockContext()) { var personAliasService = new PersonAliasService(rockContext); var followingService = new FollowingService(rockContext); var paQry = personAliasService.Queryable() .Where(p => p.PersonId == Person.Id) .Select(p => p.Id); if (followingService.Queryable() .Where(f => f.EntityTypeId == personAliasEntityType.Id && paQry.Contains(f.EntityId) && f.PersonAlias.PersonId == CurrentPersonId) .Any()) { pnlFollow.AddCssClass("following"); } else { pnlFollow.RemoveCssClass("following"); } } string script = string.Format(@" $('.following-status').click(function () {{ var $followingDiv = $(this); if ($followingDiv.hasClass('following')) {{ $.ajax({{ type: 'DELETE', url: Rock.settings.get('baseUrl') + 'api/followings/{0}/{1}/{2}', success: function(data, status, xhr){{ $followingDiv.removeClass('following'); }}, }}); }} else {{ var following = {{ EntityTypeId:{0}, EntityId:{1}, PersonAliasId:{3} }}; $.ajax({{ type: 'POST', contentType: 'application/json', data: JSON.stringify(following), url: Rock.settings.get('baseUrl') + 'api/followings', statusCode: {{ 201: function () {{ $followingDiv.addClass('following'); }} }} }}); }} }}); ", personAliasEntityType.Id, Person.PrimaryAliasId, CurrentPersonId.Value, CurrentPersonAlias.Id); ScriptManager.RegisterStartupScript(lImage, lImage.GetType(), "following", script, true); } }
protected void SetPersonAliasAttribute(Workflow workflow, IQueryable <asgn_assignment_field_value> fieldValues, string key) { var aliasId = fieldValues.Where(v => v.custom_field_id == attributeMap.Where(am => am.Value == key).First().Key).Select(v => v.selected_value).FirstOrDefault().AsIntegerOrNull(); if (aliasId.HasValue) { workflow.SetAttributeValue(key, personAliasService.Queryable().Where(p => p.AliasPersonId == aliasId).Select(p => p.Guid).FirstOrDefault()); } }
/// <summary> /// Validates that the args do not seem to be a repeat charge on the same person in a short timeframe. /// Entities are loaded from supplied IDs where applicable to ensure existence and a valid state. /// </summary> /// <param name="errorMessage">Will be set to empty string if charge does not seem repeated. Otherwise a message will be set indicating the problem.</param> /// <returns>True if the charge is a repeat. False otherwise.</returns> public bool IsRepeatCharge(out string errorMessage) { errorMessage = string.Empty; if (!_enableDuplicateChecking) { return(false); } // Since an instance of this class should be used per transaction, and because the args cannot be changed after the // instantiation, we can "cache" the result of this function. This function is public so other code can call it explicitly, // and it is also called during the actual charge method, which means it is very likely to be called multiple times. if (_isRepeatCharge.HasValue) { errorMessage = _isRepeatChargeErrorMessage; return(_isRepeatCharge.Value); } LoadEntities(); // Get all the person aliases in the giving group var personAliasIdQuery = _personAliasService.Queryable() .AsNoTracking() .Where(a => a.Person.GivingId == _authorizedPerson.GivingId) .Select(a => a.Id); // Check to see if a transaction exists for the person aliases within the last 5 minutes. This should help eliminate accidental repeat charges. var minDateTime = RockDateTime.Now.AddMinutes(-5); var recentTransactionQuery = _financialTransactionService.Queryable() .AsNoTracking() .Include(t => t.TransactionDetails) .Where(t => // Check for transactions in the giving group t.AuthorizedPersonAliasId.HasValue && personAliasIdQuery.Contains(t.AuthorizedPersonAliasId.Value) && // Check for recent transactions (t.TransactionDateTime >= minDateTime || t.FutureProcessingDateTime >= minDateTime)) .ToList(); // Look for a recent transaction that has the same account/amount combinations var repeatTransaction = recentTransactionQuery.FirstOrDefault(t => t.TransactionDetails.All(d => _automatedPaymentArgs.AutomatedPaymentDetails.Any(ad => ad.AccountId == d.AccountId && ad.Amount == d.Amount))); if (repeatTransaction != null) { errorMessage = string.Format("Found a likely repeat charge. Check transaction id: {0}. Toggle EnableDuplicateChecking to disable this protection.", repeatTransaction.Id); _isRepeatCharge = true; } else { _isRepeatCharge = false; } _isRepeatChargeErrorMessage = errorMessage; return(_isRepeatCharge.Value); }
/// <summary> /// Does cleanup of Person Aliases and Metaphones /// </summary> /// <param name="dataMap">The data map.</param> private void PersonCleanup(JobDataMap dataMap) { // Add any missing person aliases var personRockContext = new Rock.Data.RockContext(); PersonService personService = new PersonService(personRockContext); PersonAliasService personAliasService = new PersonAliasService(personRockContext); var personAliasServiceQry = personAliasService.Queryable(); foreach (var person in personService.Queryable("Aliases") .Where(p => !p.Aliases.Any() && !personAliasServiceQry.Any(pa => pa.AliasPersonId == p.Id)) .Take(300)) { person.Aliases.Add(new PersonAlias { AliasPersonId = person.Id, AliasPersonGuid = person.Guid }); } personRockContext.SaveChanges(); // Add any missing metaphones int namesToProcess = dataMap.GetString("MaxMetaphoneNames").AsInteger(); if (namesToProcess > 0) { var firstNameQry = personService.Queryable().Select(p => p.FirstName).Where(p => p != null); var nickNameQry = personService.Queryable().Select(p => p.NickName).Where(p => p != null); var lastNameQry = personService.Queryable().Select(p => p.LastName).Where(p => p != null); var nameQry = firstNameQry.Union(nickNameQry.Union(lastNameQry)); var metaphones = personRockContext.Metaphones; var existingNames = metaphones.Select(m => m.Name).Distinct(); // Get the names that have not yet been processed var namesToUpdate = nameQry .Where(n => !existingNames.Contains(n)) .Take(namesToProcess) .ToList(); foreach (string name in namesToUpdate) { string mp1 = string.Empty; string mp2 = string.Empty; Rock.Utility.DoubleMetaphone.doubleMetaphone(name, ref mp1, ref mp2); var metaphone = new Metaphone(); metaphone.Name = name; metaphone.Metaphone1 = mp1; metaphone.Metaphone2 = mp2; metaphones.Add(metaphone); } personRockContext.SaveChanges(); } }
/// <summary> /// Delete the test data /// </summary> private static void DeleteTestData() { using (var rockContext = new RockContext()) { var stepService = new StepService(rockContext); var stepQuery = stepService.Queryable().Where(s => s.ForeignKey == ForeignKey); stepService.DeleteRange(stepQuery); rockContext.SaveChanges(); } using (var rockContext = new RockContext()) { var stepProgramService = new StepProgramService(rockContext); var stepProgramQuery = stepProgramService.Queryable().Where(sp => sp.ForeignKey == ForeignKey); stepProgramService.DeleteRange(stepProgramQuery); rockContext.SaveChanges(); } using (var rockContext = new RockContext()) { var personSearchKeyService = new PersonSearchKeyService(rockContext); var personSearchKeyQuery = personSearchKeyService.Queryable() .Where(psk => psk.PersonAlias.Person.ForeignKey == ForeignKey || PersonGuids.Contains(psk.PersonAlias.Person.Guid)); personSearchKeyService.DeleteRange(personSearchKeyQuery); rockContext.SaveChanges(); } using (var rockContext = new RockContext()) { var personAliasService = new PersonAliasService(rockContext); var personAliasQuery = personAliasService.Queryable() .Where(pa => pa.Person.ForeignKey == ForeignKey || PersonGuids.Contains(pa.Person.Guid)); personAliasService.DeleteRange(personAliasQuery); rockContext.SaveChanges(); } using (var rockContext = new RockContext()) { var personService = new PersonService(rockContext); var personQuery = personService.Queryable() .Where(p => p.ForeignKey == ForeignKey || PersonGuids.Contains(p.Guid)); personService.DeleteRange(personQuery); rockContext.SaveChanges(); } }
public static IQueryable <PersonAlias> FindNotYetSyncedPersonAlises(RockContext rockContext, IQueryable <int> syncedPersonAliasIds) { var personAliasService = new PersonAliasService(rockContext); var personAlises = personAliasService .Queryable() .AsNoTracking() .Where( a => !syncedPersonAliasIds.Contains(a.Id) && a.Person.IsEmailActive && a.Person.Email != null && a.Person.Email != "" && a.Person.EmailPreference == EmailPreference.EmailAllowed); return(personAlises); }
public AttendanceCodes GetAttendanceCode(string attendanceGuid) { try { Guid guid = attendanceGuid.AsGuid(); RockContext rockContext = new RockContext(); var attendanceService = new AttendanceService(rockContext); var primaryAttendance = attendanceService.Get(guid); if (primaryAttendance == null) { return(null); } var personAliasService = new PersonAliasService(rockContext); var person = primaryAttendance.PersonAlias.Person; var personAliasIds = personAliasService.Queryable() .Where(pa => pa.PersonId == primaryAttendance.PersonAlias.PersonId) .Select(pa => pa.Id); var today = Rock.RockDateTime.Today; var tomorrow = today.AddDays(1); var codes = attendanceService.Queryable() .Where(a => personAliasIds.Contains(a.PersonAliasId ?? 0) && a.StartDateTime >= today && a.StartDateTime < tomorrow) .Select(a => a.AttendanceCode) .Select(ac => ac.Code) .DistinctBy(c => c) .ToList(); return(new AttendanceCodes() { NickName = person.NickName, LastName = person.LastName, Codes = codes }); } catch (Exception e) { ExceptionLogService.LogException(e, System.Web.HttpContext.Current); return(new AttendanceCodes() { Codes = new List <string>() }); } }
private Person GetPersonAliasFromActionAttribute(string key, RockContext rockContext, WorkflowAction action, List <string> errorMessages) { string value = GetAttributeValue(action, key); Guid guidPersonAttribute = value.AsGuid(); if (guidPersonAttribute.IsEmpty()) { return(null); } var attributePerson = AttributeCache.Get(guidPersonAttribute, rockContext); if (attributePerson == null) { return(null); } string attributePersonValue = action.GetWorkflowAttributeValue(guidPersonAttribute); if (string.IsNullOrWhiteSpace(attributePersonValue)) { return(null); } if (attributePerson.FieldType.Class != "Rock.Field.Types.PersonFieldType") { errorMessages.Add($"The attribute used for {key} to provide the person was not of type 'Person'."); return(null); } Guid personAliasGuid = attributePersonValue.AsGuid(); if (personAliasGuid.IsEmpty()) { errorMessages.Add($"Person could not be found for selected value ('{guidPersonAttribute}')!"); return(null); } PersonAliasService personAliasService = new PersonAliasService(rockContext); return(personAliasService.Queryable().AsNoTracking() .Where(a => a.Guid.Equals(personAliasGuid)) .Select(a => a.Person) .FirstOrDefault()); }
/// <summary> /// Get a lookup table to convert a Person.Guid to a PersonAlias.Id /// </summary> /// <param name="dataContext"></param> /// <returns></returns> private Dictionary <Guid, int> GetPersonGuidToAliasIdMap(RockContext dataContext) { if (_PersonGuidToAliasIdMap == null) { var aliasService = new PersonAliasService(dataContext); var personList = aliasService.Queryable() .AsNoTracking() .Where(x => !x.Person.IsSystem) .Take(_MaxRecipientCount) .GroupBy(x => x.Person.Guid) .ToDictionary(k => k.Key, v => v.First().Id); _PersonGuidToAliasIdMap = personList; } return(_PersonGuidToAliasIdMap); }
/// <summary> /// Validates that the args do not seem to be a repeat charge on the same person in a short timeframe. /// Entities are loaded from supplied IDs where applicable to ensure existence and a valid state. /// </summary> /// <param name="errorMessage">Will be set to empty string if charge does not seem repeated. Otherwise a message will be set indicating the problem.</param> /// <returns>True if the charge is a repeat. False otherwise.</returns> public bool IsRepeatCharge(out string errorMessage) { errorMessage = string.Empty; if (!_enableDuplicateChecking) { return(false); } LoadEntities(); // Get all the person aliases in the giving group var personAliasIds = _personAliasService.Queryable() .AsNoTracking() .Where(a => a.Person.GivingId == _authorizedPerson.GivingId) .Select(a => a.Id) .ToList(); // Check to see if a transaction exists for the person aliases within the last 5 minutes. This should help eliminate accidental repeat charges. var minDateTime = RockDateTime.Now.AddMinutes(-5); var recentTransactions = _financialTransactionService.Queryable() .AsNoTracking() .Include(t => t.TransactionDetails) .Where(t => // Check for transactions in the giving group t.AuthorizedPersonAliasId.HasValue && personAliasIds.Contains(t.AuthorizedPersonAliasId.Value) && // Check for recent transactions (t.TransactionDateTime >= minDateTime || t.FutureProcessingDateTime >= minDateTime)) .ToList(); // Look for a recent transaction that has the same account/amount combinations var repeatTransaction = recentTransactions.FirstOrDefault(t => t.TransactionDetails.All(d => _automatedPaymentArgs.AutomatedPaymentDetails.Any(ad => ad.AccountId == d.AccountId && ad.Amount == d.Amount))); if (repeatTransaction != null) { errorMessage = string.Format("Found a likely repeat charge. Check transaction id: {0}. Toggle EnableDuplicateChecking to disable this protection.", repeatTransaction.Id); return(true); } return(false); }
/// <summary> /// Gets a list of the Id and AliasId of all Person records in the database /// </summary> /// <param name="dataContext"></param> /// <returns></returns> public static List <PersonIdPersonAliasId> GetPersonIdWithAliasIdList() { if (_PersonIdToAliasIdMap == null) { var aliasService = new PersonAliasService(new RockContext()); _PersonIdToAliasIdMap = aliasService.Queryable() .Where(x => !x.Person.IsSystem) .GroupBy(x => x.PersonId) .Select(a => new PersonIdPersonAliasId { PersonId = a.Key, PersonAliasId = a.FirstOrDefault().Id }) .ToList(); } return(_PersonIdToAliasIdMap); }
/// <summary> /// Gets the achiever attempt query. This is the query (not enumerated) that joins attempts of this achievement type with the /// achiever entities, as well as the name (<see cref="AchieverAttemptItem.AchieverName"/> that could represent the achiever /// in a grid or other such display. /// </summary> /// <param name="achievementTypeCache">The achievement type cache.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> public override IQueryable <AchieverAttemptItem> GetAchieverAttemptQuery(AchievementTypeCache achievementTypeCache, RockContext rockContext) { var attemptService = new AchievementAttemptService(rockContext); var personAliasService = new PersonAliasService(rockContext); var attemptQuery = attemptService.Queryable().Where(aa => aa.AchievementTypeId == achievementTypeCache.Id); var personAliasQuery = personAliasService.Queryable(); return(attemptQuery.Join( personAliasQuery, aa => aa.AchieverEntityId, pa => pa.Id, (aa, pa) => new AchieverAttemptItem { AchievementAttempt = aa, Achiever = pa, AchieverName = pa.Person.NickName + " " + pa.Person.LastName })); }
/// <summary> /// Validates the request data. /// </summary> /// <param name="context">The context.</param> /// <returns></returns> private CalendarProps ValidateRequestData(HttpContext httpContext) { CalendarProps calendarProps = new CalendarProps(); Guid?personAliasGuid = httpContext.Request.QueryString["paguid"].AsGuidOrNull(); if (personAliasGuid == null) { SendBadRequest(httpContext); return(null); } using (var rockContext = new RockContext()) { var personAliasService = new PersonAliasService(rockContext); int?personId = personAliasService.Queryable().AsNoTracking().Where(pa => pa.Guid == personAliasGuid).Select(pa => pa.PersonId).Cast <int?>().FirstOrDefault(); if (personId == null) { SendBadRequest(httpContext); return(null); } calendarProps.PersonId = personId.Value; } string startDate = httpContext.Request.QueryString["startdate"]; if (!string.IsNullOrWhiteSpace(startDate)) { calendarProps.StartDate = DateTime.ParseExact(startDate, "yyyyMMdd", CultureInfo.InvariantCulture); } string endDate = httpContext.Request.QueryString["enddate"]; if (!string.IsNullOrWhiteSpace(endDate)) { calendarProps.EndDate = DateTime.ParseExact(endDate, "yyyyMMdd", CultureInfo.InvariantCulture); } return(calendarProps); }
private void Actions_CommunicateClick(object sender, EventArgs e) { var rockPage = Page as RockPage; BindGrid(); var redirectUrl = rockPage.Response.Output.ToString(); if (redirectUrl != null) { Regex rgx = new Regex(".*/(\\d*)"); string result = rgx.Replace(redirectUrl, "$1"); var recipients = GetDuplicatePersonData(); if (recipients.Any()) { // Create communication var communicationRockContext = new RockContext(); var communicationService = new CommunicationService(communicationRockContext); var communicationRecipientService = new CommunicationRecipientService(communicationRockContext); var personAliasService = new PersonAliasService(communicationRockContext); var communication = communicationService.Queryable().Where(c => c.SenderPersonAliasId == rockPage.CurrentPersonAliasId).OrderByDescending(c => c.Id).FirstOrDefault(); communication.IsBulkCommunication = false; foreach (var recipient in recipients) { PersonAlias a = personAliasService.Queryable().Where(p => p.PersonId == p.AliasPersonId && p.PersonId == recipient.Key).FirstOrDefault(); var communicationRecipient = new CommunicationRecipient { CommunicationId = communication.Id, PersonAliasId = a.Id, AdditionalMergeValues = recipient.Value }; communicationRecipientService.Add(communicationRecipient); communicationRockContext.SaveChanges(); } } } }
public virtual List <ProgressStatement> GetProgressForPerson([FromUri] int personId = default, [FromUri] bool includeOnlyEligible = default) { var rockContext = Service.Context as RockContext; var personAliasId = default(int); // If not specified, use the current person id if (personId != default) { var personAliasService = new PersonAliasService(rockContext); personAliasId = personAliasService.Queryable().AsNoTracking().FirstOrDefault(pa => pa.PersonId == personId)?.Id ?? default; if (personAliasId == default) { var errorResponse = ControllerContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"The personAliasId for the person with id {personId} did not resolve"); throw new HttpResponseException(errorResponse); } } var personAliasEntityTypeId = EntityTypeCache.Get <PersonAlias>().Id; return(GetProgressForAchiever(personAliasEntityTypeId, personAliasId, includeOnlyEligible)); }
/// <summary> /// Delete the test data /// </summary> private static void DeleteTestData() { var rockContext = new RockContext(); var stepProgramService = new StepProgramService(rockContext); var stepProgramQuery = stepProgramService.Queryable().Where(sp => sp.ForeignKey == ForeignKey); stepProgramService.DeleteRange(stepProgramQuery); rockContext.SaveChanges(); var dataViewFilterService = new DataViewFilterService(rockContext); var dvfQuery = dataViewFilterService.Queryable().Where(dvf => dvf.DataView.ForeignKey == ForeignKey || dvf.ForeignKey == ForeignKey); dataViewFilterService.DeleteRange(dvfQuery); rockContext.SaveChanges(); var dataViewService = new DataViewService(rockContext); var dvQuery = dataViewService.Queryable().Where(dv => dv.ForeignKey == ForeignKey); dataViewService.DeleteRange(dvQuery); rockContext.SaveChanges(); var personSearchKeyService = new PersonSearchKeyService(rockContext); var personSearchKeyQuery = personSearchKeyService.Queryable().Where(psk => psk.PersonAlias.Person.ForeignKey == ForeignKey); personSearchKeyService.DeleteRange(personSearchKeyQuery); var personAliasService = new PersonAliasService(rockContext); var personAliasQuery = personAliasService.Queryable().Where(pa => pa.Person.ForeignKey == ForeignKey || pa.ForeignKey == ForeignKey); personAliasService.DeleteRange(personAliasQuery); rockContext.SaveChanges(); var personService = new PersonService(rockContext); var personQuery = personService.Queryable().Where(p => p.ForeignKey == ForeignKey); personService.DeleteRange(personQuery); rockContext.SaveChanges(); }
/// <summary> /// Gets the suggestions. /// </summary> /// <param name="followingSuggestionType">Type of the following suggestion.</param> /// <param name="followerPersonIds">The follower person ids.</param> /// <returns></returns> public override List <PersonEntitySuggestion> GetSuggestions(FollowingSuggestionType followingSuggestionType, List <int> followerPersonIds) { var suggestions = new List <PersonEntitySuggestion>(); var personAliasEntityType = EntityTypeCache.Read(typeof(Rock.Model.PersonAlias)); bool isAutoFollow = GetAttributeValue(followingSuggestionType, "AutoFollow").AsBoolean(); // Get the grouptype guid Guid?groupTypeGuid = GetAttributeValue(followingSuggestionType, "GroupType").AsGuidOrNull(); if (groupTypeGuid.HasValue) { using (var rockContext = new RockContext()) { var groupMemberService = new GroupMemberService(rockContext); var personAliasService = new PersonAliasService(rockContext); // Get all the groupmember records for any follower and the selected group type var followers = groupMemberService.Queryable().AsNoTracking() .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active && m.Group != null && m.Group.IsActive && m.Group.GroupType.Guid.Equals(groupTypeGuid.Value) && followerPersonIds.Contains(m.PersonId)); // If a specific group or security role was specifed, limit groupmembers to only those of the selected group Guid?groupGuid = GetAttributeValue(followingSuggestionType, "Group").AsGuidOrNull(); if (!groupGuid.HasValue) { groupGuid = GetAttributeValue(followingSuggestionType, "SecurityRole").AsGuidOrNull(); } if (groupGuid.HasValue) { followers = followers.Where(m => m.Group.Guid.Equals(groupGuid.Value)); } // If a specific role for the follower was specified, limit groupmembers to only those with the selected role Guid?followerRoleGuid = GetAttributeValue(followingSuggestionType, "FollowerGroupType").AsGuidOrNull(); if (followerRoleGuid.HasValue) { followers = followers.Where(m => m.GroupRole.Guid.Equals(followerRoleGuid.Value)); } // Run the query to get all the groups that follower is a member of with selected filters var followerPersonGroup = followers .Select(f => new { f.PersonId, f.GroupId }) .ToList(); // Get a unique list of any of the groups that followers belong to var followedGroupIds = followerPersonGroup .Select(f => f.GroupId) .Distinct() .ToList(); // Start building query to get the people to follow from any group that contains a follower var followed = groupMemberService .Queryable().AsNoTracking() .Where(m => followedGroupIds.Contains(m.GroupId)); // If a specific role for the people being followed was specified, limit the query to only those with the selected role Guid?followedRoleGuid = GetAttributeValue(followingSuggestionType, "FollowedGroupType").AsGuidOrNull(); if (followedRoleGuid.HasValue) { followed = followed.Where(m => m.GroupRole.Guid.Equals(followedRoleGuid.Value)); } // Get all the people in any of the groups that contain a follower var followedPersonGroup = followed .Select(f => new { f.PersonId, f.GroupId }) .ToList(); // Get distinct list of people var followedPersonIds = followedPersonGroup .Select(f => f.PersonId) .Distinct() .ToList(); // Build a dictionary of the personid->personaliasid var personAliasIds = new Dictionary <int, int>(); personAliasService.Queryable().AsNoTracking() .Where(a => followedPersonIds.Contains(a.PersonId) && a.PersonId == a.AliasPersonId) .ToList() .ForEach(a => personAliasIds.AddOrIgnore(a.PersonId, a.Id)); // Loop through each follower/group combination foreach (var followedGroup in followerPersonGroup) { // Loop through the other people in that group foreach (int followedPersonId in followedPersonGroup .Where(f => f.GroupId == followedGroup.GroupId && f.PersonId != followedGroup.PersonId) .Select(f => f.PersonId)) { // If the person has a valid personalias id if (personAliasIds.ContainsKey(followedPersonId)) { if (!isAutoFollow) { // add them to the list of suggestions suggestions.Add(new PersonEntitySuggestion(followedGroup.PersonId, personAliasIds[followedPersonId])); } else { // auto-add the follow var followingService = new FollowingService(rockContext); int followerPersonAliasId = personAliasIds[followedGroup.PersonId]; int followeePersonAliasId = personAliasIds[followedPersonId]; // if person is not already following the person bool isFollowing = followingService.Queryable().Where(f => f.EntityTypeId == personAliasEntityType.Id && f.EntityId == followeePersonAliasId && f.PersonAliasId == followerPersonAliasId).Any(); if (!isFollowing) { var following = new Following(); following.EntityTypeId = personAliasEntityType.Id; following.EntityId = personAliasIds[followedPersonId]; following.PersonAliasId = personAliasIds[followedGroup.PersonId]; followingService.Add(following); rockContext.SaveChanges(); } } } } } } } return(suggestions); }
/// <summary> /// Gets the suggestions. /// </summary> /// <param name="followingSuggestionType">Type of the following suggestion.</param> /// <param name="followerPersonIds">The follower person ids.</param> /// <returns></returns> public override List <PersonEntitySuggestion> GetSuggestions(FollowingSuggestionType followingSuggestionType, List <int> followerPersonIds) { var suggestions = new List <PersonEntitySuggestion>(); var groupEntityType = EntityTypeCache.Get(typeof(Rock.Model.Group)); var personAliasEntityType = EntityTypeCache.Get(typeof(Rock.Model.PersonAlias)); bool isAutoFollow = GetAttributeValue(followingSuggestionType, "AutoFollow").AsBoolean(); // Get the grouptype guid Guid?groupTypeGuid = GetAttributeValue(followingSuggestionType, "GroupType").AsGuidOrNull(); if (groupTypeGuid.HasValue) { using (var rockContext = new RockContext()) { var followingService = new FollowingService(rockContext); var groupMemberService = new GroupMemberService(rockContext); var personAliasService = new PersonAliasService(rockContext); var followings = followingService.Queryable() .Where(a => a.EntityTypeId == groupEntityType.Id && followerPersonIds.Contains(a.PersonAlias.PersonId)) .Select(f => new { f.PersonAliasId, f.PersonAlias.PersonId, f.EntityId }).Distinct() .ToList(); var followedGroup = followings.Select(a => a.EntityId).Distinct().ToList(); // Get all the groupmember records of Followed group var followedGroupMembersQry = groupMemberService.Queryable().AsNoTracking() .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active && m.Group != null && m.Group.IsActive && !m.Group.IsArchived && m.Group.GroupType.Guid.Equals(groupTypeGuid.Value) && followedGroup.Contains(m.GroupId)); // If a specific role for the people being followed was specified, limit the query to only those with the selected role Guid?groupRoleGuid = GetAttributeValue(followingSuggestionType, "GroupRole").AsGuidOrNull(); if (groupRoleGuid.HasValue) { followedGroupMembersQry = followedGroupMembersQry.Where(m => m.GroupRole.Guid.Equals(groupRoleGuid.Value)); } var followedGroupMembers = followedGroupMembersQry.ToList(); // Run the query to get all the groups that follower is a member of with selected filters var followerPersonGroups = followings .Select(f => new { GroupMembers = followedGroupMembers.Where(a => a.GroupId == f.EntityId).ToList(), f.PersonAliasId, f.PersonId }) .ToList(); var followedMembersList = followedGroupMembers .Select(a => a.PersonId) .Distinct() .ToList(); // Build a dictionary of the personid->personaliasid var personAliasIds = new Dictionary <int, int>(); personAliasService.Queryable().AsNoTracking() .Where(a => followedMembersList.Contains(a.PersonId) && a.PersonId == a.AliasPersonId) .ToList() .ForEach(a => personAliasIds.AddOrIgnore(a.PersonId, a.Id)); // Loop through each follower/group combination foreach (var followerPersonGroup in followerPersonGroups) { // Loop through the other people in that group foreach (var member in followerPersonGroup.GroupMembers) { if (!isAutoFollow) { // add them to the list of suggestions suggestions.Add(new PersonEntitySuggestion(followerPersonGroup.PersonId, personAliasIds[member.PersonId])); } else { // auto-add the follow int followeePersonAliasId = personAliasIds[member.PersonId]; // if person is not already following the person bool isFollowing = followingService.Queryable().Where(f => f.EntityTypeId == personAliasEntityType.Id && f.EntityId == followeePersonAliasId && f.PersonAliasId == followerPersonGroup.PersonAliasId).Any(); if (!isFollowing) { var following = new Following(); following.EntityTypeId = personAliasEntityType.Id; following.EntityId = followeePersonAliasId; following.PersonAliasId = followerPersonGroup.PersonAliasId; followingService.Add(following); rockContext.SaveChanges(); } } } } } } return(suggestions); }
/// <summary> /// Processes the giving journeys. /// </summary> internal void UpdateGivingJourneyStages() { var givingAnalyticsSetting = GivingAutomationSettings.LoadGivingAutomationSettings(); var rockContext = new RockContext(); rockContext.Database.CommandTimeout = this.SqlCommandTimeout; var personService = new PersonService(rockContext); // Limit to only Business and Person type records. // Include deceased to cover transactions that could have occurred when they were not deceased // or transactions that are dated after they were marked deceased. var personQuery = personService.Queryable(new PersonService.PersonQueryOptions { IncludeDeceased = true, IncludeBusinesses = true, IncludePersons = true, IncludeNameless = false, IncludeRestUsers = false }); var personAliasService = new PersonAliasService(rockContext); var personAliasQuery = personAliasService.Queryable(); var financialTransactionService = new FinancialTransactionService(rockContext); var financialTransactionGivingAnalyticsQuery = financialTransactionService.GetGivingAutomationSourceTransactionQuery(); if (OnProgress != null) { string progressMessage = "Calculating journey classifications..."; OnProgress.Invoke(this, new ProgressEventArgs(progressMessage)); } /* Get Non-Giver GivingIds */ var nonGiverGivingIdsQuery = personQuery.Where(p => !financialTransactionGivingAnalyticsQuery.Any(ft => personAliasQuery.Any(pa => pa.Id == ft.AuthorizedPersonAliasId && pa.Person.GivingId == p.GivingId))); var nonGiverGivingIdsList = nonGiverGivingIdsQuery.Select(a => a.GivingId).Distinct().ToList(); /* Get TransactionDateList for each GivingId in the system */ var transactionDateTimes = financialTransactionGivingAnalyticsQuery.Select(a => new { GivingId = personAliasQuery.Where(pa => pa.Id == a.AuthorizedPersonAliasId).Select(pa => pa.Person.GivingId).FirstOrDefault(), a.TransactionDateTime }).Where(a => a.GivingId != null).ToList(); var transactionDateTimesByGivingId = transactionDateTimes .GroupBy(g => g.GivingId) .Select(s => new { GivingId = s.Key, TransactionDateTimeList = s.Select(x => x.TransactionDateTime).ToList() }).ToDictionary(k => k.GivingId, v => v.TransactionDateTimeList); List <AttributeCache> journeyStageAttributesList = new List <AttributeCache> { _currentJourneyStageAttribute, _previousJourneyStageAttribute, _journeyStageChangeDateAttribute }; if (journeyStageAttributesList.Any(a => a == null)) { throw new Exception("Journey Stage Attributes are not installed correctly."); } var journeyStageAttributeIds = journeyStageAttributesList.Where(a => a != null).Select(a => a.Id).ToList(); var personCurrentJourneyAttributeValues = new AttributeValueService(rockContext).Queryable() .WhereAttributeIds(journeyStageAttributeIds) .Where(av => av.EntityId.HasValue) .Join( personQuery.Where(x => !string.IsNullOrEmpty(x.GivingId)), av => av.EntityId.Value, p => p.Id, (av, p) => new { AttributeId = av.AttributeId, AttributeValue = av.Value, PersonGivingId = p.GivingId, PersonId = p.Id }) .GroupBy(a => a.PersonGivingId) .Select(a => new { GivingId = a.Key, AttributeValues = a.ToList() }).ToDictionary(k => k.GivingId, v => v.AttributeValues); var givingJourneySettings = givingAnalyticsSetting.GivingJourneySettings; var currentDate = RockDateTime.Today; var formerGiverGivingIds = new List <string>(); var lapsedGiverGivingIds = new List <string>(); var newGiverGivingIds = new List <string>(); var occasionalGiverGivingIds = new List <string>(); var consistentGiverGivingIds = new List <string>(); var noneOfTheAboveGiverGivingIds = new List <string>(); foreach (var givingIdTransactions in transactionDateTimesByGivingId) { var givingId = givingIdTransactions.Key; var transactionDateList = givingIdTransactions.Value.Where(a => a.HasValue).Select(a => a.Value).ToList(); GivingJourneyStage?givingIdGivingJourneyStage = GetGivingJourneyStage(givingJourneySettings, currentDate, transactionDateList); switch (givingIdGivingJourneyStage) { case GivingJourneyStage.Former: formerGiverGivingIds.Add(givingId); break; case GivingJourneyStage.Lapsed: lapsedGiverGivingIds.Add(givingId); break; case GivingJourneyStage.New: newGiverGivingIds.Add(givingId); break; case GivingJourneyStage.Occasional: occasionalGiverGivingIds.Add(givingId); break; case GivingJourneyStage.Consistent: consistentGiverGivingIds.Add(givingId); break; case GivingJourneyStage.None: // Shouldn't happen since we are only looking at people with transactions, and we have already // figured out the non-givers break; default: // if they are non of the above, then add them to the "none of the above" list noneOfTheAboveGiverGivingIds.Add(givingId); break; } } Debug.WriteLine($@" FormerGiverCount: {formerGiverGivingIds.Count} LapsedGiverCount: {lapsedGiverGivingIds.Count} NewGiverCount: {newGiverGivingIds.Count} OccasionalGiverCount: {occasionalGiverGivingIds.Count} ConsistentGiverCount: {consistentGiverGivingIds.Count} NonGiverCount: {nonGiverGivingIdsList.Count} NoneOfTheAboveCount: {noneOfTheAboveGiverGivingIds.Count} "); _attributeValuesByGivingIdAndPersonId = personCurrentJourneyAttributeValues .ToDictionary( k => k.Key, v => { var lookupByPersonId = v.Value .Select(s => new AttributeValueCache(s.AttributeId, s.PersonId, s.AttributeValue)) .GroupBy(g => g.EntityId.Value) .ToDictionary(k => k.Key, vv => vv.ToList()); return(lookupByPersonId); }); _personIdsByGivingId = personQuery.Where(x => !string.IsNullOrEmpty(x.GivingId)) .Select(a => new { a.GivingId, PersonId = a.Id }) .GroupBy(a => a.GivingId) .ToDictionary( k => k.Key, v => v.Select(p => p.PersonId).ToList()); UpdateJourneyStageAttributeValuesForGivingId(formerGiverGivingIds, GivingJourneyStage.Former); UpdateJourneyStageAttributeValuesForGivingId(lapsedGiverGivingIds, GivingJourneyStage.Lapsed); UpdateJourneyStageAttributeValuesForGivingId(newGiverGivingIds, GivingJourneyStage.New); UpdateJourneyStageAttributeValuesForGivingId(occasionalGiverGivingIds, GivingJourneyStage.Occasional); UpdateJourneyStageAttributeValuesForGivingId(consistentGiverGivingIds, GivingJourneyStage.Consistent); UpdateJourneyStageAttributeValuesForGivingId(nonGiverGivingIdsList, GivingJourneyStage.None); UpdateJourneyStageAttributeValuesForGivingId(noneOfTheAboveGiverGivingIds, null); }
void rptrActivities_ItemDataBound(object sender, RepeaterItemEventArgs e) { var activity = e.Item.DataItem as WorkflowActivity; if (activity != null) { var lblComplete = e.Item.FindControl("lblComplete") as Label; if (lblComplete != null) { lblComplete.Visible = activity.CompletedDateTime.HasValue; } var lblActive = e.Item.FindControl("lblActive") as Label; if (lblActive != null) { lblActive.Visible = !activity.CompletedDateTime.HasValue; } var tdAssignedToPerson = e.Item.FindControl("tdAssignedToPerson") as TermDescription; if (tdAssignedToPerson != null && activity.AssignedPersonAliasId.HasValue) { var person = _personAliasService.Queryable() .Where(a => a.Id == activity.AssignedPersonAliasId.Value) .Select(a => a.Person) .FirstOrDefault(); if (person != null) { tdAssignedToPerson.Description = string.Format("<a href='{0}{1}'>{2}</a>", ResolveRockUrl("~/Person/"), person.Id, person.FullName); } } var tdAssignedToGroup = e.Item.FindControl("tdAssignedToGroup") as TermDescription; if (tdAssignedToGroup != null && activity.AssignedGroupId.HasValue) { var group = _groupService.Get(activity.AssignedGroupId.Value); if (group != null) { tdAssignedToGroup.Description = group.Name; } } var tdActivated = e.Item.FindControl("tdActivated") as TermDescription; if (tdActivated != null && activity.ActivatedDateTime.HasValue) { tdActivated.Description = string.Format("{0} {1} ({2})", activity.ActivatedDateTime.Value.ToShortDateString(), activity.ActivatedDateTime.Value.ToShortTimeString(), activity.ActivatedDateTime.Value.ToRelativeDateString()); } var tdCompleted = e.Item.FindControl("tdCompleted") as TermDescription; if (tdCompleted != null && activity.CompletedDateTime.HasValue) { tdCompleted.Description = string.Format("{0} {1} ({2})", activity.CompletedDateTime.Value.ToShortDateString(), activity.CompletedDateTime.Value.ToShortTimeString(), activity.CompletedDateTime.Value.ToRelativeDateString()); } var phActivityAttributes = e.Item.FindControl("phActivityAttributes") as PlaceHolder; if (phActivityAttributes != null) { foreach (var attribute in activity.Attributes.OrderBy(a => a.Value.Order).Select(a => a.Value)) { var td = new TermDescription(); phActivityAttributes.Controls.Add(td); td.Term = attribute.Name; string value = activity.GetAttributeValue(attribute.Key); var field = attribute.FieldType.Field; string formattedValue = field.FormatValueAsHtml(phActivityAttributes, value, attribute.QualifierValues); if (field is Rock.Field.ILinkableFieldType) { var linkableField = field as Rock.Field.ILinkableFieldType; td.Description = string.Format("<a href='{0}{1}'>{2}</a>", ResolveRockUrl("~"), linkableField.UrlLink(value, attribute.QualifierValues), formattedValue); } else { td.Description = formattedValue; } phActivityAttributes.Controls.Add(td); } } var gridActions = e.Item.FindControl("gridActions") as Grid; if (gridActions != null) { gridActions.DataSource = activity.Actions.OrderBy(a => a.ActionType.Order) .Select(a => new { Name = a.ActionType.Name, LastProcessed = a.LastProcessedDateTime.HasValue ? string.Format("{0} {1} ({2})", a.LastProcessedDateTime.Value.ToShortDateString(), a.LastProcessedDateTime.Value.ToShortTimeString(), a.LastProcessedDateTime.Value.ToRelativeDateString()) : "", Completed = a.CompletedDateTime.HasValue, CompletedWhen = a.CompletedDateTime.HasValue ? string.Format("{0} {1} ({2})", a.CompletedDateTime.Value.ToShortDateString(), a.CompletedDateTime.Value.ToShortTimeString(), a.CompletedDateTime.Value.ToRelativeDateString()) : "" }) .ToList(); gridActions.DataBind(); } } }
/// <summary>Process all transactions (payments) from Service Reef.</summary> /// <param name="message">The message that is returned depending on the result.</param> /// <param name="state">The state of the process.</param> /// <returns><see cref="WorkerResultStatus"/></returns> public void Execute(IJobExecutionContext context) { RockContext dbContext = new RockContext(); FinancialBatchService financialBatchService = new FinancialBatchService(dbContext); PersonService personService = new PersonService(dbContext); PersonAliasService personAliasService = new PersonAliasService(dbContext); FinancialAccountService financialAccountService = new FinancialAccountService(dbContext); FinancialAccountService accountService = new FinancialAccountService(dbContext); FinancialTransactionService financialTransactionService = new FinancialTransactionService(dbContext); FinancialGatewayService financialGatewayService = new FinancialGatewayService(dbContext); DefinedValueService definedValueService = new DefinedValueService(dbContext); DefinedTypeService definedTypeService = new DefinedTypeService(dbContext); TransactionService transactionService = new TransactionService(new PayPalReporting.Data.PayPalReportingContext()); // Get the datamap for loading attributes JobDataMap dataMap = context.JobDetail.JobDataMap; String warnings = string.Empty; FinancialBatch batch = null; Double totalAmount = 0; var total = 1; var processed = 0; try { DateRange dateRange = Rock.Web.UI.Controls.SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(dataMap.GetString("DateRange") ?? "-1||"); String SRApiKey = Encryption.DecryptString(dataMap.GetString("ServiceReefAPIKey")); String SRApiSecret = Encryption.DecryptString(dataMap.GetString("ServiceReefAPISecret")); String SRApiUrl = dataMap.GetString("ServiceReefAPIURL"); DefinedValueCache transactionSource = DefinedValueCache.Read(dataMap.GetString("TransactionSource").AsGuid(), dbContext); DefinedValueCache connectionStatus = DefinedValueCache.Read(dataMap.GetString("ConnectionStatus").AsGuid(), dbContext); DefinedValueCache contribution = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION); // Setup some lookups DefinedTypeCache creditCards = DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.FINANCIAL_CREDIT_CARD_TYPE.AsGuid(), dbContext); DefinedTypeCache tenderType = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.FINANCIAL_CURRENCY_TYPE.AsGuid(), dbContext); FinancialAccount specialFund = accountService.Get(dataMap.GetString("Account").AsGuid()); FinancialGateway gateway = financialGatewayService.Get(dataMap.GetString("FinancialGateway").AsGuid()); List <FinancialAccount> trips = financialAccountService.Queryable().Where(fa => fa.ParentAccountId == specialFund.Id).OrderBy(fa => fa.Order).ToList(); // Get the trips DefinedValueCache serviceReefAccountType = DefinedValueCache.Get(dataMap.Get("ServiceReefAccountType").ToString().AsGuid()); // Setup the ServiceReef API Client var client = new RestClient(SRApiUrl); client.Authenticator = new HMACAuthenticator(SRApiKey, SRApiSecret); // Get all payments from ServiceReef var request = new RestRequest("v1/payments", Method.GET); request.AddParameter("pageSize", 100); if (dateRange.Start.HasValue) { request.AddParameter("startDate", dateRange.Start.Value.ToString("o")); } if (dateRange.End.HasValue) { request.AddParameter("endDate", dateRange.End.Value.ToString("o")); } request.AddParameter("page", 1); while (total > processed) { var response = client.Execute <Contracts.Payments>(request); if (response.StatusCode != System.Net.HttpStatusCode.OK) { throw new Exception("ServiceReef API Response: " + response.StatusDescription + " Content Length: " + response.ContentLength); } if (response.Data != null && response.Data.PageInfo != null) { total = response.Data.PageInfo.TotalRecords; foreach (Contracts.Payments.Result result in response.Data.Results) { // Process the transaction if (result.PaymentProcessorTransactionId != null) { if (result.FirstName == null || result.LastName == null) { warnings += "Missing Firstname/Lastname for ServiceReef transaction Id: " + result.TransactionId + Environment.NewLine; processed++; continue; } FinancialAccount trip = null; // Make sure we have a sub-account to go with this transaction if (result.EventId > 0) { trip = trips.Where(t => t.GlCode == result.EventCode && t.Url == result.EventUrl).FirstOrDefault(); } if (trip == null) { if (result.EventCode == null) { warnings += "Event Code is missing on the Service Reef Trip for ServiceReef transaction Id: " + result.TransactionId + Environment.NewLine; processed++; continue; } // Create the trip subaccount FinancialAccount tripFA = new FinancialAccount(); tripFA.Name = result.EventName; // Name is limited to 50 if (tripFA.Name.Length > 50) { tripFA.Name = tripFA.Name.Substring(0, 50); } tripFA.Description = "Service Reef Event. Name: " + result.EventName + " ID: " + result.EventId; tripFA.GlCode = result.EventCode; tripFA.Url = result.EventUrl; tripFA.PublicName = result.EventName; // Public Name is limited to 50 if (tripFA.PublicName.Length > 50) { tripFA.PublicName = tripFA.PublicName.Substring(0, 50); } tripFA.IsTaxDeductible = true; tripFA.IsPublic = false; tripFA.ParentAccountId = specialFund.Id; tripFA.Order = specialFund.Order + 1; tripFA.AccountTypeValueId = serviceReefAccountType.Id; // Figure out what order it should be; foreach (FinancialAccount tmpTrip in trips) { if (tmpTrip.Name.CompareTo(tripFA.Name) < 0) { tripFA.Order++; } } financialAccountService.Add(tripFA); // Now save the trip dbContext.SaveChanges(); // Increment all the rest of the Orders financialAccountService.Queryable().Where(fa => fa.Order >= tripFA.Order && fa.Id != tripFA.Id).ToList().ForEach(c => c.Order++); dbContext.SaveChanges(); trips = financialAccountService.Queryable().Where(fa => fa.ParentAccountId == specialFund.Id).OrderBy(fa => fa.Order).ToList(); trip = tripFA; } FinancialTransaction tran = financialTransactionService.Queryable().Where(tx => tx.TransactionCode == result.PaymentProcessorTransactionId).FirstOrDefault(); // We haven't processed this before so get busy! if (tran == null) { tran = new FinancialTransaction(); tran.FinancialPaymentDetail = new FinancialPaymentDetail(); if (result.Type == "CreditCard") { tran.FinancialPaymentDetail.CurrencyTypeValueId = tenderType.DefinedValues.Where(t => t.Value == "Credit Card").FirstOrDefault().Id; } else { tran.TransactionTypeValueId = tenderType.DefinedValues.Where(t => t.Value == "Credit Card").FirstOrDefault().Id; } Person person = null; // Find the person this transaction belongs to // 1. First start by determining whether this was a person // paying their application fee or contributing to themselves // because then we can just use their member info if (result.UserId > 0 && result.DonatedToUserId == result.UserId && result.DonatedToFirstName == result.FirstName && result.DonatedToLastName == result.LastName) { var memberRequest = new RestRequest("v1/members/{userId}", Method.GET); memberRequest.AddUrlSegment("userId", result.UserId.ToString()); var memberResult = client.Execute <Contracts.Member>(memberRequest); if (memberResult.Data != null && memberResult.Data.ArenaId > 0) { try { Person personMatch = personAliasService.Queryable().Where(pa => pa.AliasPersonId == memberResult.Data.ArenaId).Select(pa => pa.Person).FirstOrDefault(); if (personMatch == null) { throw new Exception("Person not found: " + memberResult.Data.ArenaId); } person = personMatch; } catch (Exception e) { warnings += "Loading the person failed transaction id " + result.TransactionId + " for " + result.FirstName + " " + result.LastName + " with the following error: " + e.Message + Environment.NewLine; processed++; continue; } } } // 2. If we didn't get a person match via their Alias Id // then just use the standard person match logic if (person == null) { String street1 = null; String postalCode = null; if (result.Address != null) { street1 = result.Address.Address1; postalCode = result.Address.Zip; } List <Person> matches = personService.GetByMatch(result.FirstName.Trim(), result.LastName.Trim(), null, result.Email, null, street1, postalCode).ToList(); if (matches.Count > 1) { // Find the oldest member record in the list person = matches.Where(p => p.ConnectionStatusValue.Value == "Member").OrderBy(p => p.Id).FirstOrDefault(); if (person == null) { // Find the oldest attendee record in the list person = matches.Where(p => p.ConnectionStatusValue.Value == "Attendee").OrderBy(p => p.Id).FirstOrDefault(); if (person == null) { person = matches.OrderBy(p => p.Id).First(); } } } else if (matches.Count == 1) { person = matches.First(); } else { // Create the person person = new Person(); person.FirstName = result.FirstName.Trim(); person.LastName = result.LastName.Trim(); if (result.Email.IsValidEmail()) { person.Email = result.Email.Trim(); } person.RecordTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id; person.ConnectionStatusValueId = connectionStatus.Id; person.RecordStatusValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id; Group family = PersonService.SaveNewPerson(person, dbContext); GroupLocation location = new GroupLocation(); location.GroupLocationTypeValueId = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id; location.Location = new Location() { Street1 = result.Address.Address1, Street2 = result.Address.Address2, City = result.Address.City, State = result.Address.State, PostalCode = result.Address.Zip, Country = result.Address.Country }; family.CampusId = CampusCache.All().FirstOrDefault().Id; family.GroupLocations.Add(location); dbContext.SaveChanges(); } } // Get details about the transaction from our PayPal report table Transaction tx = transactionService.Get(result.PaymentProcessorTransactionId); if (tx != null) { if (tx.TenderType.Contains("ACH")) { result.Type = "ACH"; result.Method = null; } else { result.Type = "Credit Card"; result.Method = tx.TenderType; } } else { // Defaults result.Type = "Credit Card"; result.Method = "Visa"; warnings += "Unable to find transaction in _org_secc_PaypalReporting_Transaction table: " + result.TransactionId + Environment.NewLine; } // If we don't have a batch, create one if (batch == null) { batch = new FinancialBatch(); batch.BatchStartDateTime = result.Date; batch.BatchEndDateTime = DateTime.Now; batch.Name = "Service Reef Payments"; batch.Status = BatchStatus.Open; financialBatchService.Add(batch); dbContext.SaveChanges(); } // Complete the FinancialTransaction tran.AuthorizedPersonAliasId = person.PrimaryAliasId; tran.BatchId = batch.Id; tran.Summary = "F" + specialFund.Id + ":$" + result.Amount.ToString(); tran.TransactionDateTime = result.Date; tran.FinancialGatewayId = gateway.Id; FinancialTransactionDetail financialTransactionDetail = new FinancialTransactionDetail(); financialTransactionDetail.AccountId = trip.Id; financialTransactionDetail.Amount = result.Amount.ToString().AsDecimal(); tran.TransactionDetails.Add(financialTransactionDetail); tran.TransactionTypeValueId = contribution.Id; tran.FinancialPaymentDetail = new FinancialPaymentDetail(); tran.FinancialPaymentDetail.CurrencyTypeValueId = tenderType.DefinedValues.Where(type => type.Value.ToLower() == result.Type.ToLower()).FirstOrDefault().Id; if (result.Method != null) { tran.FinancialPaymentDetail.CreditCardTypeValueId = creditCards.DefinedValues.Where(card => card.Value.ToLower() == result.Method.ToLower()).FirstOrDefault().Id; } tran.TransactionCode = result.PaymentProcessorTransactionId; tran.SourceTypeValueId = transactionSource.Id; financialTransactionService.Add(tran); dbContext.SaveChanges(); totalAmount += result.Amount; } } processed++; } } else { total = 0; } // Update the page number for the next request var pageParam = request.Parameters.Where(p => p.Name == "page").FirstOrDefault(); pageParam.Value = (int)pageParam.Value + 1; } } catch (Exception ex) { throw new Exception("ServiceReef Job Failed", ex); } finally { if (batch != null && totalAmount > 0) { batch.ControlAmount = (Decimal)totalAmount; } dbContext.SaveChanges(); } if (warnings.Length > 0) { throw new Exception(warnings); } context.Result = "Successfully imported " + processed + " transactions."; }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { var rockContext = new RockContext(); var groupMemberService = new GroupMemberService(rockContext); var groupService = new GroupService(rockContext); var groupTypeService = new GroupTypeService(rockContext); var attributeService = new AttributeService(rockContext); var attributeValueService = new AttributeValueService(rockContext); var personService = new PersonService(rockContext); var personAliasService = new PersonAliasService(rockContext); var entityTypeService = new EntityTypeService(rockContext); var registrationRegistrantService = new RegistrationRegistrantService(rockContext); var eiogmService = new EventItemOccurrenceGroupMapService(rockContext); var groupLocationService = new GroupLocationService(rockContext); var locationService = new LocationService(rockContext); var signatureDocumentServce = new SignatureDocumentService(rockContext); var phoneNumberService = new PhoneNumberService(rockContext); int[] signatureDocumentIds = { }; if (!string.IsNullOrWhiteSpace(GetAttributeValue("SignatureDocumentTemplates"))) { signatureDocumentIds = Array.ConvertAll(GetAttributeValue("SignatureDocumentTemplates").Split(','), int.Parse); } Guid bbGroup = GetAttributeValue("Group").AsGuid(); var group = new GroupService(rockContext).Get(bbGroup); if (group.Name.Contains("Week 2")) { cmpCampus.Visible = true; } Guid hsmGroupTypeGuid = GetAttributeValue("MSMGroupType").AsGuid(); int? hsmGroupTypeId = groupTypeService.Queryable().Where(gt => gt.Guid == hsmGroupTypeGuid).Select(gt => gt.Id).FirstOrDefault(); int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Rock.Model.Group).FullName).FirstOrDefault().Id; var registrationTemplateIds = eiogmService.Queryable().Where(r => r.GroupId == group.Id).Select(m => m.RegistrationInstance.RegistrationTemplateId.ToString()).ToList(); hlGroup.NavigateUrl = "/group/" + group.Id; var attributeIds = attributeService.Queryable() .Where(a => (a.EntityTypeQualifierColumn == "GroupId" && a.EntityTypeQualifierValue == group.Id.ToString()) || (a.EntityTypeQualifierColumn == "GroupTypeId" && a.EntityTypeQualifierValue == group.GroupTypeId.ToString()) || (a.EntityTypeQualifierColumn == "RegistrationTemplateId" && registrationTemplateIds.Contains(a.EntityTypeQualifierValue))) .Select(a => a.Id).ToList(); var gmTmpqry = groupMemberService.Queryable() .Where(gm => (gm.GroupId == group.Id)); var qry = gmTmpqry .GroupJoin(registrationRegistrantService.Queryable(), obj => obj.Id, rr => rr.GroupMemberId, (obj, rr) => new { GroupMember = obj, Person = obj.Person, RegistrationRegistrant = rr }) .GroupJoin(attributeValueService.Queryable(), obj => new { PersonId = (int?)obj.Person.Id, AttributeId = 739 }, av => new { PersonId = av.EntityId, av.AttributeId }, (obj, av) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, School = av.Select(s => s.Value).FirstOrDefault() }) .GroupJoin(attributeValueService.Queryable(), obj => obj.GroupMember.Id, av => av.EntityId.Value, (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)), School = obj.School /*, Location = obj.Location */ }) .GroupJoin(attributeValueService.Queryable(), obj => obj.RegistrationRegistrant.FirstOrDefault().Id, av => av.EntityId.Value, (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = obj.GroupMemberAttributeValues, RegistrationAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)), School = obj.School /*, Location = obj.Location */ }); var qry2 = gmTmpqry .GroupJoin( groupMemberService.Queryable() .Join(groupService.Queryable(), gm => new { Id = gm.GroupId, GroupTypeId = 10 }, g => new { g.Id, g.GroupTypeId }, (gm, g) => new { GroupMember = gm, Group = g }) .Join(groupLocationService.Queryable(), obj => new { GroupId = obj.Group.Id, GroupLocationTypeValueId = (int?)19 }, gl => new { gl.GroupId, gl.GroupLocationTypeValueId }, (g, gl) => new { GroupMember = g.GroupMember, GroupLocation = gl }) .Join(locationService.Queryable(), obj => obj.GroupLocation.LocationId, l => l.Id, (obj, l) => new { GroupMember = obj.GroupMember, Location = l }), gm => gm.PersonId, glgm => glgm.GroupMember.PersonId, (obj, l) => new { GroupMember = obj, Location = l.Select(loc => loc.Location).FirstOrDefault() } ) .GroupJoin(signatureDocumentServce.Queryable() .Join(personAliasService.Queryable(), sd => sd.AppliesToPersonAliasId, pa => pa.Id, (sd, pa) => new { SignatureDocument = sd, Alias = pa }), obj => obj.GroupMember.PersonId, sd => sd.Alias.PersonId, (obj, sds) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = sds }) .GroupJoin(phoneNumberService.Queryable(), obj => obj.GroupMember.PersonId, p => p.PersonId, (obj, pn) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = obj.SignatureDocuments, PhoneNumbers = pn }); if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}PersonName", keyPrefix)))) { string personName = GetUserPreference(string.Format("{0}PersonName", keyPrefix)).ToLower(); qry = qry.ToList().Where(q => q.GroupMember.Person.FullName.ToLower().Contains(personName)).AsQueryable(); } decimal?lowerVal = GetUserPreference(string.Format("{0}BalanceOwedLower", keyPrefix)).AsDecimalOrNull(); decimal?upperVal = GetUserPreference(string.Format("{0}BalanceOwedUpper", keyPrefix)).AsDecimalOrNull(); if (lowerVal != null && upperVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() >= lowerVal && q.RegistrationRegistrant.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() <= upperVal).AsQueryable(); } else if (lowerVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() >= lowerVal).AsQueryable(); } else if (upperVal != null) { qry = qry.ToList().Where(q => q.RegistrationRegistrant.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() <= upperVal).AsQueryable(); } else if (!string.IsNullOrEmpty(cmpCampus.SelectedValue)) { if (group.Name.Contains("Week 2")) { qry = qry.ToList().Where(q => q.RegistrationAttributeValues.Where(ra => ra.AttributeKey == "Whichcampusdoyouwanttodepartforcampfromandroomwith" && ra.Value == cmpCampus.SelectedValue).Any()).AsQueryable(); } } var stopwatch = new Stopwatch(); stopwatch.Start(); var tmp = qry.ToList(); var tmp2 = qry2.ToList(); lStats.Text = "Query Runtime: " + stopwatch.Elapsed; stopwatch.Reset(); stopwatch.Start(); var newQry = tmp.Select(g => new { Id = g.GroupMember.Id, RegisteredBy = new ModelValue <Person>(g.RegistrationRegistrant.Select(rr => rr.Registration.PersonAlias.Person).FirstOrDefault()), Registrant = new ModelValue <Person>(g.Person), Age = g.Person.Age, GraduationYear = g.Person.GraduationYear, RegistrationId = g.RegistrationRegistrant.Select(rr => rr.RegistrationId).FirstOrDefault(), Group = new ModelValue <Rock.Model.Group>((Rock.Model.Group)g.GroupMember.Group), DOB = g.Person.BirthDate.HasValue ? g.Person.BirthDate.Value.ToShortDateString() : "", Address = new ModelValue <Rock.Model.Location>((Rock.Model.Location)tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location).FirstOrDefault()), Email = g.Person.Email, Gender = g.Person.Gender, // (B & B Registration) GraduationYearProfile = g.Person.GraduationYear, // (Person Profile) HomePhone = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(), CellPhone = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(), GroupMemberData = new Func <GroupMemberAttributes>(() => { GroupMemberAttributes gma = new GroupMemberAttributes(g.GroupMember, g.Person, g.GroupMemberAttributeValues); return(gma); })(), RegistrantData = new Func <RegistrantAttributes>(() => { RegistrantAttributes row = new RegistrantAttributes(g.RegistrationRegistrant.FirstOrDefault(), g.RegistrationAttributeValues); return(row); })(), School = string.IsNullOrEmpty(g.School)?"":DefinedValueCache.Read(g.School.AsGuid()) != null?DefinedValueCache.Read(g.School.AsGuid()).Value:"", LegalRelease = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.SignatureDocuments).OrderByDescending(sd => sd.SignatureDocument.CreatedDateTime).Where(sd => signatureDocumentIds.Contains(sd.SignatureDocument.SignatureDocumentTemplateId)).Select(sd => sd.SignatureDocument.SignatureDocumentTemplate.Name + " (" + sd.SignatureDocument.Status.ToString() + ")").FirstOrDefault(), Departure = g.GroupMemberAttributeValues.Where(av => av.AttributeKey == "Departure").Select(av => av.Value).FirstOrDefault(), Campus = group.Campus, // Role = group.ParentGroup.GroupType.Name.Contains("Serving") || group.Name.ToLower().Contains("leader")? "Leader":"Student", // MSMGroup = String.Join(", ", groupMemberService.Queryable().Where(gm => gm.PersonId == g.GroupMember.PersonId && gm.Group.GroupTypeId == hsmGroupTypeId && gm.GroupMemberStatus == GroupMemberStatus.Active).Select(gm => gm.Group.Name).ToList()), Person = g.Person, AddressStreet = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location != null?gm.Location.Street1:"").FirstOrDefault(), AddressCityStateZip = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location != null ? gm.Location.City + ", " + gm.Location.State + " " + gm.Location.PostalCode : "").FirstOrDefault(), RegistrantName = g.Person.FullName, }).OrderBy(w => w.Registrant.Model.LastName).ToList().AsQueryable(); lStats.Text += "<br />Object Build Runtime: " + stopwatch.Elapsed; stopwatch.Stop(); gReport.GetRecipientMergeFields += GReport_GetRecipientMergeFields; var mergeFields = new List <String>(); mergeFields.Add("Id"); mergeFields.Add("RegisteredBy"); mergeFields.Add("Group"); mergeFields.Add("Registrant"); mergeFields.Add("Age"); mergeFields.Add("GraduationYear"); mergeFields.Add("DOB"); mergeFields.Add("Address"); mergeFields.Add("Email"); mergeFields.Add("Gender"); mergeFields.Add("GraduationYearProfile"); mergeFields.Add("HomePhone"); mergeFields.Add("CellPhone"); mergeFields.Add("GroupMemberData"); mergeFields.Add("RegistrantData"); mergeFields.Add("LegalRelease"); mergeFields.Add("Departure"); mergeFields.Add("Campus"); mergeFields.Add("Role"); mergeFields.Add("MSMGroup"); gReport.CommunicateMergeFields = mergeFields; /* * if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}POA", keyPrefix)))) * { * string poa = GetUserPreference(string.Format("{0}POA", keyPrefix)); * if (poa == "[Blank]") * { * poa = ""; * } * newQry = newQry.Where(q => q.GroupMemberData.POA == poa); * } */ SortProperty sortProperty = gReport.SortProperty; if (sortProperty != null) { gReport.SetLinqDataSource(newQry.Sort(sortProperty)); } else { gReport.SetLinqDataSource(newQry.OrderBy(p => p.Registrant.Model.LastName)); } gReport.DataBind(); }
private void FastPassCheckin(string accessKey) { try { CurrentCheckInState.CheckIn.SearchType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_SCANNED_ID); CurrentCheckInState.CheckIn.SearchValue = accessKey; CurrentCheckInState.CheckIn.ConfirmSingleFamily = false; CurrentCheckInState.CheckIn.UserEnteredSearch = false; string workflowActivity = GetAttributeValue("WorkflowActivity"); List <string> errors = new List <string>(); bool test = ProcessActivity(workflowActivity, out errors); if (!CurrentCheckInState.CheckIn.Families.Any() || !CurrentCheckInState.CheckIn.CheckedInByPersonAliasId.HasValue) { MobileCheckinMessage(GetAttributeValue(AttributeKeys.FastPassNotFound)); return; } CurrentCheckInState.CheckIn.Families.FirstOrDefault().Selected = true; test = ProcessActivity(GetAttributeValue(AttributeKeys.PersonSearchActivityName), out errors); RockContext rockContext = new RockContext(); PersonAliasService personAliasService = new PersonAliasService(rockContext); var personId = personAliasService.Queryable().AsNoTracking() .Where(pa => pa.Id == CurrentCheckInState.CheckIn.CheckedInByPersonAliasId.Value) .Select(pa => pa.PersonId) .FirstOrDefault(); var person = CurrentCheckInState.CheckIn.CurrentFamily.People.Where(p => p.Person.Id == personId).FirstOrDefault(); var selected = false; if (person == null) { MobileCheckinMessage(GetAttributeValue(AttributeKeys.NoCheckinAvailable), 4); return; } foreach (var gt in person.GroupTypes.OrderByDescending(gt => gt.PreSelected)) { foreach (var g in gt.Groups.OrderByDescending(g => g.PreSelected)) { foreach (var l in g.Locations.OrderByDescending(l => l.PreSelected)) { foreach (var s in l.Schedules) { s.Selected = true; l.Selected = true; g.Selected = true; gt.Selected = true; selected = true; } if (selected) { break; } } if (selected) { break; } } if (selected) { break; } } if (!selected) { if (person.GroupTypes.SelectMany(gt => gt.Groups).Any()) { MobileCheckinMessage(GetAttributeValue(AttributeKeys.AlreadyCheckedIn), 4); } else { MobileCheckinMessage(GetAttributeValue(AttributeKeys.NoCheckinAvailable), 4); } return; } test = ProcessActivity(GetAttributeValue(AttributeKeys.SaveAttendanceActivtyName), out errors); LabelPrinter labelPrinter = new LabelPrinter() { Request = Request, Labels = person.GroupTypes.Where(gt => gt.Labels != null).SelectMany(gt => gt.Labels).ToList() }; labelPrinter.PrintNetworkLabels(); var script = labelPrinter.GetClientScript(); ScriptManager.RegisterStartupScript(upContent, upContent.GetType(), "addLabelScript", script, true); MobileCheckinMessage(GetAttributeValue(AttributeKeys.FastPassComplete), 2); } catch (Exception e) { LogException(e); } }
/// <summary> /// Executes this instance. /// </summary> /// <exception cref="System.NotImplementedException"></exception> public void Execute() { var achievementTypeCache = AchievementTypeCache.Get(AchievementTypeId); if (achievementTypeCache == null || !achievementTypeCache.IsActive) { return; } if (IsNowStarting && achievementTypeCache.AchievementStartWorkflowTypeId.HasValue) { LaunchWorkflow(achievementTypeCache.AchievementStartWorkflowTypeId.Value); } if (IsNowEnding && !IsNowSuccessful && achievementTypeCache.AchievementFailureWorkflowTypeId.HasValue) { LaunchWorkflow(achievementTypeCache.AchievementFailureWorkflowTypeId.Value); } if (IsNowSuccessful && achievementTypeCache.AchievementSuccessWorkflowTypeId.HasValue) { LaunchWorkflow(achievementTypeCache.AchievementSuccessWorkflowTypeId.Value); } if (IsNowSuccessful && achievementTypeCache.AchievementStepStatusId.HasValue && achievementTypeCache.AchievementStepTypeId.HasValue) { var rockContext = new RockContext(); var achievementAttemptService = new AchievementAttemptService(rockContext); var achieverEntityId = achievementAttemptService.Queryable() .AsNoTracking() .Where(aa => aa.Guid == AchievementAttemptGuid) .Select(s => s.AchieverEntityId) .FirstOrDefault(); var personAliasEntityTypeId = EntityTypeCache.Get <PersonAlias>().Id; var personEntityTypeId = EntityTypeCache.Get <Person>().Id; int personAliasId = default; if (achievementTypeCache.AchieverEntityTypeId == personAliasEntityTypeId) { personAliasId = achieverEntityId; } else if (achievementTypeCache.AchieverEntityTypeId == personEntityTypeId) { var personAliasService = new PersonAliasService(rockContext); personAliasId = personAliasService.Queryable() .AsNoTracking() .Where(pa => pa.PersonId == achieverEntityId) .Select(pa => pa.Id) .FirstOrDefault(); } if (personAliasId != default) { AddStep(achievementTypeCache.AchievementStepTypeId.Value, achievementTypeCache.AchievementStepStatusId.Value, personAliasId); } } }
/// <summary> /// Executes this instance. /// </summary> /// <param name="message"></param> public override void Execute(Message message) { using (var rockContext = new RockContext()) { // Load the alert and alert type var financialTransactionAlertService = new FinancialTransactionAlertService(rockContext); var alert = financialTransactionAlertService.Queryable() .AsNoTracking() .Include(a => a.FinancialTransactionAlertType) .FirstOrDefault(a => a.Id == message.FinancialTransactionAlertId); var alertType = alert?.FinancialTransactionAlertType; // If the alert or alert type are no longer in the database, then there is nothing that can be done if (alertType == null) { return; } // Get the person that this alert was generated for. Several of the items below use this var personAliasService = new PersonAliasService(rockContext); var person = personAliasService.Queryable() .AsNoTracking() .Where(pa => pa.Id == alert.PersonAliasId) .Select(pa => pa.Person) .FirstOrDefault(); // Generate the merge objects for the lava templates used in the items below var isoDate = alert.AlertDateTime.ToISO8601DateString(); var alertsPageId = PageCache.Get(SystemGuid.Page.GIVING_ALERTS).Id; var relativeAlertLink = $"page/{alertsPageId}?StartDate={isoDate}&EndDate={isoDate}&AlertTypeId={alertType.Id}"; var mergeObjects = new Dictionary <string, object> { { nameof(FinancialTransactionAlert), alert }, { nameof(FinancialTransactionAlertType), alertType }, { nameof(Person), person }, { "RelativeAlertLink", relativeAlertLink } }; // Launch workflow if configured if (alertType.WorkflowTypeId.HasValue) { var workflowAttributeValues = new Dictionary <string, string>(); workflowAttributeValues.Add(nameof(FinancialTransactionAlert), alert.Guid.ToString()); workflowAttributeValues.Add(nameof(FinancialTransactionAlertType), alertType.Guid.ToString()); workflowAttributeValues.Add(nameof(Person), person.Guid.ToString()); alert.LaunchWorkflow(alertType.WorkflowTypeId, string.Empty, workflowAttributeValues, null); } // Add the person to a connection opportunity if configured if (alertType.ConnectionOpportunityId.HasValue) { var connectionOpportunityService = new ConnectionOpportunityService(rockContext); var statuses = connectionOpportunityService.Queryable() .AsNoTracking() .Where(co => co.Id == alertType.ConnectionOpportunityId) .SelectMany(co => co.ConnectionType.ConnectionStatuses) .Where(cs => cs.IsActive) .ToList() .OrderBy(cs => cs.Order); var status = statuses.FirstOrDefault(cs => cs.IsDefault) ?? statuses.FirstOrDefault(); if (status != null) { var connectionRequestService = new ConnectionRequestService(rockContext); var request = new ConnectionRequest { ConnectionOpportunityId = alertType.ConnectionOpportunityId.Value, PersonAliasId = alert.PersonAliasId, ConnectionStatusId = status.Id }; if (alert.TransactionId.HasValue) { request.LoadAttributes(); request.SetAttributeValue("FinancialTransactionId", alert.TransactionId.Value.ToString()); } connectionRequestService.Add(request); } } // Send a bus event if configured if (alertType.SendBusEvent) { new TransactionWasAlertedMessage { FinancialTransactionAlertId = alert.Id }.Publish(); } // Send a communication if configured if (alertType.SystemCommunicationId.HasValue) { var systemCommunicationService = new SystemCommunicationService(rockContext); var systemCommunication = systemCommunicationService.Get(alertType.SystemCommunicationId.Value); if (person != null && systemCommunication != null) { CommunicationHelper.SendMessage(person, ( int )person.CommunicationPreference, systemCommunication, mergeObjects); } } // Send a communication to account followers if an Account Participant System Communication and Account is specified // for this alert type if (alertType.AccountParticipantSystemCommunicationId.HasValue && alertType.FinancialAccountId.HasValue) { var systemCommunicationService = new SystemCommunicationService(rockContext); var financialAccountService = new FinancialAccountService(rockContext); var accountParticipantSystemCommunication = systemCommunicationService.Get(alertType.AccountParticipantSystemCommunicationId.Value); if (accountParticipantSystemCommunication != null) { var accountFollowers = financialAccountService .GetAccountParticipants(alertType.FinancialAccountId.Value, RelatedEntityPurposeKey.FinancialAccountGivingAlert) .Select(a => a.Person); foreach (var accountFollower in accountFollowers) { CommunicationHelper.SendMessage(accountFollower, ( int )accountFollower.CommunicationPreference, accountParticipantSystemCommunication, mergeObjects); } } } // Send a notification to a group if configured if (alertType.AlertSummaryNotificationGroupId.HasValue) { var systemEmailGuid = SystemGuid.SystemCommunication.FINANCIAL_TRANSACTION_ALERT_NOTIFICATION_SUMMARY.AsGuid(); var systemCommunicationService = new SystemCommunicationService(rockContext); var systemCommunication = systemCommunicationService.Get(systemEmailGuid); CommunicationHelper.SendMessage(alertType.AlertSummaryNotificationGroupId.Value, systemCommunication, mergeObjects); } rockContext.SaveChanges(); } }
/// <summary>Process all trips (events) from Service Reef.</summary> /// <param name="message">The message that is returned depending on the result.</param> /// <param name="state">The state of the process.</param> /// <returns><see cref="WorkerResultStatus"/></returns> public void Execute(IJobExecutionContext context) { RockContext dbContext = new RockContext(); PersonService personService = new PersonService(dbContext); PersonAliasService personAliasService = new PersonAliasService(dbContext); GroupService groupService = new GroupService(dbContext); GroupMemberService groupMemberService = new GroupMemberService(dbContext); AttributeService attributeService = new AttributeService(dbContext); AttributeValueService attributeValueService = new AttributeValueService(dbContext); GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(dbContext); DefinedValueService definedValueService = new DefinedValueService(dbContext); DefinedTypeService definedTypeService = new DefinedTypeService(dbContext); LocationService locationService = new LocationService(dbContext); // Get the datamap for loading attributes JobDataMap dataMap = context.JobDetail.JobDataMap; String warnings = string.Empty; var total = 1; var processed = 0; try { DateRange dateRange = Rock.Web.UI.Controls.SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(dataMap.GetString("DateRange") ?? "-1||"); String SRApiKey = Encryption.DecryptString(dataMap.GetString("ServiceReefAPIKey")); String SRApiSecret = Encryption.DecryptString(dataMap.GetString("ServiceReefAPISecret")); String SRApiUrl = dataMap.GetString("ServiceReefAPIURL"); DefinedValueCache connectionStatus = DefinedValueCache.Get(dataMap.GetString("DefaultConnectionStatus").AsGuid(), dbContext); if (SRApiUrl.Last() != '/') { SRApiUrl += "/"; } Group group = groupService.Get(dataMap.GetString("ParentGroup").AsGuid()); GroupTypeCache parentGroupType = GroupTypeCache.Get(dataMap.Get("YearGroupType").ToString().AsGuid(), dbContext); GroupTypeCache groupType = GroupTypeCache.Get(dataMap.Get("TripGroupType").ToString().AsGuid(), dbContext); Rock.Model.Attribute attribute = attributeService.Get(dataMap.GetString("ServiceReefUserId").AsGuid()); Rock.Model.Attribute attribute2 = attributeService.Get(dataMap.GetString("ServiceReefProfileURL").AsGuid()); var entitytype = EntityTypeCache.Get(typeof(Group)).Id; // Setup the ServiceReef API Client var client = new RestClient(SRApiUrl); client.Authenticator = new HMACAuthenticator(SRApiKey, SRApiSecret); // Get all events from ServiceReef var request = new RestRequest("v1/events", Method.GET); request.AddParameter("pageSize", 100); if (dateRange.Start.HasValue) { request.AddParameter("startDate", dateRange.Start.Value.ToString("o")); } if (dateRange.End.HasValue) { request.AddParameter("endDate", dateRange.End.Value.ToString("o")); } request.AddParameter("page", 1); while (total > processed) { var response = client.Execute <Contracts.Events>(request); if (response.StatusCode != System.Net.HttpStatusCode.OK) { throw new Exception("ServiceReef API Response: " + response.StatusDescription + " Content Length: " + response.ContentLength); } if (response.Data != null && response.Data.PageInfo != null) { total = response.Data.PageInfo.TotalRecords; foreach (Contracts.Events.Result result in response.Data.Results) { // Process the event Group trip = null; Group trip2 = null; var startdate = result.StartDate; var parentgroup = string.Format("{0} Mission Trips", startdate.Year); if (result.EventId > 0) { trip = groupService.Queryable().Where(t => t.Name == parentgroup).FirstOrDefault(); trip2 = groupService.Queryable().Where(t => t.ForeignId == result.EventId && t.GroupTypeId == groupType.Id).FirstOrDefault(); } Guid guid = Guid.NewGuid(); Guid guid2 = Guid.NewGuid(); if (trip == null) { // Create trip parent Group Group tripPG = new Group(); tripPG.Name = parentgroup; tripPG.GroupTypeId = parentGroupType.Id; tripPG.ParentGroupId = group.Id; tripPG.IsSystem = false; tripPG.IsActive = true; tripPG.IsSecurityRole = false; tripPG.Order = 0; tripPG.Guid = guid; groupService.Add(tripPG); // Now save the trip parent group dbContext.SaveChanges(); trip = tripPG; } if (trip2 == null) { // Create the trip Group tripG = new Group(); tripG.Name = result.Name; tripG.GroupTypeId = groupType.Id; tripG.ParentGroupId = trip.Id; tripG.IsSystem = false; tripG.IsActive = true; tripG.IsSecurityRole = false; tripG.Order = 0; tripG.ForeignId = result.EventId; groupService.Add(tripG); // Now save the trip dbContext.SaveChanges(); trip2 = tripG; } trip2.LoadAttributes(); if (startdate != DateTime.MinValue) { trip2.SetAttributeValue("Year", startdate.Year.ToString()); trip2.SetAttributeValue("Month", startdate.ToString("MMMM")); trip2.SaveAttributeValues(); } dbContext.SaveChanges(); var eventRequest = new RestRequest("v1/events/{eventId}", Method.GET); eventRequest.AddUrlSegment("eventId", result.EventId.ToString()); var eventResult = client.Execute <Contracts.Event>(eventRequest); if (eventResult.Data != null && eventResult.Data.Categories.Count > 0) { foreach (Contracts.Event.CategorySimple categorysimple in eventResult.Data.Categories) { var option = categorysimple.Options.FirstOrDefault(); if (option != null) { trip2.SetAttributeValue(categorysimple.Name.RemoveAllNonAlphaNumericCharacters(), option.Name); trip2.SaveAttributeValues(); } } dbContext.SaveChanges(); } var amount = 1; var handled = 0; String rest = String.Format("v1/events/{0}/participants", result.EventId); var request2 = new RestRequest(rest, Method.GET); request2.AddParameter("pageSize", 100); request2.AddParameter("page", 1); // We haven't processed this before so get busy! while (amount > handled) { var response2 = client.Execute <Contracts.Participants>(request2); if (response2.StatusCode != System.Net.HttpStatusCode.OK) { throw new Exception("ServiceReef API Response: " + response2.StatusDescription + " Content Length: " + response2.ContentLength); } if (response2.Data != null && response2.Data.PageInfo != null) { amount = response2.Data.PageInfo.TotalRecords; foreach (Contracts.Participants.Result result2 in response2.Data.Results) { Person person = null; if (result2.RegistrationStatus != "Draft") { if (result2.UserId > 0) { var memberRequest = new RestRequest("v1/members/{userId}", Method.GET); memberRequest.AddUrlSegment("userId", result2.UserId.ToString()); var memberResult = client.Execute <Contracts.Member>(memberRequest); if (memberResult.Data != null && memberResult.Data.ArenaId > 0) { Person personMatch = personAliasService.Queryable().Where(pa => pa.AliasPersonId == memberResult.Data.ArenaId).Select(pa => pa.Person).FirstOrDefault(); if (personMatch != null) { person = personMatch; } } } // 2. If we didn't get a person match via their Alias Id // then use their ServiceReef UserId attribute if (person == null && attribute != null) { var personIds = attributeValueService.Queryable().Where(av => av.AttributeId == attribute.Id && av.Value == result2.UserId.ToString()).Select(av => av.EntityId); if (personIds.Count() == 1) { person = personService.Get(personIds.FirstOrDefault().Value); } } // 3. If we STILL don't have a person match then // just use the standard person match/create logic if (person == null) { String street1 = null; String postalCode = null; if (result2.Address != null) { street1 = result2.Address.Address1; postalCode = result2.Address.Zip; } var email = result2.Email.Trim(); List <Person> matches = null; Location homelocation = new Location(); if (!email.IsValidEmail()) { email = null; matches = personService.Queryable() .Where(p => p.FirstName == result2.FirstName.Trim() && p.LastName == result2.LastName.Trim()).ToList(); if (matches.Count() > 0 && !string.IsNullOrEmpty(street1) && !string.IsNullOrEmpty(postalCode)) { homelocation.Street1 = street1; homelocation.PostalCode = postalCode; locationService.Verify(homelocation, true); } foreach (Person match in matches) { Boolean addressMatches = false; // Check the address if (!string.IsNullOrEmpty(street1) && !string.IsNullOrEmpty(postalCode)) { if (match.GetHomeLocation(dbContext) != null) { if (match.GetHomeLocation(dbContext).Street1 == street1 && match.GetHomeLocation(dbContext).PostalCode.Split('-')[0] == postalCode) { addressMatches = true; } } } if (!addressMatches) { matches.Remove(person); } } } else { matches = personService.GetByMatch(result2.FirstName.Trim(), result2.LastName.Trim(), null, email, null, street1, postalCode).ToList(); } if (matches.Count > 1) { // Find the oldest member record in the list person = matches.Where(p => p.ConnectionStatusValue.Value == "Member").OrderBy(p => p.Id).FirstOrDefault(); if (person == null) { // Find the oldest attendee record in the list person = matches.Where(p => p.ConnectionStatusValue.Value == "Attendee").OrderBy(p => p.Id).FirstOrDefault(); if (person == null) { person = matches.OrderBy(p => p.Id).First(); } } } else if (matches.Count == 1) { person = matches.First(); } else { // Create the person Guid guid3 = Guid.NewGuid(); person = new Person(); person.FirstName = result2.FirstName.Trim(); person.LastName = result2.LastName.Trim(); if (email.IsValidEmail()) { person.Email = email; } person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id; person.ConnectionStatusValueId = connectionStatus.Id; person.RecordStatusValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id; person.IsSystem = false; person.IsDeceased = false; person.IsEmailActive = true; person.Guid = guid3; var masteranswer = result2.MasterApplicationAnswers.Find(a => a.Question == "Gender"); var answer = result2.ApplicationAnswers.Find(a => a.Question == "Gender"); var flag = true; if (masteranswer != null) { var gender = masteranswer.Answer; if (!String.IsNullOrEmpty(gender)) { gender.Trim(); if (gender == "Male" || gender == "male") { person.Gender = Gender.Male; } else { person.Gender = Gender.Female; } flag = false; } } if (answer != null && flag == true) { var gender2 = answer.Answer; if (!String.IsNullOrEmpty(gender2)) { gender2.Trim(); if (gender2 == "Male" || gender2 == "male") { person.Gender = Gender.Male; } else { person.Gender = Gender.Female; } } else { person.Gender = Gender.Unknown; } } else if (flag == true) { person.Gender = Gender.Unknown; } Group family = PersonService.SaveNewPerson(person, dbContext); GroupLocation location = new GroupLocation(); location.GroupLocationTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME).Id; location.Location = new Location() { Street1 = result2.Address.Address1, Street2 = result2.Address.Address2, City = result2.Address.City, State = result2.Address.State, PostalCode = result2.Address.Zip, Country = result2.Address.Country }; location.IsMappedLocation = true; family.CampusId = CampusCache.All().FirstOrDefault().Id; family.GroupLocations.Add(location); dbContext.SaveChanges(); } } Guid guid4 = Guid.NewGuid(); Guid guid5 = Guid.NewGuid(); var userid = result2.UserId; var profileurl = result2.ProfileUrl; person.LoadAttributes(); if (userid > 0) { person.SetAttributeValue(attribute.Key, result2.UserId.ToString()); } if (!String.IsNullOrEmpty(profileurl)) { person.SetAttributeValue(attribute2.Key, result2.ProfileUrl); } person.SaveAttributeValues(); dbContext.SaveChanges(); var member = groupService.GroupHasMember(trip2.Guid, person.Id); if (member == false) { Guid guid6 = Guid.NewGuid(); GroupMember participant = new GroupMember(); participant.PersonId = person.Id; participant.GroupId = trip2.Id; participant.IsSystem = false; participant.Guid = guid6; var grouprole = groupTypeRoleService.Queryable().Where(r => r.GroupTypeId == trip2.GroupTypeId).FirstOrDefault().Id; participant.GroupRoleId = groupType.DefaultGroupRoleId.GetValueOrDefault(grouprole); if (result2.RegistrationStatus == "Approved") { participant.GroupMemberStatus = GroupMemberStatus.Active; } else if (result2.RegistrationStatus == "Cancelled") { participant.GroupMemberStatus = GroupMemberStatus.Inactive; } else { participant.GroupMemberStatus = GroupMemberStatus.Pending; } groupMemberService.Add(participant); dbContext.SaveChanges(); } } handled++; } } else { amount = 0; } var pageParam2 = request2.Parameters.Where(p => p.Name == "page").FirstOrDefault(); pageParam2.Value = (int)pageParam2.Value + 1; } processed++; } } else { total = 0; } // Update the page number for the next request var pageParam = request.Parameters.Where(p => p.Name == "page").FirstOrDefault(); pageParam.Value = (int)pageParam.Value + 1; } } catch (Exception ex) { throw new Exception("ServiceReef Job Failed", ex); } finally { dbContext.SaveChanges(); } if (warnings.Length > 0) { throw new Exception(warnings); } context.Result = "Successfully imported " + processed + " trips."; }