private void RaiseHistoryChanged(HistoryService.History history) => Context.DoCallBack(() => Changed?.Invoke(this, history));
/// <summary> /// Processes the NCOA results: Mark all 48 month move addresses as previous and processed if enabled, otherwise mark as manual update required. /// </summary> /// <param name="mark48MonthAsPrevious">if a 48 month move should be marked as previous, set to <c>true</c>.</param> /// <param name="previousValueId">The previous value identifier.</param> private void ProcessNcoaResults48MonthMove(bool mark48MonthAsPrevious, int?previousValueId) { List <int> ncoaIds = null; // Process the '48 Month Move' NCOA Types using (var rockContext = new RockContext()) { ncoaIds = new NcoaHistoryService(rockContext) .Queryable().AsNoTracking() .Where(n => n.Processed == Processed.NotProcessed && n.NcoaType == NcoaType.Month48Move) .Select(n => n.Id) .ToList(); } foreach (int id in ncoaIds) { using (var rockContext = new RockContext()) { var ncoaHistory = new NcoaHistoryService(rockContext).Get(id); if (ncoaHistory != null) { var groupService = new GroupService(rockContext); var groupLocationService = new GroupLocationService(rockContext); var changes = new History.HistoryChangeList(); // If configured to mark these as previous, and we're able to mark it as previous set the status to 'Complete' // otherwise set it to require a manual update if (mark48MonthAsPrevious && MarkAsPreviousLocation(ncoaHistory, groupLocationService, previousValueId, changes) != null) { ncoaHistory.Processed = Processed.Complete; // If there were any changes, write to history if (changes.Any()) { var family = groupService.Get(ncoaHistory.FamilyId); if (family != null) { foreach (var fm in family.Members) { HistoryService.SaveChanges( rockContext, typeof(Person), SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), fm.PersonId, changes, family.Name, typeof(Group), family.Id, false); } } } } else { ncoaHistory.Processed = Processed.ManualUpdateRequired; } rockContext.SaveChanges(); } } } }
/// <summary> /// Processes the NCOA results: Mark all individual move addresses as previous, add the new address as current; and processed. /// If minMoveDistance is specified, mark the individual as inactive if the individual moved further than the specified distance. /// </summary> /// <param name="inactiveReason">The inactive reason.</param> /// <param name="minMoveDistance">The minimum move distance.</param> /// <param name="homeValueId">The home value identifier.</param> /// <param name="previousValueId">The previous value identifier.</param> private void ProcessNcoaResultsIndividualMove(DefinedValueCache inactiveReason, decimal?minMoveDistance, int?homeValueId, int?previousValueId) { List <int> ncoaIds = null; // Process 'Move' NCOA Types (For the remaining Individual move types that weren't updated with the family move) using (var rockContext = new RockContext()) { ncoaIds = new NcoaHistoryService(rockContext) .Queryable().AsNoTracking() .Where(n => n.Processed == Processed.NotProcessed && n.NcoaType == NcoaType.Move && n.MoveType == MoveType.Individual) .Select(n => n.Id) .ToList(); } foreach (int id in ncoaIds) { using (var rockContext = new RockContext()) { // Get the NCOA record and make sure it still hasn't been processed var ncoaHistory = new NcoaHistoryService(rockContext).Get(id); if (ncoaHistory != null && ncoaHistory.Processed == Processed.NotProcessed) { var ncoaHistoryService = new NcoaHistoryService(rockContext); var groupMemberService = new GroupMemberService(rockContext); var personAliasService = new PersonAliasService(rockContext); var groupService = new GroupService(rockContext); var groupLocationService = new GroupLocationService(rockContext); var locationService = new LocationService(rockContext); var personService = new PersonService(rockContext); var changes = new History.HistoryChangeList(); // Default the status to requiring a manual update (we might change this though) ncoaHistory.Processed = Processed.ManualUpdateRequired; // Find the existing family var family = groupService.Get(ncoaHistory.FamilyId); // If there's only one person in the family if (family.Members.Count == 1) { // And that person is the same as the move record's person then we can process it. var personAlias = personAliasService.Get(ncoaHistory.PersonAliasId); var familyMember = family.Members.First(); if (personAlias != null && familyMember.PersonId == personAlias.PersonId) { // If were able to mark their existing address as previous and add a new updated Home address, // then set the status to complete (otherwise leave it as needing a manual update). var previousGroupLocation = MarkAsPreviousLocation(ncoaHistory, groupLocationService, previousValueId, changes); if (previousGroupLocation != null) { if (AddNewHomeLocation(ncoaHistory, locationService, groupLocationService, homeValueId, changes, previousGroupLocation.IsMailingLocation, previousGroupLocation.IsMappedLocation)) { ncoaHistory.Processed = Processed.Complete; // Look for any other moves for the same person to same address, and set their process to complete also foreach (var ncoaIndividual in ncoaHistoryService .Queryable().Where(n => n.Processed == Processed.NotProcessed && n.NcoaType == NcoaType.Move && n.MoveType == MoveType.Individual && n.PersonAliasId == ncoaHistory.PersonAliasId && n.Id != ncoaHistory.Id && n.UpdatedStreet1 == ncoaHistory.UpdatedStreet1)) { ncoaIndividual.Processed = Processed.Complete; } // If there were any changes, write to history and check to see if person should be inactivated if (changes.Any()) { if (ncoaHistory.MoveDistance.HasValue && minMoveDistance.HasValue && ncoaHistory.MoveDistance.Value >= minMoveDistance.Value) { History.HistoryChangeList personChanges; personService.InactivatePerson(familyMember.Person, inactiveReason, $"Received a Change of Address (NCOA) notice that was for more than {minMoveDistance} miles away.", out personChanges); if (personChanges.Any()) { HistoryService.SaveChanges( rockContext, typeof(Person), SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), familyMember.PersonId, personChanges, false); } } HistoryService.SaveChanges( rockContext, typeof(Person), SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), familyMember.PersonId, changes, family.Name, typeof(Group), family.Id, false); } } } } } rockContext.SaveChanges(); } } } }
public HistoryController(HistoryService historyService) { _historyService = historyService ?? throw new ArgumentNullException(nameof(historyService)); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { if (RegistrantState != null) { RockContext rockContext = new RockContext(); var personService = new PersonService(rockContext); var registrantService = new RegistrationRegistrantService(rockContext); var registrantFeeService = new RegistrationRegistrantFeeService(rockContext); var registrationTemplateFeeService = new RegistrationTemplateFeeService(rockContext); var registrationTemplateFeeItemService = new RegistrationTemplateFeeItemService(rockContext); RegistrationRegistrant registrant = null; if (RegistrantState.Id > 0) { registrant = registrantService.Get(RegistrantState.Id); } var previousRegistrantPersonIds = registrantService.Queryable().Where(a => a.RegistrationId == RegistrantState.RegistrationId) .Where(r => r.PersonAlias != null) .Select(r => r.PersonAlias.PersonId) .ToList(); bool newRegistrant = false; var registrantChanges = new History.HistoryChangeList(); if (registrant == null) { newRegistrant = true; registrant = new RegistrationRegistrant(); registrant.RegistrationId = RegistrantState.RegistrationId; registrantService.Add(registrant); registrantChanges.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, "Registrant"); } if (!registrant.PersonAliasId.Equals(ppPerson.PersonAliasId)) { string prevPerson = (registrant.PersonAlias != null && registrant.PersonAlias.Person != null) ? registrant.PersonAlias.Person.FullName : string.Empty; string newPerson = ppPerson.PersonName; newRegistrant = true; History.EvaluateChange(registrantChanges, "Person", prevPerson, newPerson); } int?personId = ppPerson.PersonId.Value; registrant.PersonAliasId = ppPerson.PersonAliasId.Value; // Get the name of registrant for history string registrantName = "Unknown"; if (ppPerson.PersonId.HasValue) { var person = personService.Get(ppPerson.PersonId.Value); if (person != null) { registrantName = person.FullName; } } // set their status (wait list / registrant) registrant.OnWaitList = !tglWaitList.Checked; History.EvaluateChange(registrantChanges, "Cost", registrant.Cost, cbCost.Text.AsDecimal()); registrant.Cost = cbCost.Text.AsDecimal(); History.EvaluateChange(registrantChanges, "Discount Applies", registrant.DiscountApplies, cbDiscountApplies.Checked); registrant.DiscountApplies = cbDiscountApplies.Checked; if (!Page.IsValid) { return; } // Remove/delete any registrant fees that are no longer in UI with quantity foreach (var dbFee in registrant.Fees.ToList()) { if (!RegistrantState.FeeValues.Keys.Contains(dbFee.RegistrationTemplateFeeId) || RegistrantState.FeeValues[dbFee.RegistrationTemplateFeeId] == null || !RegistrantState.FeeValues[dbFee.RegistrationTemplateFeeId] .Any(f => f.RegistrationTemplateFeeItemId == dbFee.RegistrationTemplateFeeItemId && f.Quantity > 0)) { var feeOldValue = string.Format("'{0}' Fee (Quantity:{1:N0}, Cost:{2:C2}, Option:{3}", dbFee.RegistrationTemplateFee.Name, dbFee.Quantity, dbFee.Cost, dbFee.Option); registrantChanges.AddChange(History.HistoryVerb.Delete, History.HistoryChangeType.Record, "Fee").SetOldValue(feeOldValue); registrant.Fees.Remove(dbFee); registrantFeeService.Delete(dbFee); } } // Add/Update any of the fees from UI foreach (var uiFee in RegistrantState.FeeValues.Where(f => f.Value != null)) { foreach (var uiFeeOption in uiFee.Value) { var dbFee = registrant.Fees .Where(f => f.RegistrationTemplateFeeId == uiFee.Key && f.RegistrationTemplateFeeItemId == uiFeeOption.RegistrationTemplateFeeItemId) .FirstOrDefault(); if (dbFee == null) { dbFee = new RegistrationRegistrantFee(); dbFee.RegistrationTemplateFeeId = uiFee.Key; var registrationTemplateFeeItem = uiFeeOption.RegistrationTemplateFeeItemId != null?registrationTemplateFeeItemService.GetNoTracking(uiFeeOption.RegistrationTemplateFeeItemId.Value) : null; if (registrationTemplateFeeItem != null) { dbFee.Option = registrationTemplateFeeItem.Name; } dbFee.RegistrationTemplateFeeItemId = uiFeeOption.RegistrationTemplateFeeItemId; registrant.Fees.Add(dbFee); } var templateFee = dbFee.RegistrationTemplateFee; if (templateFee == null) { templateFee = registrationTemplateFeeService.Get(uiFee.Key); } string feeName = templateFee != null ? templateFee.Name : "Fee"; if (!string.IsNullOrWhiteSpace(uiFeeOption.FeeLabel)) { feeName = string.Format("{0} ({1})", feeName, uiFeeOption.FeeLabel); } if (dbFee.Id <= 0) { registrantChanges.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, "Fee").SetNewValue(feeName); } History.EvaluateChange(registrantChanges, feeName + " Quantity", dbFee.Quantity, uiFeeOption.Quantity); dbFee.Quantity = uiFeeOption.Quantity; History.EvaluateChange(registrantChanges, feeName + " Cost", dbFee.Cost, uiFeeOption.Cost); dbFee.Cost = uiFeeOption.Cost; } } if (TemplateState.RequiredSignatureDocumentTemplate != null) { var person = new PersonService(rockContext).Get(personId.Value); var documentService = new SignatureDocumentService(rockContext); var binaryFileService = new BinaryFileService(rockContext); SignatureDocument document = null; int?signatureDocumentId = hfSignedDocumentId.Value.AsIntegerOrNull(); int?binaryFileId = fuSignedDocument.BinaryFileId; if (signatureDocumentId.HasValue) { document = documentService.Get(signatureDocumentId.Value); } if (document == null && binaryFileId.HasValue) { var instance = new RegistrationInstanceService(rockContext).Get(RegistrationInstanceId); document = new SignatureDocument(); document.SignatureDocumentTemplateId = TemplateState.RequiredSignatureDocumentTemplate.Id; document.AppliesToPersonAliasId = registrant.PersonAliasId.Value; document.AssignedToPersonAliasId = registrant.PersonAliasId.Value; document.Name = string.Format( "{0}_{1}", instance != null ? instance.Name : TemplateState.Name, person != null ? person.FullName.RemoveSpecialCharacters() : string.Empty); document.Status = SignatureDocumentStatus.Signed; document.LastStatusDate = RockDateTime.Now; documentService.Add(document); } if (document != null) { int?origBinaryFileId = document.BinaryFileId; document.BinaryFileId = binaryFileId; if (origBinaryFileId.HasValue && origBinaryFileId.Value != document.BinaryFileId) { // if a new the binaryFile was uploaded, mark the old one as Temporary so that it gets cleaned up var oldBinaryFile = binaryFileService.Get(origBinaryFileId.Value); if (oldBinaryFile != null && !oldBinaryFile.IsTemporary) { oldBinaryFile.IsTemporary = true; } } // ensure the IsTemporary is set to false on binaryFile associated with this document if (document.BinaryFileId.HasValue) { var binaryFile = binaryFileService.Get(document.BinaryFileId.Value); if (binaryFile != null && binaryFile.IsTemporary) { binaryFile.IsTemporary = false; } } } } if (!registrant.IsValid) { // Controls will render the error messages return; } // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges() rockContext.WrapTransaction(() => { rockContext.SaveChanges(); registrant.LoadAttributes(); // NOTE: We will only have Registration Attributes displayed and editable on Registrant Detail. // To Edit Person or GroupMember Attributes, they will have to go the PersonDetail or GroupMemberDetail blocks foreach (var field in TemplateState.Forms .SelectMany(f => f.Fields .Where(t => t.FieldSource == RegistrationFieldSource.RegistrantAttribute && t.AttributeId.HasValue))) { var attribute = AttributeCache.Get(field.AttributeId.Value); if (attribute != null) { string originalValue = registrant.GetAttributeValue(attribute.Key); var fieldValue = RegistrantState.FieldValues .Where(f => f.Key == field.Id) .Select(f => f.Value.FieldValue) .FirstOrDefault(); string newValue = fieldValue != null ? fieldValue.ToString() : string.Empty; if ((originalValue ?? string.Empty).Trim() != (newValue ?? string.Empty).Trim()) { string formattedOriginalValue = string.Empty; if (!string.IsNullOrWhiteSpace(originalValue)) { formattedOriginalValue = attribute.FieldType.Field.FormatValue(null, originalValue, attribute.QualifierValues, false); } string formattedNewValue = string.Empty; if (!string.IsNullOrWhiteSpace(newValue)) { formattedNewValue = attribute.FieldType.Field.FormatValue(null, newValue, attribute.QualifierValues, false); } History.EvaluateChange(registrantChanges, attribute.Name, formattedOriginalValue, formattedNewValue); } if (fieldValue != null) { registrant.SetAttributeValue(attribute.Key, fieldValue.ToString()); } } } registrant.SaveAttributeValues(rockContext); }); if (newRegistrant && TemplateState.GroupTypeId.HasValue && ppPerson.PersonId.HasValue) { using (var newRockContext = new RockContext()) { var reloadedRegistrant = new RegistrationRegistrantService(newRockContext).Get(registrant.Id); if (reloadedRegistrant != null && reloadedRegistrant.Registration != null && reloadedRegistrant.Registration.Group != null && reloadedRegistrant.Registration.Group.GroupTypeId == TemplateState.GroupTypeId.Value) { int?groupRoleId = TemplateState.GroupMemberRoleId.HasValue ? TemplateState.GroupMemberRoleId.Value : reloadedRegistrant.Registration.Group.GroupType.DefaultGroupRoleId; if (groupRoleId.HasValue) { var groupMemberService = new GroupMemberService(newRockContext); var groupMember = groupMemberService .Queryable().AsNoTracking() .Where(m => m.GroupId == reloadedRegistrant.Registration.Group.Id && m.PersonId == reloadedRegistrant.PersonId && m.GroupRoleId == groupRoleId.Value) .FirstOrDefault(); if (groupMember == null) { groupMember = new GroupMember(); groupMember.GroupId = reloadedRegistrant.Registration.Group.Id; groupMember.PersonId = ppPerson.PersonId.Value; groupMember.GroupRoleId = groupRoleId.Value; groupMember.GroupMemberStatus = TemplateState.GroupMemberStatus; groupMemberService.Add(groupMember); newRockContext.SaveChanges(); registrantChanges.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, string.Format("Registrant to {0} group", reloadedRegistrant.Registration.Group.Name)); } else { registrantChanges.AddChange(History.HistoryVerb.Modify, History.HistoryChangeType.Record, string.Format("Registrant to existing person in {0} group", reloadedRegistrant.Registration.Group.Name)); } if (reloadedRegistrant.GroupMemberId.HasValue && reloadedRegistrant.GroupMemberId.Value != groupMember.Id) { groupMemberService.Delete(reloadedRegistrant.GroupMember); newRockContext.SaveChanges(); registrantChanges.AddChange(History.HistoryVerb.Delete, History.HistoryChangeType.Record, string.Format("Registrant to previous person in {0} group", reloadedRegistrant.Registration.Group.Name)); } // Record this to the Person's and Registrants Notes and History... reloadedRegistrant.GroupMemberId = groupMember.Id; } } if (reloadedRegistrant.Registration.FirstName.IsNotNullOrWhiteSpace() && reloadedRegistrant.Registration.LastName.IsNotNullOrWhiteSpace()) { reloadedRegistrant.Registration.SavePersonNotesAndHistory(reloadedRegistrant.Registration.FirstName, reloadedRegistrant.Registration.LastName, this.CurrentPersonAliasId, previousRegistrantPersonIds); } newRockContext.SaveChanges(); } } HistoryService.SaveChanges( rockContext, typeof(Registration), Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(), registrant.RegistrationId, registrantChanges, "Registrant: " + registrantName, null, null); } NavigateToRegistration(); }
private void CreateDefaultHistoryServiceInstance() { var services = new ServiceCollection(); var mockStore = new Mock <IUserStore <ApplicationUser> >(); var mockOptionsAccessor = new Mock <IOptions <IdentityOptions> >(); var mockPasswordHasher = new Mock <IPasswordHasher <ApplicationUser> >(); var userValidators = new List <IUserValidator <ApplicationUser> >(); var validators = new List <IPasswordValidator <ApplicationUser> >(); var mockKeyNormalizer = new Mock <ILookupNormalizer>(); var mockErrors = new Mock <IdentityErrorDescriber>(); var mockServices = new Mock <IServiceProvider>(); var mockLogger = new Mock <ILogger <UserManager <ApplicationUser> > >(); var userManager = new UserManager <ApplicationUser>(mockStore.Object, mockOptionsAccessor.Object, mockPasswordHasher.Object, userValidators, validators, mockKeyNormalizer.Object, mockErrors.Object, mockServices.Object, mockLogger.Object); var userResolver = new UserResolver(userManager, _mapper); var bonusResolver = new BonusResolver(new Mock <IVendorService>().Object, new Mock <IBonusService>().Object, _mapper); services.AddTransient(sp => userManager); services.AddTransient(sp => userResolver); services.AddTransient(sp => bonusResolver); IServiceProvider serviceProvider = services.BuildServiceProvider(); var myProfile = new MapperProfile(); var configuration = new MapperConfiguration(cfg => { cfg.AddProfile(myProfile); cfg.ConstructServicesUsing(serviceProvider.GetService); }); _mapper = new Mapper(configuration); var historyGenerator = Generator .For <History>() .For(x => x.Id) .ChooseFrom(Guid.NewGuid()) .For(x => x.CreatorId) .ChooseFrom(Guid.NewGuid()) .For(x => x.BonusId) .ChooseFrom(Guid.NewGuid()) .For(x => x.CreatedDate) .ChooseFrom(DateTime.Now); _fakeHistoryDtos = historyGenerator.Generate(10).ToList(); _historyRepo = new Mock <IHistoryRepository>(); _historyRepo.Setup(s => s.GetAllAsync(default(CancellationToken))).ReturnsAsync(_mapper.Map <List <History> >(_fakeHistoryDtos)); _historyRepo.Setup(s => s.GetByIdAsync(It.IsAny <Guid>(), default(CancellationToken))).ReturnsAsync(_mapper.Map <History>(_fakeHistoryDtos[1])); _historyRepo.Setup(s => s.AddAsync(It.IsAny <History>(), default(CancellationToken))); _historyRepo.Setup(s => s.RemoveAsync(It.IsAny <Guid>(), default(CancellationToken))).ReturnsAsync(_mapper.Map <History>(_fakeHistoryDtos[0])); _historyRepo.Setup(s => s.GetBonusHistory(It.IsAny <Guid>(), default(CancellationToken))).ReturnsAsync(_mapper.Map <List <History> >(_fakeHistoryDtos)); _historyRepo.Setup(s => s.GetUserHistory(It.IsAny <Guid>(), default(CancellationToken))).ReturnsAsync(_mapper.Map <List <History> >(_fakeHistoryDtos)); _historyRepo.Setup(s => s.GetBonusHistoryByUsageDate(It.IsAny <Guid>(), It.IsAny <DateTime>(), It.IsAny <DateTime>(), default(CancellationToken))).ReturnsAsync(_mapper.Map <List <History> >(_fakeHistoryDtos)); _historyRepo.Setup(s => s.GetUserHistoryByUsageDate(It.IsAny <Guid>(), It.IsAny <DateTime>(), It.IsAny <DateTime>(), default(CancellationToken))).ReturnsAsync(_mapper.Map <List <History> >(_fakeHistoryDtos)); _historyRepo.Setup(x => x.GetCountHistoryByBonusIdAsync(It.IsAny <Guid>(), default(CancellationToken))) .ReturnsAsync(5); _bonusRepo = new Mock <IBonusRepository>(); _bonusRepo.Setup(x => x.UpdateBonusRatingAsync(It.IsAny <Guid>(), It.IsAny <double>(), default(CancellationToken))) .ReturnsAsync(new Bonus()); _bonusRepo.Setup(x => x.GetByIdAsync(It.IsAny <Guid>(), default(CancellationToken))) .ReturnsAsync(new Bonus()); _emailService = new Mock <IEmailService>(); _emailService.Setup(s => s.SendEmailAsync(It.IsAny <History>())); _mockEmailService = _emailService.Object; _mockhistoryRepository = _historyRepo.Object; _mockBonusRepository = _bonusRepo.Object; _historyService = new HistoryService(_mockhistoryRepository, _mockBonusRepository, _mockEmailService, _mapper); }
private async void LoadHistory() { HistoryList = await HistoryService.GetHistory(); }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute( RockContext rockContext, WorkflowAction action, Object entity, out List<string> errorMessages ) { errorMessages = new List<string>(); // get person Person person = null; string personAttributeValue = GetAttributeValue( action, "Person" ); Guid? guidPersonAttribute = personAttributeValue.AsGuidOrNull(); if ( guidPersonAttribute.HasValue ) { var attributePerson = AttributeCache.Read( guidPersonAttribute.Value, rockContext ); if ( attributePerson != null || attributePerson.FieldType.Class != "Rock.Field.Types.PersonFieldType" ) { string attributePersonValue = action.GetWorklowAttributeValue( guidPersonAttribute.Value ); if ( !string.IsNullOrWhiteSpace( attributePersonValue ) ) { Guid personAliasGuid = attributePersonValue.AsGuid(); if ( !personAliasGuid.IsEmpty() ) { person = new PersonAliasService( rockContext ).Queryable() .Where( a => a.Guid.Equals( personAliasGuid ) ) .Select( a => a.Person ) .FirstOrDefault(); if ( person == null ) { errorMessages.Add( string.Format( "Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString() ) ); return false; } } } } } if ( person == null ) { errorMessages.Add( "The attribute used to provide the person was invalid, or not of type 'Person'." ); return false; } // determine the phone type to edit DefinedValueCache phoneType = null; var phoneTypeAttributeValue = action.GetWorklowAttributeValue( GetAttributeValue( action, "PhoneTypeAttribute" ).AsGuid() ); if ( phoneTypeAttributeValue != null ) { phoneType = DefinedValueCache.Read( phoneTypeAttributeValue.AsGuid() ); } if ( phoneType == null ) { phoneType = DefinedValueCache.Read( GetAttributeValue( action, "PhoneType" ).AsGuid() ); } if ( phoneType == null ) { errorMessages.Add( "The phone type to be updated was not selected." ); return false; } // get the ignore blank setting var ignoreBlanks = GetActionAttributeValue( action, "IgnoreBlankValues" ).AsBoolean( true ); // get the new phone number value string phoneNumberValue = GetAttributeValue( action, "PhoneNumber" ); Guid? phoneNumberValueGuid = phoneNumberValue.AsGuidOrNull(); if ( phoneNumberValueGuid.HasValue ) { phoneNumberValue = action.GetWorklowAttributeValue( phoneNumberValueGuid.Value ); } else { phoneNumberValue = phoneNumberValue.ResolveMergeFields( GetMergeFields( action ) ); } phoneNumberValue = PhoneNumber.CleanNumber( phoneNumberValue ); // gets value indicating if phone number is unlisted string unlistedValue = GetAttributeValue( action, "Unlisted" ); Guid? unlistedValueGuid = unlistedValue.AsGuidOrNull(); if ( unlistedValueGuid.HasValue ) { unlistedValue = action.GetWorklowAttributeValue( unlistedValueGuid.Value ); } else { unlistedValue = unlistedValue.ResolveMergeFields( GetMergeFields( action ) ); } bool? unlisted = unlistedValue.AsBooleanOrNull(); // gets value indicating if messaging should be enabled for phone number string smsEnabledValue = GetAttributeValue( action, "MessagingEnabled" ); Guid? smsEnabledValueGuid = smsEnabledValue.AsGuidOrNull(); if ( smsEnabledValueGuid.HasValue ) { smsEnabledValue = action.GetWorklowAttributeValue( smsEnabledValueGuid.Value ); } else { smsEnabledValue = smsEnabledValue.ResolveMergeFields( GetMergeFields( action ) ); } bool? smsEnabled = smsEnabledValue.AsBooleanOrNull(); var phoneNumber = person.PhoneNumbers.FirstOrDefault( n => n.NumberTypeValueId == phoneType.Id ); string oldValue = string.Empty; if ( phoneNumber == null ) { phoneNumber = new PhoneNumber { NumberTypeValueId = phoneType.Id }; person.PhoneNumbers.Add( phoneNumber ); } else { oldValue = phoneNumber.NumberFormattedWithCountryCode; } if ( !string.IsNullOrWhiteSpace( phoneNumberValue ) || !ignoreBlanks ) { phoneNumber.Number = phoneNumberValue; } if ( unlisted.HasValue ) { phoneNumber.IsUnlisted = unlisted.Value; } if ( smsEnabled.HasValue ) { phoneNumber.IsMessagingEnabled = smsEnabled.Value; } var changes = new List<string>(); History.EvaluateChange( changes, string.Format( "{0} Phone", phoneType.Value ), oldValue, phoneNumber.NumberFormattedWithCountryCode ); if ( changes.Any() ) { changes.Add( string.Format( "<em>(Updated by the '{0}' workflow)</em>", action.ActionType.ActivityType.WorkflowType.Name ) ); HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes, false ); } rockContext.SaveChanges(); action.AddLogEntry( string.Format( "Updated {0} phone for {1} to {2}.", phoneType.Value, person.FullName, phoneNumber.NumberFormattedWithCountryCode ) ); return true; }
public IActionResult Get([FromBody] HistoryCredentials operation) { var idClaim = User.Claims.FirstOrDefault(x => x.Type.Equals(JwtRegisteredClaimNames.Jti, StringComparison.InvariantCultureIgnoreCase)); if (idClaim != null) { Guid tokenGuid = Guid.Parse(idClaim.ToString().Remove(0, 5)); var histService = new HistoryService(); var scService = new ScoreService(); var workerCount = 0; var oldCount = 1; List <Operations> historyList = new List <Operations>(); while (workerCount != oldCount) { try { var showHistory = histService.ReturnHistory(new HistoryModel { ClientId = tokenGuid, Id = workerCount, ScoreFrom = operation.ScoreFrom }, "SELECT * FROM viewhistories WHERE (clientid = @clientid AND scorefrom=@scorefrom AND id >= @id) OR (takerid = @clientid AND scoreto=@scorefrom AND id >= @id);"); oldCount = workerCount; workerCount = showHistory.Id + 1; if (showHistory.SentTime <= operation.TimeTo && showHistory.SentTime >= operation.TimeFrom) { Operations hist = new Operations(); if (showHistory.ScoreFrom == "4000000000") { hist.Type = "Пополнение"; } else if (scService.ReturnScore( new ScoreModel { ClientId = tokenGuid, NumScore = showHistory.ScoreTo }, "SELECT * FROM scores WHERE numscore=@numscore AND clientid=@clientid") != null && scService.ReturnScore( new ScoreModel { ClientId = tokenGuid, NumScore = showHistory.ScoreFrom }, "SELECT * FROM scores WHERE numscore=@numscore AND clientid=@clientid") != null) { hist.Type = "Перевод"; } else { hist.Type = "Платёж"; } hist.ByTemplate = showHistory.Template; hist.SentTime = showHistory.SentTime; hist.ScoreFrom = showHistory.ScoreFrom; hist.ScoreTo = showHistory.ScoreTo; hist.HowMuch = showHistory.HowMuch; historyList.Add(hist); } } catch { workerCount = oldCount; } } return(Ok(historyList)); } return(BadRequest("No claim")); }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { if (_entity == null) { return; } var entityTypeCache = EntityTypeCache.Get(_entity.GetType(), false); if (entityTypeCache == null) { return; } var rockContext = new RockContext(); var historyService = new HistoryService(rockContext); IQueryable <History> qry; if (entityTypeCache.Id == EntityTypeCache.GetId <Rock.Model.Person>()) { // If this is History for a Person, also include any History for any of their Families int? groupEntityTypeId = EntityTypeCache.GetId <Rock.Model.Group>(); List <int> familyIds = (_entity as Person).GetFamilies().Select(a => a.Id).ToList(); qry = historyService.Queryable().Include(a => a.CreatedByPersonAlias.Person) .Where(h => (h.EntityTypeId == entityTypeCache.Id && h.EntityId == _entity.Id) || (h.EntityTypeId == groupEntityTypeId && familyIds.Contains(h.EntityId))); // as per issue #1594, if relatedEntityType is an Attribute then check View Authorization var attributeEntity = EntityTypeCache.Get(Rock.SystemGuid.EntityType.ATTRIBUTE.AsGuid()); var personAttributes = new AttributeService(rockContext).GetByEntityTypeId(entityTypeCache.Id).ToList().Select(a => AttributeCache.Get(a)); var allowedAttributeIds = GetAuthorizedPersonAttributes(rockContext).Select(a => a.Id).ToList(); qry = qry.Where(a => (a.RelatedEntityTypeId == attributeEntity.Id) ? allowedAttributeIds.Contains(a.RelatedEntityId.Value) : true); } else { qry = historyService.Queryable().Include(a => a.CreatedByPersonAlias.Person) .Where(h => (h.EntityTypeId == entityTypeCache.Id && h.EntityId == _entity.Id)); } var historyCategories = new CategoryService(rockContext).GetByEntityTypeId(EntityTypeCache.GetId <Rock.Model.History>()).ToList().Select(a => CategoryCache.Get(a)); var allowedCategoryIds = historyCategories.Where(a => a.IsAuthorized(Rock.Security.Authorization.VIEW, CurrentPerson)).Select(a => a.Id).ToList(); qry = qry.Where(a => allowedCategoryIds.Contains(a.CategoryId)); int?categoryId = GetCategoryId(); if (categoryId.HasValue) { qry = qry.Where(a => a.CategoryId == categoryId.Value); } int?personId = gfSettings.GetUserPreference("Who").AsIntegerOrNull(); if (personId.HasValue) { qry = qry.Where(h => h.CreatedByPersonAlias.PersonId == personId.Value); } var drp = new DateRangePicker(); drp.DelimitedValues = gfSettings.GetUserPreference("Date Range"); if (drp.LowerValue.HasValue) { qry = qry.Where(h => h.CreatedDateTime >= drp.LowerValue.Value); } if (drp.UpperValue.HasValue) { DateTime upperDate = drp.UpperValue.Value.Date.AddDays(1); qry = qry.Where(h => h.CreatedDateTime < upperDate); } // Combine history records that were saved at the same time var historySummaryList = historyService.GetHistorySummary(qry); string summary = gfSettings.GetUserPreference("Summary Contains"); if (!string.IsNullOrWhiteSpace(summary)) { historySummaryList = historySummaryList.Where(h => h.HistoryList.Any(x => x.SummaryHtml.IndexOf(summary, StringComparison.OrdinalIgnoreCase) >= 0)).ToList(); } SortProperty sortProperty = gHistory.SortProperty; if (sortProperty != null) { historySummaryList = historySummaryList.AsQueryable().Sort(sortProperty).ToList(); } else { historySummaryList = historySummaryList.OrderByDescending(t => t.CreatedDateTime).ToList(); } gHistory.DataSource = historySummaryList; gHistory.EntityTypeId = EntityTypeCache.Get <History>().Id; gHistory.DataBind(); }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { if (Page.IsValid) { if (ViewMode == VIEW_MODE_EDIT) { int personEntityTypeId = EntityTypeCache.Read(typeof(Person)).Id; var rockContext = new RockContext(); rockContext.WrapTransaction(() => { var changes = new List <string>(); foreach (int attributeId in AttributeList) { var attribute = AttributeCache.Read(attributeId); if (Person != null && ViewMode == VIEW_MODE_EDIT && attribute.IsAuthorized(Authorization.EDIT, CurrentPerson)) { Control attributeControl = fsAttributes.FindControl(string.Format("attribute_field_{0}", attribute.Id)); if (attributeControl != null) { string originalValue = Person.GetAttributeValue(attribute.Key); string newValue = attribute.FieldType.Field.GetEditValue(attributeControl, attribute.QualifierValues); Rock.Attribute.Helper.SaveAttributeValue(Person, attribute, newValue, rockContext); // Check for changes to write to history if ((originalValue ?? string.Empty).Trim() != (newValue ?? string.Empty).Trim()) { string formattedOriginalValue = string.Empty; if (!string.IsNullOrWhiteSpace(originalValue)) { formattedOriginalValue = attribute.FieldType.Field.FormatValue(null, originalValue, attribute.QualifierValues, false); } string formattedNewValue = string.Empty; if (!string.IsNullOrWhiteSpace(newValue)) { formattedNewValue = attribute.FieldType.Field.FormatValue(null, newValue, attribute.QualifierValues, false); } History.EvaluateChange(changes, attribute.Name, formattedOriginalValue, formattedNewValue); } } } } if (changes.Any()) { HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), Person.Id, changes); } }); } else if (ViewMode == VIEW_MODE_ORDER) { // Split and deliminate again to remove trailing delimiter var attributeOrder = hfAttributeOrder.Value.SplitDelimitedValues().ToList().AsDelimited(","); SetUserPreference(_preferenceKey, attributeOrder); BindAttributes(); } ViewMode = VIEW_MODE_VIEW; CreateControls(false); } }
public HistoryController(ComponentHistoryService componentHistoryService, HistoryService historyService, ComponentRegistryService componentRegistryService) { _componentHistoryService = componentHistoryService ?? throw new ArgumentNullException(nameof(componentHistoryService)); _historyService = historyService ?? throw new ArgumentNullException(nameof(historyService)); _componentRegistryService = componentRegistryService ?? throw new ArgumentNullException(nameof(componentRegistryService)); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Before public void setUp() throws Exception //JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET: public virtual void setUp() { commandExecutor = ((ProcessEngineConfigurationImpl)bootstrapRule.ProcessEngine.ProcessEngineConfiguration).CommandExecutorTxRequired; historyService = bootstrapRule.ProcessEngine.HistoryService; }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Before public void initServices() public virtual void initServices() { runtimeService = rule.RuntimeService; taskService = rule.TaskService; historyService = rule.HistoryService; }
private void _SetHistoryItemToTextBox(HistoryService.HistoryItem historyItem) { _TextBox.Text = ((HistoryService.HistoryItem)historyItem).String; _TextBox.CaretIndex = _TextBox.Text.Length; }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages) { errorMessages = new List <string>(); var personGuid = GetAttributeValue(action, "Person", true).AsGuidOrNull(); if (personGuid == null) { errorMessages.Add("Person Add History requires a valid person"); return(false); } var categoryGuid = GetAttributeValue(action, "Category").AsGuid(); var category = new CategoryService(rockContext).Get(categoryGuid); if (category == null) { errorMessages.Add("Person Add History requires a valid category"); return(false); } PersonAliasService personAliasService = new PersonAliasService(rockContext); var personAlias = personAliasService.Get(personGuid.Value); if (personAlias != null) { var person = personAlias.Person; var entityTypeId = EntityTypeCache.GetId(typeof(Rock.Model.Person)); var workflowEntityTypeId = EntityTypeCache.GetId(typeof(Rock.Model.Workflow)); var mergeFields = GetMergeFields(action); var caption = GetAttributeValue(action, "Caption").ResolveMergeFields(mergeFields); var summary = GetAttributeValue(action, "Summary").ResolveMergeFields(mergeFields); var verb = GetAttributeValue(action, "Verb").ResolveMergeFields(mergeFields); var personChanges = new History.HistoryChangeList(); personChanges.AddCustom(verb, History.HistoryChangeType.Record.ToString(), summary.Truncate(250)); personChanges.First().Caption = caption; if (action?.Activity?.Workflow != null && action.Activity.WorkflowId != 0) { personChanges.First().RelatedEntityTypeId = workflowEntityTypeId; personChanges.First().RelatedEntityId = action.Activity.WorkflowId; } HistoryService.SaveChanges( rockContext, typeof(Rock.Model.Person), category.Guid, person.Id, personChanges, true ); return(true); } else { errorMessages.Add("Person Add History requires a valid person"); return(false); } }
private void ApplyHistoryChange(HistoryService.HistoryUpdatePart change) { if (change == null) return; ApplyHistoryUpdateAccount(change.Account); ApplyHistoryUpdateAccountSettings(change.AccountSettings); ApplyHistoryUpdateAccountSettingsColumn(change.AccountSettingsColumn); ApplyHistoryUpdateAccountSettingsExportDirectory(change.AccountSettingsExportDirectory); ApplyHistoryUpdateAccountSettingsImportDirectory(change.AccountSettingsImportDirectory); ApplyHistoryUpdateAccountSettingsSheduleTime(change.AccountSettingsSheduleTime); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Before public void setUp() public virtual void setUp() { runtimeService = engineRule.RuntimeService; historyService = engineRule.HistoryService; externalTaskService = engineRule.ExternalTaskService; }
/// <summary> /// Handles the Click event of the lbMerge control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void lbMerge_Click(object sender, EventArgs e) { if (MergeData.People.Count < 2) { nbPeople.Visible = true; return; } bool reconfirmRequired = (MergeData.People.Select(p => p.Email).Distinct().Count() > 1 && MergeData.People.Where(p => p.HasLogins).Any()); GetValuesSelection(); int?primaryPersonId = null; var oldPhotos = new List <int>(); var rockContext = new RockContext(); rockContext.WrapTransaction(() => { var personService = new PersonService(rockContext); var userLoginService = new UserLoginService(rockContext); var familyService = new GroupService(rockContext); var familyMemberService = new GroupMemberService(rockContext); var binaryFileService = new BinaryFileService(rockContext); var phoneNumberService = new PhoneNumberService(rockContext); Person primaryPerson = personService.Get(MergeData.PrimaryPersonId ?? 0); if (primaryPerson != null) { primaryPersonId = primaryPerson.Id; var changes = new List <string>(); foreach (var p in MergeData.People.Where(p => p.Id != primaryPerson.Id)) { changes.Add(string.Format("Merged <span class='field-value'>{0} [ID: {1}]</span> with this record.", p.FullName, p.Id)); } // Photo Id int?newPhotoId = MergeData.GetSelectedValue(MergeData.GetProperty("Photo")).Value.AsIntegerOrNull(); if (!primaryPerson.PhotoId.Equals(newPhotoId)) { changes.Add("Modified the photo."); primaryPerson.PhotoId = newPhotoId; } primaryPerson.TitleValueId = GetNewIntValue("Title", changes); primaryPerson.FirstName = GetNewStringValue("FirstName", changes); primaryPerson.NickName = GetNewStringValue("NickName", changes); primaryPerson.MiddleName = GetNewStringValue("MiddleName", changes); primaryPerson.LastName = GetNewStringValue("LastName", changes); primaryPerson.SuffixValueId = GetNewIntValue("Suffix", changes); primaryPerson.RecordTypeValueId = GetNewIntValue("RecordType", changes); primaryPerson.RecordStatusValueId = GetNewIntValue("RecordStatus", changes); primaryPerson.RecordStatusReasonValueId = GetNewIntValue("RecordStatusReason", changes); primaryPerson.ConnectionStatusValueId = GetNewIntValue("ConnectionStatus", changes); primaryPerson.IsDeceased = GetNewBoolValue("Deceased", changes); primaryPerson.Gender = (Gender)GetNewEnumValue("Gender", typeof(Gender), changes); primaryPerson.MaritalStatusValueId = GetNewIntValue("MaritalStatus", changes); primaryPerson.SetBirthDate(GetNewDateTimeValue("BirthDate", changes)); primaryPerson.AnniversaryDate = GetNewDateTimeValue("AnniversaryDate", changes); primaryPerson.GraduationYear = GetNewIntValue("GraduationYear", changes); primaryPerson.Email = GetNewStringValue("Email", changes); primaryPerson.IsEmailActive = GetNewBoolValue("EmailActive", changes); primaryPerson.EmailNote = GetNewStringValue("EmailNote", changes); primaryPerson.EmailPreference = (EmailPreference)GetNewEnumValue("EmailPreference", typeof(EmailPreference), changes); primaryPerson.SystemNote = GetNewStringValue("InactiveReasonNote", changes); primaryPerson.SystemNote = GetNewStringValue("SystemNote", changes); // Update phone numbers var phoneTypes = DefinedTypeCache.Read(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE.AsGuid()).DefinedValues; foreach (var phoneType in phoneTypes) { var phoneNumber = primaryPerson.PhoneNumbers.Where(p => p.NumberTypeValueId == phoneType.Id).FirstOrDefault(); string oldValue = phoneNumber != null ? phoneNumber.Number : string.Empty; string key = "phone_" + phoneType.Id.ToString(); string newValue = GetNewStringValue(key, changes); if (!oldValue.Equals(newValue, StringComparison.OrdinalIgnoreCase)) { // New phone doesn't match old if (!string.IsNullOrWhiteSpace(newValue)) { // New value exists if (phoneNumber == null) { // Old value didn't exist... create new phone record phoneNumber = new PhoneNumber { NumberTypeValueId = phoneType.Id }; primaryPerson.PhoneNumbers.Add(phoneNumber); } // Update phone number phoneNumber.Number = newValue; } else { // New value doesn't exist if (phoneNumber != null) { // old value existed.. delete it primaryPerson.PhoneNumbers.Remove(phoneNumber); phoneNumberService.Delete(phoneNumber); } } } } // Save the new record rockContext.SaveChanges(); // Update the attributes primaryPerson.LoadAttributes(rockContext); foreach (var property in MergeData.Properties.Where(p => p.Key.StartsWith("attr_"))) { string attributeKey = property.Key.Substring(5); string oldValue = primaryPerson.GetAttributeValue(attributeKey) ?? string.Empty; string newValue = GetNewStringValue(property.Key, changes) ?? string.Empty; if (!oldValue.Equals(newValue)) { var attribute = primaryPerson.Attributes[attributeKey]; Rock.Attribute.Helper.SaveAttributeValue(primaryPerson, attribute, newValue, rockContext); } } HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), primaryPerson.Id, changes); // Delete the unselected photos string photoKeeper = primaryPerson.PhotoId.HasValue ? primaryPerson.PhotoId.Value.ToString() : string.Empty; foreach (var photoValue in MergeData.Properties .Where(p => p.Key == "Photo") .SelectMany(p => p.Values) .Where(v => v.Value != "" && v.Value != photoKeeper) .Select(v => v.Value)) { int photoId = 0; if (int.TryParse(photoValue, out photoId)) { var photo = binaryFileService.Get(photoId); if (photo != null) { string errorMessages; if (binaryFileService.CanDelete(photo, out errorMessages)) { binaryFileService.Delete(photo); } } } } rockContext.SaveChanges(); // Delete merged person's family records and any families that would be empty after merge foreach (var p in MergeData.People.Where(p => p.Id != primaryPersonId.Value)) { // Delete the merged person's phone numbers (we've already updated the primary persons values) foreach (var phoneNumber in phoneNumberService.GetByPersonId(p.Id)) { phoneNumberService.Delete(phoneNumber); } // If there was more than one email address and user has logins, then set any of the local // logins ( database & AD ) to require a reconfirmation if (reconfirmRequired) { foreach (var login in userLoginService.GetByPersonId(p.Id)) { var component = Rock.Security.AuthenticationContainer.GetComponent(login.EntityType.Name); if (!component.RequiresRemoteAuthentication) { login.IsConfirmed = false; } } } rockContext.SaveChanges(); // Delete the merged person's other family member records and the family if they were the only one in the family Guid familyGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid(); foreach (var familyMember in familyMemberService.Queryable().Where(m => m.PersonId == p.Id && m.Group.GroupType.Guid == familyGuid)) { familyMemberService.Delete(familyMember); rockContext.SaveChanges(); // Get the family var family = familyService.Queryable("Members").Where(f => f.Id == familyMember.GroupId).FirstOrDefault(); if (!family.Members.Any()) { // If there are not any other family members, delete the family record. var oldFamilyChanges = new List <string>(); History.EvaluateChange(oldFamilyChanges, "Family", family.Name, string.Empty); HistoryService.SaveChanges(rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), primaryPersonId.Value, oldFamilyChanges, family.Name, typeof(Group), family.Id); // If theres any people that have this group as a giving group, set it to null (the person being merged should be the only one) foreach (Person gp in personService.Queryable().Where(g => g.GivingGroupId == family.Id)) { gp.GivingGroupId = null; } // Delete the family familyService.Delete(family); rockContext.SaveChanges(); } } } } }); foreach (var p in MergeData.People.Where(p => p.Id != primaryPersonId.Value)) { // Run merge proc to merge all associated data var parms = new Dictionary <string, object>(); parms.Add("OldId", p.Id); parms.Add("NewId", primaryPersonId.Value); DbService.ExecuteCommand("spCrm_PersonMerge", CommandType.StoredProcedure, parms); } NavigateToLinkedPage("PersonDetailPage", "PersonId", primaryPersonId.Value); }
/// <summary> /// Handles the Click event of the btnSubmit control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnSubmit_Click(object sender, EventArgs e) { nbUnsubscribeSuccessMessage.Visible = false; nbEmailPreferenceSuccessMessage.Visible = false; if (rbUnsubscribe.Checked && rbUnsubscribe.Visible) { UnsubscribeFromLists(); return; } if (_person != null) { var changes = new List <string>(); var rockContext = new RockContext(); var service = new PersonService(rockContext); var person = service.Get(_person.Id); if (person != null) { EmailPreference emailPreference = EmailPreference.EmailAllowed; if (rbEmailPreferenceNoMassEmails.Checked) { emailPreference = EmailPreference.NoMassEmails; } if (rbEmailPreferenceDoNotEmail.Checked || rbNotInvolved.Checked) { emailPreference = EmailPreference.DoNotEmail; } History.EvaluateChange(changes, "Email Preference", person.EmailPreference, emailPreference); person.EmailPreference = emailPreference; if (rbNotInvolved.Checked) { var newRecordStatus = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE); if (newRecordStatus != null) { History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(person.RecordStatusValueId), newRecordStatus.Value); person.RecordStatusValueId = newRecordStatus.Id; } var newInactiveReason = DefinedValueCache.Read(ddlInactiveReason.SelectedValue.AsInteger()); if (newInactiveReason != null) { History.EvaluateChange(changes, "Record Status Reason", DefinedValueCache.GetName(person.RecordStatusReasonValueId), newInactiveReason.Value); person.RecordStatusReasonValueId = newInactiveReason.Id; } var newReviewReason = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_REVIEW_REASON_SELF_INACTIVATED); if (newReviewReason != null) { History.EvaluateChange(changes, "Review Reason", DefinedValueCache.GetName(person.ReviewReasonValueId), newReviewReason.Value); person.ReviewReasonValueId = newReviewReason.Id; } // If the inactive reason note is the same as the current review reason note, update it also. if ((person.InactiveReasonNote ?? string.Empty) == (person.ReviewReasonNote ?? string.Empty)) { History.EvaluateChange(changes, "Inactive Reason Note", person.InactiveReasonNote, tbInactiveNote.Text); person.InactiveReasonNote = tbInactiveNote.Text; } History.EvaluateChange(changes, "Review Reason Note", person.ReviewReasonNote, tbInactiveNote.Text); person.ReviewReasonNote = tbInactiveNote.Text; } else { var newRecordStatus = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE); if (newRecordStatus != null) { History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(person.RecordStatusValueId), newRecordStatus.Value); person.RecordStatusValueId = newRecordStatus.Id; } History.EvaluateChange(changes, "Record Status Reason", DefinedValueCache.GetName(person.RecordStatusReasonValueId), string.Empty); person.RecordStatusReasonValueId = null; } HistoryService.AddChanges( rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), person.Id, changes, CurrentPersonAliasId); rockContext.SaveChanges(); nbEmailPreferenceSuccessMessage.Visible = true; return; } } }
public async void SearchText(string query) { try { // create the square template and attach it to the wide template ITileSquarePeekImageAndText04 squareContent = TileContentFactory.CreateTileSquarePeekImageAndText04(); squareContent.TextBodyWrap.Text = query; squareContent.Image.Src = "ms-appx:///Assets/Logo.png"; squareContent.Branding = TileBranding.Name; // send the notification TileUpdateManager.CreateTileUpdaterForApplication().Update(squareContent.CreateNotification()); } catch { } //Show loader: //LoadingPanel.Visibility = Windows.UI.Xaml.Visibility.Visible; //LoadingPanel2.Visibility = Windows.UI.Xaml.Visibility.Visible; var result = await DataLoader.LoadAsync(() => SearchService.SearchAsync(query)); //TODO Hide loader //LoadingPanel.Visibility = Windows.UI.Xaml.Visibility.Collapsed; //LoadingPanel2.Visibility = Windows.UI.Xaml.Visibility.Collapsed; if (result != null) { if (result.Results != null && result.Results.Count > 0) { //ResultPanel.Visibility = Windows.UI.Xaml.Visibility.Visible; //ResultPanel2.Visibility = Windows.UI.Xaml.Visibility.Visible; //ResultGrid.DataContext = result; //SnapGrid.DataContext = result; SearchWord = result; //ResultList.ItemsSource = result.Results; var historyList = await HistoryService.GetHistory(); HistoryList = historyList; //Scroller.Focus(Windows.UI.Xaml.FocusState.Programmatic); Right = true; //Scroller.ScrollToHorizontalOffset(double.MaxValue); } else { //TODO: Show niet in woordenboek SearchWord = null; //NotAvailablePanel.Visibility = Windows.UI.Xaml.Visibility.Visible; //NotAvailablePanel2.Visibility = Windows.UI.Xaml.Visibility.Visible; } } else { //TODO: Show error DataLoader.LoadingState = LoadingState.Error; //ErrorPanel.Visibility = Windows.UI.Xaml.Visibility.Visible; //ErrorPanel2.Visibility = Windows.UI.Xaml.Visibility.Visible; } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { if (IsUserAuthorized(Rock.Security.Authorization.EDIT)) { var rockContext = new RockContext(); rockContext.WrapTransaction(() => { var personService = new PersonService(rockContext); var changes = new List <string>(); var person = personService.Get(Person.Id); int?orphanedPhotoId = null; if (person.PhotoId != imgPhoto.BinaryFileId) { orphanedPhotoId = person.PhotoId; person.PhotoId = imgPhoto.BinaryFileId; if (orphanedPhotoId.HasValue) { if (person.PhotoId.HasValue) { changes.Add("Modified the photo."); } else { changes.Add("Deleted the photo."); } } else if (person.PhotoId.HasValue) { changes.Add("Added a photo."); } } int?newTitleId = ddlTitle.SelectedValueAsInt(); History.EvaluateChange(changes, "Title", DefinedValueCache.GetName(person.TitleValueId), DefinedValueCache.GetName(newTitleId)); person.TitleValueId = newTitleId; History.EvaluateChange(changes, "First Name", person.FirstName, tbFirstName.Text); person.FirstName = tbFirstName.Text; string nickName = string.IsNullOrWhiteSpace(tbNickName.Text) ? tbFirstName.Text : tbNickName.Text; History.EvaluateChange(changes, "Nick Name", person.NickName, nickName); person.NickName = tbNickName.Text; History.EvaluateChange(changes, "Middle Name", person.MiddleName, tbMiddleName.Text); person.MiddleName = tbMiddleName.Text; History.EvaluateChange(changes, "Last Name", person.LastName, tbLastName.Text); person.LastName = tbLastName.Text; int?newSuffixId = ddlSuffix.SelectedValueAsInt(); History.EvaluateChange(changes, "Suffix", DefinedValueCache.GetName(person.SuffixValueId), DefinedValueCache.GetName(newSuffixId)); person.SuffixValueId = newSuffixId; var birthMonth = person.BirthMonth; var birthDay = person.BirthDay; var birthYear = person.BirthYear; var birthday = bpBirthDay.SelectedDate; if (birthday.HasValue) { // If setting a future birthdate, subtract a century until birthdate is not greater than today. var today = RockDateTime.Today; while (birthday.Value.CompareTo(today) > 0) { birthday = birthday.Value.AddYears(-100); } person.BirthMonth = birthday.Value.Month; person.BirthDay = birthday.Value.Day; if (birthday.Value.Year != DateTime.MinValue.Year) { person.BirthYear = birthday.Value.Year; } else { person.BirthYear = null; } } else { person.SetBirthDate(null); } History.EvaluateChange(changes, "Birth Month", birthMonth, person.BirthMonth); History.EvaluateChange(changes, "Birth Day", birthDay, person.BirthDay); History.EvaluateChange(changes, "Birth Year", birthYear, person.BirthYear); int?graduationYear = null; if (ypGraduation.SelectedYear.HasValue) { graduationYear = ypGraduation.SelectedYear.Value; } History.EvaluateChange(changes, "Graduation Year", person.GraduationYear, graduationYear); person.GraduationYear = graduationYear; History.EvaluateChange(changes, "Anniversary Date", person.AnniversaryDate, dpAnniversaryDate.SelectedDate); person.AnniversaryDate = dpAnniversaryDate.SelectedDate; var newGender = rblGender.SelectedValue.ConvertToEnum <Gender>(); History.EvaluateChange(changes, "Gender", person.Gender, newGender); person.Gender = newGender; int?newMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt(); History.EvaluateChange(changes, "Marital Status", DefinedValueCache.GetName(person.MaritalStatusValueId), DefinedValueCache.GetName(newMaritalStatusId)); person.MaritalStatusValueId = newMaritalStatusId; int?newConnectionStatusId = ddlConnectionStatus.SelectedValueAsInt(); History.EvaluateChange(changes, "Connection Status", DefinedValueCache.GetName(person.ConnectionStatusValueId), DefinedValueCache.GetName(newConnectionStatusId)); person.ConnectionStatusValueId = newConnectionStatusId; var phoneNumberTypeIds = new List <int>(); bool smsSelected = false; foreach (RepeaterItem item in rContactInfo.Items) { HiddenField hfPhoneType = item.FindControl("hfPhoneType") as HiddenField; PhoneNumberBox pnbPhone = item.FindControl("pnbPhone") as PhoneNumberBox; CheckBox cbUnlisted = item.FindControl("cbUnlisted") as CheckBox; CheckBox cbSms = item.FindControl("cbSms") as CheckBox; if (hfPhoneType != null && pnbPhone != null && cbSms != null && cbUnlisted != null) { if (!string.IsNullOrWhiteSpace(PhoneNumber.CleanNumber(pnbPhone.Number))) { int phoneNumberTypeId; if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId)) { var phoneNumber = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId); string oldPhoneNumber = string.Empty; if (phoneNumber == null) { phoneNumber = new PhoneNumber { NumberTypeValueId = phoneNumberTypeId }; person.PhoneNumbers.Add(phoneNumber); } else { oldPhoneNumber = phoneNumber.NumberFormattedWithCountryCode; } phoneNumber.CountryCode = PhoneNumber.CleanNumber(pnbPhone.CountryCode); phoneNumber.Number = PhoneNumber.CleanNumber(pnbPhone.Number); // Only allow one number to have SMS selected if (smsSelected) { phoneNumber.IsMessagingEnabled = false; } else { phoneNumber.IsMessagingEnabled = cbSms.Checked; smsSelected = cbSms.Checked; } phoneNumber.IsUnlisted = cbUnlisted.Checked; phoneNumberTypeIds.Add(phoneNumberTypeId); History.EvaluateChange( changes, string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumberTypeId)), oldPhoneNumber, phoneNumber.NumberFormattedWithCountryCode); } } } } // Remove any blank numbers var phoneNumberService = new PhoneNumberService(rockContext); foreach (var phoneNumber in person.PhoneNumbers .Where(n => n.NumberTypeValueId.HasValue && !phoneNumberTypeIds.Contains(n.NumberTypeValueId.Value)) .ToList()) { History.EvaluateChange( changes, string.Format("{0} Phone", DefinedValueCache.GetName(phoneNumber.NumberTypeValueId)), phoneNumber.ToString(), string.Empty); person.PhoneNumbers.Remove(phoneNumber); phoneNumberService.Delete(phoneNumber); } History.EvaluateChange(changes, "Email", person.Email, tbEmail.Text); person.Email = tbEmail.Text.Trim(); History.EvaluateChange(changes, "Email Active", person.IsEmailActive, cbIsEmailActive.Checked); person.IsEmailActive = cbIsEmailActive.Checked; var newEmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>(); History.EvaluateChange(changes, "Email Preference", person.EmailPreference, newEmailPreference); person.EmailPreference = newEmailPreference; int?newGivingGroupId = ddlGivingGroup.SelectedValueAsId(); if (person.GivingGroupId != newGivingGroupId) { string oldGivingGroupName = person.GivingGroup != null ? person.GivingGroup.Name : string.Empty; string newGivingGroupName = newGivingGroupId.HasValue ? ddlGivingGroup.Items.FindByValue(newGivingGroupId.Value.ToString()).Text : string.Empty; History.EvaluateChange(changes, "Giving Group", oldGivingGroupName, newGivingGroupName); } person.GivingGroupId = newGivingGroupId; int?newRecordStatusId = ddlRecordStatus.SelectedValueAsInt(); History.EvaluateChange(changes, "Record Status", DefinedValueCache.GetName(person.RecordStatusValueId), DefinedValueCache.GetName(newRecordStatusId)); person.RecordStatusValueId = newRecordStatusId; int?newRecordStatusReasonId = null; if (person.RecordStatusValueId.HasValue && person.RecordStatusValueId.Value == DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE)).Id) { newRecordStatusReasonId = ddlReason.SelectedValueAsInt(); } History.EvaluateChange(changes, "Inactive Reason", DefinedValueCache.GetName(person.RecordStatusReasonValueId), DefinedValueCache.GetName(newRecordStatusReasonId)); person.RecordStatusReasonValueId = newRecordStatusReasonId; History.EvaluateChange(changes, "Inactive Reason Note", person.InactiveReasonNote, tbInactiveReasonNote.Text); person.InactiveReasonNote = tbInactiveReasonNote.Text.Trim(); // Save any Removed/Added Previous Names var personPreviousNameService = new PersonPreviousNameService(rockContext); var databasePreviousNames = personPreviousNameService.Queryable().Where(a => a.PersonAlias.PersonId == person.Id).ToList(); foreach (var deletedPreviousName in databasePreviousNames.Where(a => !PersonPreviousNamesState.Any(p => p.Guid == a.Guid))) { personPreviousNameService.Delete(deletedPreviousName); History.EvaluateChange( changes, "Previous Name", deletedPreviousName.ToString(), string.Empty); } foreach (var addedPreviousName in PersonPreviousNamesState.Where(a => !databasePreviousNames.Any(d => d.Guid == a.Guid))) { addedPreviousName.PersonAliasId = person.PrimaryAliasId.Value; personPreviousNameService.Add(addedPreviousName); History.EvaluateChange( changes, "Previous Name", string.Empty, addedPreviousName.ToString()); } if (person.IsValid) { if (rockContext.SaveChanges() > 0) { if (changes.Any()) { HistoryService.SaveChanges( rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), Person.Id, changes); } if (orphanedPhotoId.HasValue) { BinaryFileService binaryFileService = new BinaryFileService(rockContext); var binaryFile = binaryFileService.Get(orphanedPhotoId.Value); if (binaryFile != null) { string errorMessage; if (binaryFileService.CanDelete(binaryFile, out errorMessage)) { binaryFileService.Delete(binaryFile); rockContext.SaveChanges(); } } } // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up if (imgPhoto.CropBinaryFileId.HasValue) { if (imgPhoto.CropBinaryFileId != person.PhotoId) { BinaryFileService binaryFileService = new BinaryFileService(rockContext); var binaryFile = binaryFileService.Get(imgPhoto.CropBinaryFileId.Value); if (binaryFile != null && binaryFile.IsTemporary) { string errorMessage; if (binaryFileService.CanDelete(binaryFile, out errorMessage)) { binaryFileService.Delete(binaryFile); rockContext.SaveChanges(); } } } } } Response.Redirect(string.Format("~/Person/{0}", Person.Id), false); } }); } }
/// <summary> /// When implemented by a class, enables a server control to process an event raised when a form is posted to the server. /// </summary> /// <param name="eventArgument">A <see cref="T:System.String" /> that represents an optional event argument to be passed to the event handler.</param> public void RaisePostBackEvent(string eventArgument) { if (eventArgument == "StatusUpdate" && hfAction.Value.IsNotNullOrWhiteSpace()) { var batchesSelected = new List <int>(); gBatchList.SelectedKeys.ToList().ForEach(b => batchesSelected.Add(b.ToString().AsInteger())); if (batchesSelected.Any()) { var newStatus = hfAction.Value == "OPEN" ? BatchStatus.Open : BatchStatus.Closed; var rockContext = new RockContext(); var batchService = new FinancialBatchService(rockContext); var batchesToUpdate = batchService.Queryable() .Where(b => batchesSelected.Contains(b.Id) && b.Status != newStatus) .ToList(); foreach (var batch in batchesToUpdate) { var changes = new History.HistoryChangeList(); History.EvaluateChange(changes, "Status", batch.Status, newStatus); string errorMessage; if (!batch.IsValidBatchStatusChange(batch.Status, newStatus, this.CurrentPerson, out errorMessage)) { maWarningDialog.Show(errorMessage, ModalAlertType.Warning); return; } if (batch.IsAutomated && batch.Status == BatchStatus.Pending && newStatus != BatchStatus.Pending) { errorMessage = string.Format("{0} is an automated batch and the status can not be modified when the status is pending. The system will automatically set this batch to OPEN when all transactions have been downloaded.", batch.Name); maWarningDialog.Show(errorMessage, ModalAlertType.Warning); return; } batch.Status = newStatus; if (!batch.IsValid) { string message = string.Format("Unable to update status for the selected batches.<br/><br/>{0}", batch.ValidationResults.AsDelimited("<br/>")); maWarningDialog.Show(message, ModalAlertType.Warning); return; } HistoryService.SaveChanges( rockContext, typeof(FinancialBatch), Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(), batch.Id, changes, false); } rockContext.SaveChanges(); nbResult.Text = string.Format( "{0} batches were {1}.", batchesToUpdate.Count().ToString("N0"), newStatus == BatchStatus.Open ? "opened" : "closed"); nbResult.NotificationBoxType = NotificationBoxType.Success; nbResult.Visible = true; } else { nbResult.Text = string.Format("There were not any batches selected."); nbResult.NotificationBoxType = NotificationBoxType.Warning; nbResult.Visible = true; } ddlAction.SelectedIndex = 0; hfAction.Value = string.Empty; BindGrid(); } }
/// <summary> /// Determines whether [has event happened] [the specified entity]. /// </summary> /// <param name="followingEvent">The following event.</param> /// <param name="entity">The entity.</param> /// <param name="lastNotified">The last notified.</param> /// <returns></returns> public override bool HasEventHappened(FollowingEventType followingEvent, IEntity entity, DateTime?lastNotified) { if (followingEvent != null && entity != null) { var personAlias = entity as PersonAlias; if (personAlias != null && personAlias.Person != null) { // // Get all the attributes/settings we need. // int daysBack = GetAttributeValue(followingEvent, "MaxDaysBack").AsInteger(); string targetOldValue = GetAttributeValue(followingEvent, "OldValue") ?? string.Empty; string targetNewValue = GetAttributeValue(followingEvent, "NewValue") ?? string.Empty; string targetPersonGuid = GetAttributeValue(followingEvent, "Person"); bool negateChangedBy = GetAttributeValue(followingEvent, "NegatePerson").AsBoolean(); bool matchBothValues = GetAttributeValue(followingEvent, "MatchBoth").AsBoolean(); var attributes = GetAttributeValue(followingEvent, "Fields").Split(',').Select(a => a.Trim()); // // Populate all the other random variables we need for processing. // PersonAlias targetPersonAlias = new PersonAliasService(new RockContext()).Get(targetPersonGuid.AsGuid()); DateTime daysBackDate = RockDateTime.Now.AddDays(-daysBack); var person = personAlias.Person; int personEntityTypeId = EntityTypeCache.Get(typeof(Person)).Id; int categoryId = CategoryCache.Get(Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid()).Id; // // Start building the basic query. We want all History items that are for // people objects and use the Demographic Changes category. // var qry = new HistoryService(new RockContext()).Queryable() .Where(h => h.EntityTypeId == personEntityTypeId && h.EntityId == person.Id && h.CategoryId == categoryId); // // Put in our limiting dates. We always limit by our days back date, // and conditionally limit based on the last time we notified the // stalker - I mean the follower. // if (lastNotified.HasValue) { qry = qry.Where(h => h.CreatedDateTime >= lastNotified.Value); } qry = qry.Where(h => h.CreatedDateTime >= daysBackDate); // // Walk each history item found that matches our filter. // Dictionary <string, List <PersonHistoryChange> > changes = new Dictionary <string, List <PersonHistoryChange> >(); foreach (var history in qry.ToList()) { // // Check what kind of change this was. // History.HistoryVerb?historyVerb = history.Verb.ConvertToEnumOrNull <History.HistoryVerb>(); string title = history.ValueName; // // Walk each attribute entered by the user to match against. // foreach (var attribute in attributes) { PersonHistoryChange change = new PersonHistoryChange(); change.Old = history.OldValue; change.New = history.NewValue; // // Check if this is one of the attributes we are following. // if (title != null && title.Trim() == attribute) { // // Get the ValuePair object to work with. // if (!changes.ContainsKey(attribute)) { changes.Add(attribute, new List <PersonHistoryChange>()); } change.PersonId = history.CreatedByPersonId; changes[attribute].Add(change); // // If the value has been changed back to what it was then ignore the change. // if (changes[attribute].Count >= 2) { var changesList = changes[attribute].ToList(); if (changesList[changesList.Count - 2].Old == changesList[changesList.Count - 1].New) { changes.Remove(title); } } } } } // // Walk the list of final changes and see if we need to notify. // foreach (var items in changes.Values) { foreach (PersonHistoryChange change in items) { // // Check for a match on the person who made the change. // if (targetPersonAlias == null || targetPersonAlias.Id == 0 || (!negateChangedBy && targetPersonAlias.PersonId == change.PersonId) || (negateChangedBy && targetPersonAlias.PersonId != change.PersonId)) { bool oldMatch = (string.IsNullOrEmpty(targetOldValue) || targetOldValue == change.Old); bool newMatch = (string.IsNullOrEmpty(targetNewValue) || targetNewValue == change.New); // // If the old value and the new value match then trigger the event. // if ((matchBothValues && oldMatch && newMatch) || (!matchBothValues && (oldMatch || newMatch))) { return(true); } } } } } } return(false); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Before public void init() public virtual void init() { runtimeService = engineRule.RuntimeService; historyService = engineRule.HistoryService; }
private void StartHistoryTracking(Commitment commitment, Apprenticeship apprenticeship, CallerType callerType, string userId, string userName) { _historyService = new HistoryService(_historyRepository); _historyService.TrackUpdate(commitment, CommitmentChangeType.EditedApprenticeship.ToString(), commitment.Id, null, callerType, userId, apprenticeship.ProviderId, apprenticeship.EmployerAccountId, userName); _historyService.TrackUpdate(apprenticeship, ApprenticeshipChangeType.Updated.ToString(), null, apprenticeship.Id, callerType, userId, apprenticeship.ProviderId, apprenticeship.EmployerAccountId, userName); }
/// <summary> /// Processes the NCOA results: Mark all family move addresses as previous, add the new address as current; and processed. /// If minMoveDistance is specified, mark the family as inactive if the family moved further than the specified distance. /// </summary> /// <param name="inactiveReason">The inactive reason.</param> /// <param name="minMoveDistance">The minimum move distance.</param> /// <param name="homeValueId">The home value identifier.</param> /// <param name="previousValueId">The previous value identifier.</param> private void ProcessNcoaResultsFamilyMove(DefinedValueCache inactiveReason, decimal?minMoveDistance, int?homeValueId, int?previousValueId) { List <int> ncoaIds = null; // Process 'Move' NCOA Types (The 'Family' move types will be processed first) using (var rockContext = new RockContext()) { ncoaIds = new NcoaHistoryService(rockContext) .Queryable().AsNoTracking() .Where(n => n.Processed == Processed.NotProcessed && n.NcoaType == NcoaType.Move && n.MoveType == MoveType.Family) .Select(n => n.Id) .ToList(); } foreach (int id in ncoaIds) { using (var rockContext = new RockContext()) { // Get the NCOA record and make sure it still hasn't been processed var ncoaHistory = new NcoaHistoryService(rockContext).Get(id); if (ncoaHistory != null && ncoaHistory.Processed == Processed.NotProcessed) { var ncoaHistoryService = new NcoaHistoryService(rockContext); var groupService = new GroupService(rockContext); var groupLocationService = new GroupLocationService(rockContext); var locationService = new LocationService(rockContext); var personService = new PersonService(rockContext); var familyChanges = new History.HistoryChangeList(); ncoaHistory.Processed = Processed.ManualUpdateRequired; // If we're able to mark the existing address as previous and successfully create a new home address.. var previousGroupLocation = MarkAsPreviousLocation(ncoaHistory, groupLocationService, previousValueId, familyChanges); if (previousGroupLocation != null) { if (AddNewHomeLocation(ncoaHistory, locationService, groupLocationService, homeValueId, familyChanges, previousGroupLocation.IsMailingLocation, previousGroupLocation.IsMappedLocation)) { // set the status to 'Complete' ncoaHistory.Processed = Processed.Complete; // Look for any other moves for the same family and to same address, and set their status to complete as well foreach (var ncoaIndividual in ncoaHistoryService .Queryable().Where(n => n.Processed == Processed.NotProcessed && n.NcoaType == NcoaType.Move && n.FamilyId == ncoaHistory.FamilyId && n.Id != ncoaHistory.Id && n.UpdatedStreet1 == ncoaHistory.UpdatedStreet1)) { ncoaIndividual.Processed = Processed.Complete; } // If there were any changes, write to history and check to see if person should be inactivated if (familyChanges.Any()) { var family = groupService.Get(ncoaHistory.FamilyId); if (family != null) { foreach (var fm in family.Members) { if (ncoaHistory.MoveDistance.HasValue && minMoveDistance.HasValue && ncoaHistory.MoveDistance.Value >= minMoveDistance.Value) { History.HistoryChangeList personChanges; personService.InactivatePerson(fm.Person, inactiveReason, $"Received a Change of Address (NCOA) notice that was for more than {minMoveDistance} miles away.", out personChanges); if (personChanges.Any()) { HistoryService.SaveChanges( rockContext, typeof(Person), SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(), fm.PersonId, personChanges, false); } } HistoryService.SaveChanges( rockContext, typeof(Person), SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), fm.PersonId, familyChanges, family.Name, typeof(Group), family.Id, false); } } } } } rockContext.SaveChanges(); } } } }
static async Task Main(string[] args) { ICardRepository <Card> cardRepository = new CardRepository <Card>(); IGameRepository <Game> gameRepository = new GameRepository <Game>(); IPlayerRepository <Player> playerRepository = new PlayerRepository <Player>(); IRoundRepository <Round> roundRepository = new RoundRepository <Round>(); HistoryService history = new HistoryService(gameRepository, roundRepository); GameService service = new GameService(gameRepository, playerRepository, roundRepository, cardRepository); #region //var uiViewModel = new GameServiceViewModel { PlayerName = "Scott", BotQuantity = 2 }; //var result = await service.StartGame(uiViewModel); //foreach (var user in result.Users) //{ // Console.WriteLine(user.ToString()); // foreach (var card in user.Cards) // { // Console.WriteLine($"{ card.CardRank} : { card.CardSuit}"); // } // Console.WriteLine("========================"); //} //Console.ReadKey(); //Console.WriteLine("===================SECOND ROUND==================="); //Console.WriteLine("===================SECOND ROUND==================="); //var resultAfteNextRound = await service.StartNextRoundForPlayers(result.Users); //foreach (var user in resultAfteNextRound.Users) //{ // Console.WriteLine(user.ToString()); // foreach (var card in user.Cards) // { // Console.WriteLine($"{ card.CardRank} : { card.CardSuit}"); // } // Console.WriteLine("========================"); //} //Console.ReadKey(); //var final = await service.FinalPointsCount(resultAfteNextRound.Users); //foreach (var user in final.Users) //{ // Console.WriteLine(user.ToString()); // foreach (var card in user.Cards) // { // Console.WriteLine($"{ card.CardRank} : { card.CardSuit}"); // } // Console.WriteLine("========================"); //} #endregion #region try { var query = await history.GetAllRoundsFromParticularGame(100); } catch (Exception e) { Console.WriteLine(e.Message); } //var roundhistory = history.CreateUserHistoryVM(query); //foreach (var round in roundhistory) //{ // Console.WriteLine(round.UserName); // foreach (var card in round.Cards) // { // Console.WriteLine($"{card.CardRank} : {card.CardSuit}"); // } //} #endregion }
private void OnHistoryChanged(object sender, HistoryService.History e) => RunUnderDispatcher(new Action(() => worker.ApplyHistoryChanges(e)));
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { if (Person != null) { var familyIds = families.Select(f => f.Key).ToList(); var qry = new HistoryService(new RockContext()).Queryable("CreatedByPersonAlias.Person") .Where(h => (h.EntityTypeId == personEntityTypeId && h.EntityId == Person.Id) || (h.EntityTypeId == groupEntityTypeId && familyIds.Contains(h.EntityId))); int categoryId = int.MinValue; if (int.TryParse(gfSettings.GetUserPreference("Category"), out categoryId)) { qry = qry.Where(h => h.CategoryId == categoryId); } string summary = gfSettings.GetUserPreference("Summary Contains"); if (!string.IsNullOrWhiteSpace(summary)) { qry = qry.Where(h => h.Summary.Contains(summary)); } int personId = int.MinValue; if (int.TryParse(gfSettings.GetUserPreference("Who"), out personId)) { qry = qry.Where(h => h.CreatedByPersonAlias.PersonId == personId); } var drp = new DateRangePicker(); drp.DelimitedValues = gfSettings.GetUserPreference("Date Range"); if (drp.LowerValue.HasValue) { qry = qry.Where(h => h.CreatedDateTime >= drp.LowerValue.Value); } if (drp.UpperValue.HasValue) { DateTime upperDate = drp.UpperValue.Value.Date.AddDays(1); qry = qry.Where(h => h.CreatedDateTime < upperDate); } SortProperty sortProperty = gHistory.SortProperty; if (sortProperty != null) { qry = qry.Sort(sortProperty); } else { qry = qry.OrderByDescending(t => t.CreatedDateTime); } // Combine history records that were saved at the same time var histories = new List <History>(); foreach (var history in qry) { var existingHistory = histories .Where(h => h.CreatedByPersonAliasId == history.CreatedByPersonAliasId && h.CreatedDateTime == history.CreatedDateTime && h.EntityTypeId == history.EntityTypeId && h.EntityId == history.EntityId && h.CategoryId == history.CategoryId && h.RelatedEntityTypeId == history.RelatedEntityTypeId && h.RelatedEntityId == history.RelatedEntityId).FirstOrDefault(); if (existingHistory != null) { existingHistory.Summary += "<br/>" + history.Summary; } else { histories.Add(history); } } gHistory.DataSource = histories.Select(h => new { Id = h.Id, CategoryId = h.CategoryId, Category = h.Category != null ? h.Category.Name : "", EntityTypeId = h.EntityTypeId, EntityId = h.EntityId, Caption = h.Caption ?? string.Empty, Summary = h.Summary, RelatedEntityTypeId = h.RelatedEntityTypeId ?? 0, RelatedEntityId = h.RelatedEntityId ?? 0, CreatedByPersonId = h.CreatedByPersonAlias != null ? h.CreatedByPersonAlias.PersonId : 0, PersonName = h.CreatedByPersonAlias != null && h.CreatedByPersonAlias.Person != null ? h.CreatedByPersonAlias.Person.NickName + " " + h.CreatedByPersonAlias.Person.LastName : "", CreatedDateTime = h.CreatedDateTime }).ToList(); gHistory.DataBind(); } }
private void OnHistoryChanged(object sender, HistoryService.History e) => worker.ApplyHistoryChanges(e);
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages) { errorMessages = new List <string>(); // get person Person person = null; string personAttributeValue = GetAttributeValue(action, "Person"); Guid? guidPersonAttribute = personAttributeValue.AsGuidOrNull(); if (guidPersonAttribute.HasValue) { var attributePerson = AttributeCache.Get(guidPersonAttribute.Value, rockContext); if (attributePerson != null || attributePerson.FieldType.Class != "Rock.Field.Types.PersonFieldType") { string attributePersonValue = action.GetWorkflowAttributeValue(guidPersonAttribute.Value); if (!string.IsNullOrWhiteSpace(attributePersonValue)) { Guid personAliasGuid = attributePersonValue.AsGuid(); if (!personAliasGuid.IsEmpty()) { person = new PersonAliasService(rockContext).Queryable() .Where(a => a.Guid.Equals(personAliasGuid)) .Select(a => a.Person) .FirstOrDefault(); if (person == null) { errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString())); return(false); } } } } } if (person == null) { errorMessages.Add("The attribute used to provide the person was invalid, or not of type 'Person'."); return(false); } // determine the location type to edit DefinedValueCache locationType = null; var locationTypeAttributeValue = action.GetWorkflowAttributeValue(GetAttributeValue(action, "LocationTypeAttribute").AsGuid()); if (locationTypeAttributeValue != null) { locationType = DefinedValueCache.Get(locationTypeAttributeValue.AsGuid()); } if (locationType == null) { locationType = DefinedValueCache.Get(GetAttributeValue(action, "LocationType").AsGuid()); } if (locationType == null) { errorMessages.Add("The location type to be updated was not selected."); return(false); } // get the new phone number value Location location = null; string locationValue = GetAttributeValue(action, "Location"); Guid? locationGuid = locationValue.AsGuidOrNull(); if (!locationGuid.HasValue || locationGuid.Value.IsEmpty()) { string locationAttributeValue = GetAttributeValue(action, "LocationAttribute"); Guid? locationAttributeValueGuid = locationAttributeValue.AsGuidOrNull(); if (locationAttributeValueGuid.HasValue) { locationGuid = action.GetWorkflowAttributeValue(locationAttributeValueGuid.Value).AsGuidOrNull(); } } if (locationGuid.HasValue) { location = new LocationService(rockContext).Get(locationGuid.Value); } if (location == null) { errorMessages.Add("The location value could not be determined."); return(false); } // gets value indicating if location is a mailing location string mailingValue = GetAttributeValue(action, "IsMailing"); Guid? mailingValueGuid = mailingValue.AsGuidOrNull(); if (mailingValueGuid.HasValue) { mailingValue = action.GetWorkflowAttributeValue(mailingValueGuid.Value); } else { mailingValue = mailingValue.ResolveMergeFields(GetMergeFields(action)); } bool?mailing = mailingValue.AsBooleanOrNull(); // gets value indicating if location is a mapped location string mappedValue = GetAttributeValue(action, "IsMapped"); Guid? mappedValueGuid = mappedValue.AsGuidOrNull(); if (mappedValueGuid.HasValue) { mappedValue = action.GetWorkflowAttributeValue(mappedValueGuid.Value); } else { mappedValue = mappedValue.ResolveMergeFields(GetMergeFields(action)); } bool?mapped = mappedValue.AsBooleanOrNull(); var savePreviousAddress = GetAttributeValue(action, "SavePreviousAddress").AsBoolean(); var locationService = new LocationService(rockContext); locationService.Verify(location, false); var groupLocationService = new GroupLocationService(rockContext); foreach (var family in person.GetFamilies(rockContext).ToList()) { bool locationUpdated = false; if (savePreviousAddress) { // Get all existing addresses of the specified type var groupLocations = family.GroupLocations.Where(l => l.GroupLocationTypeValueId == locationType.Id).ToList(); // Create a new address of the specified type, saving all existing addresses of that type as Previous Addresses // Use the specified Is Mailing and Is Mapped values from the action's parameters if they are set, // otherwise set them to true if any of the existing addresses of that type have those values set to true GroupService.AddNewGroupAddress(rockContext, family, locationType.Guid.ToString(), location.Id, true, $"the {action.ActionTypeCache.ActivityType.WorkflowType.Name} workflow", mailing ?? groupLocations.Any(x => x.IsMailingLocation), mapped ?? groupLocations.Any(x => x.IsMappedLocation)); } else { var groupLocation = family.GroupLocations.FirstOrDefault(l => l.GroupLocationTypeValueId == locationType.Id); string oldValue = string.Empty; if (groupLocation == null) { groupLocation = new GroupLocation(); groupLocation.GroupId = family.Id; groupLocation.GroupLocationTypeValueId = locationType.Id; groupLocationService.Add(groupLocation); } else { oldValue = groupLocation.Location.ToString(); } locationUpdated = oldValue != location.ToString(); groupLocation.Location = location; if (mailing.HasValue) { if (((oldValue == string.Empty) ? null : groupLocation.IsMailingLocation.ToString()) != mailing.Value.ToString()) { locationUpdated = true; } groupLocation.IsMailingLocation = mailing.Value; } if (mapped.HasValue) { if (((oldValue == string.Empty) ? null : groupLocation.IsMappedLocation.ToString()) != mapped.Value.ToString()) { locationUpdated = true; } groupLocation.IsMappedLocation = mapped.Value; } } if (locationUpdated) { var groupChanges = new History.HistoryChangeList(); groupChanges.AddChange(History.HistoryVerb.Modify, History.HistoryChangeType.Record, "Location").SourceOfChange = $"{action.ActionTypeCache.ActivityType.WorkflowType.Name} workflow"; foreach (var fm in family.Members) { HistoryService.SaveChanges( rockContext, typeof(Person), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(), fm.PersonId, groupChanges, family.Name, typeof(Group), family.Id, false, null, rockContext.SourceOfChange); } } rockContext.SaveChanges(); action.AddLogEntry(string.Format("Updated the {0} location for {1} (family: {2}) to {3}", locationType.Value, person.FullName, family.Name, location.ToString())); } return(true); }
public void ApplyHistoryChanges(HistoryService.History e) { if (!IsLoaded) return; ApplyHistoryChange(e?.Add); ApplyHistoryChange(e?.Change); ApplyHistoryRemove(e?.Remove); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Before public void createProcessEngine() public virtual void createProcessEngine() { runtimeService = engineRule.RuntimeService; historyService = engineRule.HistoryService; }
private void ApplyHistoryRemove(HistoryService.HistoryRemovePart remove) { if (remove == null) return; ApplyHistoryRemoveAccount(remove.Account); ApplyHistoryRemoveAccountSettingsColumn(remove.AccountSettingsColumn); ApplyHistoryRemoveAccountSettingsExportDirectory(remove.AccountSettingsExportDirectory); ApplyHistoryRemoveAccountSettingsImportDirectory(remove.AccountSettingsImportDirectory); ApplyHistoryRemoveAccountSettingsSheduleTime(remove.AccountSettingsSheduleTime); }
// // Swipe Panel Events // private void ProcessSwipe(string swipeData) { try { using (var rockContext = new RockContext()) { // create swipe object SwipePaymentInfo swipeInfo = new SwipePaymentInfo(swipeData); swipeInfo.Amount = this.Amounts.Sum(a => a.Value); // if not anonymous then add contact info to the gateway transaction if (this.AnonymousGiverPersonAliasId != this.SelectedGivingUnit.PersonAliasId) { var giver = new PersonAliasService(rockContext).Queryable("Person, Person.PhoneNumbers").Where(p => p.Id == this.SelectedGivingUnit.PersonAliasId).FirstOrDefault(); swipeInfo.FirstName = giver.Person.NickName; swipeInfo.LastName = giver.Person.LastName; if (giver.Person.PhoneNumbers != null) { Guid homePhoneValueGuid = new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME); var homephone = giver.Person.PhoneNumbers.Where(p => p.NumberTypeValue.Guid == homePhoneValueGuid).FirstOrDefault(); if (homephone != null) { swipeInfo.Phone = homephone.NumberFormatted; } } var homeLocation = giver.Person.GetHomeLocation(); if (homeLocation != null) { swipeInfo.Street1 = homeLocation.Street1; if (!string.IsNullOrWhiteSpace(homeLocation.Street2)) { swipeInfo.Street2 = homeLocation.Street2; } swipeInfo.City = homeLocation.City; swipeInfo.State = homeLocation.State; swipeInfo.PostalCode = homeLocation.PostalCode; } } // add comment to the transaction swipeInfo.Comment1 = GetAttributeValue("PaymentComment"); // get gateway FinancialGateway financialGateway = null; GatewayComponent gateway = null; Guid? gatewayGuid = GetAttributeValue("CreditCardGateway").AsGuidOrNull(); if (gatewayGuid.HasValue) { financialGateway = new FinancialGatewayService(rockContext).Get(gatewayGuid.Value); if (financialGateway != null) { financialGateway.LoadAttributes(rockContext); } gateway = financialGateway.GetGatewayComponent(); } if (gateway != null) { string errorMessage = string.Empty; var transaction = gateway.Charge(financialGateway, swipeInfo, out errorMessage); if (transaction != null) { _transactionCode = transaction.TransactionCode; var personName = new PersonAliasService(rockContext) .Queryable().AsNoTracking() .Where(a => a.Id == this.SelectedGivingUnit.PersonAliasId) .Select(a => a.Person.NickName + " " + a.Person.LastName) .FirstOrDefault(); transaction.AuthorizedPersonAliasId = this.SelectedGivingUnit.PersonAliasId; transaction.TransactionDateTime = RockDateTime.Now; transaction.FinancialGatewayId = financialGateway.Id; var txnType = DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION)); transaction.TransactionTypeValueId = txnType.Id; transaction.Summary = swipeInfo.Comment1; if (transaction.FinancialPaymentDetail == null) { transaction.FinancialPaymentDetail = new FinancialPaymentDetail(); } transaction.FinancialPaymentDetail.SetFromPaymentInfo(swipeInfo, gateway, rockContext); Guid sourceGuid = Guid.Empty; if (Guid.TryParse(GetAttributeValue("Source"), out sourceGuid)) { var source = DefinedValueCache.Get(sourceGuid); if (source != null) { transaction.SourceTypeValueId = source.Id; } } foreach (var accountAmount in this.Amounts.Where(a => a.Value > 0)) { var transactionDetail = new FinancialTransactionDetail(); transactionDetail.Amount = accountAmount.Value; transactionDetail.AccountId = accountAmount.Key; transaction.TransactionDetails.Add(transactionDetail); var account = new FinancialAccountService(rockContext).Get(accountAmount.Key); } var batchService = new FinancialBatchService(rockContext); // Get the batch var batch = batchService.Get( GetAttributeValue("BatchNamePrefix"), swipeInfo.CurrencyTypeValue, swipeInfo.CreditCardTypeValue, transaction.TransactionDateTime.Value, financialGateway.GetBatchTimeOffset()); var batchChanges = new History.HistoryChangeList(); if (batch.Id == 0) { batchChanges.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, "Batch"); History.EvaluateChange(batchChanges, "Batch Name", string.Empty, batch.Name); History.EvaluateChange(batchChanges, "Status", null, batch.Status); History.EvaluateChange(batchChanges, "Start Date/Time", null, batch.BatchStartDateTime); History.EvaluateChange(batchChanges, "End Date/Time", null, batch.BatchEndDateTime); } decimal newControlAmount = batch.ControlAmount + transaction.TotalAmount; History.EvaluateChange(batchChanges, "Control Amount", batch.ControlAmount.FormatAsCurrency(), newControlAmount.FormatAsCurrency()); batch.ControlAmount = newControlAmount; transaction.BatchId = batch.Id; batch.Transactions.Add(transaction); rockContext.WrapTransaction(() => { rockContext.SaveChanges(); HistoryService.SaveChanges( rockContext, typeof(FinancialBatch), Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(), batch.Id, batchChanges ); }); // send receipt in one is configured and not giving anonymously if (!string.IsNullOrWhiteSpace(GetAttributeValue("ReceiptEmail")) && (this.AnonymousGiverPersonAliasId != this.SelectedGivingUnit.PersonAliasId)) { _receiptSent = true; SendReceipt(); } HidePanels(); ShowReceiptPanel(); } else { lSwipeErrors.Text = String.Format("<div class='alert alert-danger'>An error occurred while process this transaction. Message: {0}</div>", errorMessage); } } else { lSwipeErrors.Text = "<div class='alert alert-danger'>Invalid gateway provided. Please provide a gateway. Transaction not processed.</div>"; } } } catch (Exception ex) { lSwipeErrors.Text = String.Format("<div class='alert alert-danger'>An error occurred while process this transaction. Message: {0}</div>", ex.Message); } }