/// <summary> /// Binds the fees grid. /// </summary> private void BindFeesGrid() { var instanceId = this.RegistrationInstanceId; if (instanceId.GetValueOrDefault(0) == 0) { return; } var registrationTemplateFeeService = new RegistrationTemplateFeeService(new RockContext()); var data = registrationTemplateFeeService.GetRegistrationTemplateFeeReport(instanceId.Value); // Add Date Range var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(sdrpFeeDateRange.DelimitedValues); if (dateRange.Start.HasValue) { data = data.Where(r => r.RegistrationDate >= dateRange.Start.Value); } if (dateRange.End.HasValue) { data = data.Where(r => r.RegistrationDate < dateRange.End.Value); } // Fee Name if (ddlFeeName.SelectedIndex > 0) { data = data.Where(r => r.FeeName == ddlFeeName.SelectedItem.Text); } // Fee Options if (cblFeeOptions.SelectedValues.Count > 0) { data = data.Where(r => cblFeeOptions.SelectedValues.Any(v => v.Equals(r.FeeItem.Guid.ToString(), StringComparison.OrdinalIgnoreCase))); } SortProperty sortProperty = gFees.SortProperty; if (sortProperty != null) { data = data.AsQueryable().Sort(sortProperty).ToList(); } else { data = data.OrderByDescending(f => f.RegistrationDate).ToList(); } gFees.DataSource = data; gFees.DataBind(); }
/// <summary> /// Populates ddlFeeName with the name of the DDL fee. /// </summary> private void Populate_ddlFeeName() { int?instanceId = this.RegistrationInstanceId; if (instanceId.GetValueOrDefault(0) == 0) { return; } var rockContext = new RockContext(); var registrationInstanceService = new RegistrationInstanceService(rockContext); var templateId = registrationInstanceService.Get(( int )instanceId).RegistrationTemplateId; var registrationTemplateFeeService = new RegistrationTemplateFeeService(new RockContext()); var templateFees = registrationTemplateFeeService.Queryable().Where(f => f.RegistrationTemplateId == templateId).ToList(); ddlFeeName.Items.Add(new ListItem()); foreach (var templateFee in templateFees) { ddlFeeName.Items.Add(new ListItem(templateFee.Name, templateFee.Id.ToString())); } }
/// <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 ) { ParseControls( true ); var rockContext = new RockContext(); var service = new RegistrationTemplateService( rockContext ); RegistrationTemplate RegistrationTemplate = null; int? RegistrationTemplateId = hfRegistrationTemplateId.Value.AsIntegerOrNull(); if ( RegistrationTemplateId.HasValue ) { RegistrationTemplate = service.Get( RegistrationTemplateId.Value ); } bool newTemplate = false; if ( RegistrationTemplate == null ) { newTemplate = true; RegistrationTemplate = new RegistrationTemplate(); } RegistrationNotify notify = RegistrationNotify.None; foreach( ListItem li in cblNotify.Items ) { if ( li.Selected ) { notify = notify | (RegistrationNotify)li.Value.AsInteger(); } } RegistrationTemplate.IsActive = cbIsActive.Checked; RegistrationTemplate.Name = tbName.Text; RegistrationTemplate.CategoryId = cpCategory.SelectedValueAsInt(); RegistrationTemplate.GroupTypeId = gtpGroupType.SelectedGroupTypeId; RegistrationTemplate.GroupMemberRoleId = rpGroupTypeRole.GroupRoleId; RegistrationTemplate.GroupMemberStatus = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>(); RegistrationTemplate.RequiredSignatureDocumentTemplateId = ddlSignatureDocumentTemplate.SelectedValueAsInt(); RegistrationTemplate.SignatureDocumentAction = cbDisplayInLine.Checked ? SignatureDocumentAction.Embed : SignatureDocumentAction.Email; RegistrationTemplate.RegistrationWorkflowTypeId = wtpRegistrationWorkflow.SelectedValueAsInt(); RegistrationTemplate.Notify = notify; RegistrationTemplate.AddPersonNote = cbAddPersonNote.Checked; RegistrationTemplate.LoginRequired = cbLoginRequired.Checked; RegistrationTemplate.AllowExternalRegistrationUpdates = cbAllowExternalUpdates.Checked; RegistrationTemplate.AllowGroupPlacement = cbAllowGroupPlacement.Checked; RegistrationTemplate.AllowMultipleRegistrants = cbMultipleRegistrants.Checked; RegistrationTemplate.MaxRegistrants = nbMaxRegistrants.Text.AsInteger(); RegistrationTemplate.RegistrantsSameFamily = rblRegistrantsInSameFamily.SelectedValueAsEnum<RegistrantsSameFamily>(); RegistrationTemplate.ShowCurrentFamilyMembers = cbShowCurrentFamilyMembers.Checked; RegistrationTemplate.SetCostOnInstance = !tglSetCostOnTemplate.Checked; RegistrationTemplate.Cost = cbCost.Text.AsDecimal(); RegistrationTemplate.MinimumInitialPayment = cbMinimumInitialPayment.Text.AsDecimalOrNull(); RegistrationTemplate.FinancialGatewayId = fgpFinancialGateway.SelectedValueAsInt(); RegistrationTemplate.BatchNamePrefix = txtBatchNamePrefix.Text; RegistrationTemplate.ConfirmationFromName = tbConfirmationFromName.Text; RegistrationTemplate.ConfirmationFromEmail = tbConfirmationFromEmail.Text; RegistrationTemplate.ConfirmationSubject = tbConfirmationSubject.Text; RegistrationTemplate.ConfirmationEmailTemplate = ceConfirmationEmailTemplate.Text; RegistrationTemplate.ReminderFromName = tbReminderFromName.Text; RegistrationTemplate.ReminderFromEmail = tbReminderFromEmail.Text; RegistrationTemplate.ReminderSubject = tbReminderSubject.Text; RegistrationTemplate.ReminderEmailTemplate = ceReminderEmailTemplate.Text; RegistrationTemplate.PaymentReminderFromName = tbPaymentReminderFromName.Text; RegistrationTemplate.PaymentReminderFromEmail = tbPaymentReminderFromEmail.Text; RegistrationTemplate.PaymentReminderSubject = tbPaymentReminderSubject.Text; RegistrationTemplate.PaymentReminderEmailTemplate = cePaymentReminderEmailTemplate.Text; RegistrationTemplate.PaymentReminderTimeSpan = nbPaymentReminderTimeSpan.Text.AsInteger(); RegistrationTemplate.RegistrationTerm = string.IsNullOrWhiteSpace( tbRegistrationTerm.Text ) ? "Registration" : tbRegistrationTerm.Text; RegistrationTemplate.RegistrantTerm = string.IsNullOrWhiteSpace( tbRegistrantTerm.Text ) ? "Registrant" : tbRegistrantTerm.Text; RegistrationTemplate.FeeTerm = string.IsNullOrWhiteSpace( tbFeeTerm.Text ) ? "Additional Options" : tbFeeTerm.Text; RegistrationTemplate.DiscountCodeTerm = string.IsNullOrWhiteSpace( tbDiscountCodeTerm.Text ) ? "Discount Code" : tbDiscountCodeTerm.Text; RegistrationTemplate.SuccessTitle = tbSuccessTitle.Text; RegistrationTemplate.SuccessText = ceSuccessText.Text; if ( !Page.IsValid || !RegistrationTemplate.IsValid ) { return; } foreach ( var form in FormState ) { if ( !form.IsValid ) { return; } if ( FormFieldsState.ContainsKey( form.Guid ) ) { foreach( var formField in FormFieldsState[ form.Guid ]) { if ( !formField.IsValid ) { return; } } } } // Get the valid group member attributes var group = new Group(); group.GroupTypeId = gtpGroupType.SelectedGroupTypeId ?? 0; var groupMember = new GroupMember(); groupMember.Group = group; groupMember.LoadAttributes(); var validGroupMemberAttributeIds = groupMember.Attributes.Select( a => a.Value.Id ).ToList(); // Remove any group member attributes that are not valid based on selected group type foreach( var fieldList in FormFieldsState.Select( s => s.Value ) ) { foreach( var formField in fieldList .Where( a => a.FieldSource == RegistrationFieldSource.GroupMemberAttribute && a.AttributeId.HasValue && !validGroupMemberAttributeIds.Contains( a.AttributeId.Value ) ) .ToList() ) { fieldList.Remove( formField ); } } // Perform Validation var validationErrors = new List<string>(); if ( ( ( RegistrationTemplate.SetCostOnInstance ?? false ) || RegistrationTemplate.Cost > 0 || FeeState.Any() ) && !RegistrationTemplate.FinancialGatewayId.HasValue ) { validationErrors.Add( "A Financial Gateway is required when the registration has a cost or additional fees or is configured to allow instances to set a cost." ); } if ( validationErrors.Any() ) { nbValidationError.Visible = true; nbValidationError.Text = "<ul class='list-unstyled'><li>" + validationErrors.AsDelimited( "</li><li>" ) + "</li></ul>"; } else { // Save the entity field changes to registration template if ( RegistrationTemplate.Id.Equals( 0 ) ) { service.Add( RegistrationTemplate ); } rockContext.SaveChanges(); var attributeService = new AttributeService( rockContext ); var registrationTemplateFormService = new RegistrationTemplateFormService( rockContext ); var registrationTemplateFormFieldService = new RegistrationTemplateFormFieldService( rockContext ); var registrationTemplateDiscountService = new RegistrationTemplateDiscountService( rockContext ); var registrationTemplateFeeService = new RegistrationTemplateFeeService( rockContext ); var registrationRegistrantFeeService = new RegistrationRegistrantFeeService( rockContext ); var groupService = new GroupService( rockContext ); // delete forms that aren't assigned in the UI anymore var formUiGuids = FormState.Select( f => f.Guid ).ToList(); foreach ( var form in registrationTemplateFormService .Queryable() .Where( f => f.RegistrationTemplateId == RegistrationTemplate.Id && !formUiGuids.Contains( f.Guid ) ) ) { foreach( var formField in form.Fields.ToList() ) { form.Fields.Remove( formField ); registrationTemplateFormFieldService.Delete( formField ); } registrationTemplateFormService.Delete( form ); } // delete fields that aren't assigned in the UI anymore var fieldUiGuids = FormFieldsState.SelectMany( a => a.Value).Select( f => f.Guid ).ToList(); foreach ( var formField in registrationTemplateFormFieldService .Queryable() .Where( a => formUiGuids.Contains( a.RegistrationTemplateForm.Guid ) && !fieldUiGuids.Contains( a.Guid ) ) ) { registrationTemplateFormFieldService.Delete( formField ); } // delete discounts that aren't assigned in the UI anymore var discountUiGuids = DiscountState.Select( u => u.Guid ).ToList(); foreach ( var discount in registrationTemplateDiscountService .Queryable() .Where( d => d.RegistrationTemplateId == RegistrationTemplate.Id && !discountUiGuids.Contains( d.Guid ) ) ) { registrationTemplateDiscountService.Delete( discount ); } // delete fees that aren't assigned in the UI anymore var feeUiGuids = FeeState.Select( u => u.Guid ).ToList(); var deletedfees = registrationTemplateFeeService .Queryable() .Where( d => d.RegistrationTemplateId == RegistrationTemplate.Id && !feeUiGuids.Contains( d.Guid ) ) .ToList(); var deletedFeeIds = deletedfees.Select( f => f.Id ).ToList(); foreach ( var registrantFee in registrationRegistrantFeeService .Queryable() .Where( f => deletedFeeIds.Contains( f.RegistrationTemplateFeeId ) ) .ToList() ) { registrationRegistrantFeeService.Delete( registrantFee ); } foreach ( var fee in deletedfees ) { registrationTemplateFeeService.Delete( fee ); } int? entityTypeId = EntityTypeCache.Read( typeof( Rock.Model.RegistrationRegistrant ) ).Id; var qualifierColumn = "RegistrationTemplateId"; var qualifierValue = RegistrationTemplate.Id.ToString(); // Get the registration attributes still in the UI var attributesUI = FormFieldsState .SelectMany( s => s.Value.Where( a => a.FieldSource == RegistrationFieldSource.RegistrationAttribute && a.Attribute != null ) ) .Select( f => f.Attribute ) .ToList(); var selectedAttributeGuids = attributesUI.Select( a => a.Guid ); // Delete the registration attributes that were removed from the UI var attributesDB = attributeService.Get( entityTypeId, qualifierColumn, qualifierValue ); foreach ( var attr in attributesDB.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ).ToList() ) { attributeService.Delete( attr ); Rock.Web.Cache.AttributeCache.Flush( attr.Id ); } rockContext.SaveChanges(); // Save all of the registration attributes still in the UI foreach ( var attr in attributesUI ) { Helper.SaveAttributeEdits( attr, entityTypeId, qualifierColumn, qualifierValue, rockContext ); } // add/updated forms/fields foreach ( var formUI in FormState ) { var form = RegistrationTemplate.Forms.FirstOrDefault( f => f.Guid.Equals( formUI.Guid ) ); if ( form == null ) { form = new RegistrationTemplateForm(); form.Guid = formUI.Guid; RegistrationTemplate.Forms.Add( form ); } form.Name = formUI.Name; form.Order = formUI.Order; if ( FormFieldsState.ContainsKey( form.Guid ) ) { foreach ( var formFieldUI in FormFieldsState[form.Guid] ) { var formField = form.Fields.FirstOrDefault( a => a.Guid.Equals( formFieldUI.Guid ) ); if ( formField == null ) { formField = new RegistrationTemplateFormField(); formField.Guid = formFieldUI.Guid; form.Fields.Add( formField ); } formField.AttributeId = formFieldUI.AttributeId; if ( !formField.AttributeId.HasValue && formFieldUI.FieldSource == RegistrationFieldSource.RegistrationAttribute && formFieldUI.Attribute != null ) { var attr = AttributeCache.Read( formFieldUI.Attribute.Guid, rockContext ); if ( attr != null ) { formField.AttributeId = attr.Id; } } formField.FieldSource = formFieldUI.FieldSource; formField.PersonFieldType = formFieldUI.PersonFieldType; formField.IsInternal = formFieldUI.IsInternal; formField.IsSharedValue = formFieldUI.IsSharedValue; formField.ShowCurrentValue = formFieldUI.ShowCurrentValue; formField.PreText = formFieldUI.PreText; formField.PostText = formFieldUI.PostText; formField.IsGridField = formFieldUI.IsGridField; formField.IsRequired = formFieldUI.IsRequired; formField.Order = formFieldUI.Order; } } } // add/updated discounts foreach ( var discountUI in DiscountState ) { var discount = RegistrationTemplate.Discounts.FirstOrDefault( a => a.Guid.Equals( discountUI.Guid ) ); if ( discount == null ) { discount = new RegistrationTemplateDiscount(); discount.Guid = discountUI.Guid; RegistrationTemplate.Discounts.Add( discount ); } discount.Code = discountUI.Code; discount.DiscountPercentage = discountUI.DiscountPercentage; discount.DiscountAmount = discountUI.DiscountAmount; discount.Order = discountUI.Order; } // add/updated fees foreach ( var feeUI in FeeState ) { var fee = RegistrationTemplate.Fees.FirstOrDefault( a => a.Guid.Equals( feeUI.Guid ) ); if ( fee == null ) { fee = new RegistrationTemplateFee(); fee.Guid = feeUI.Guid; RegistrationTemplate.Fees.Add( fee ); } fee.Name = feeUI.Name; fee.FeeType = feeUI.FeeType; fee.CostValue = feeUI.CostValue; fee.DiscountApplies = feeUI.DiscountApplies; fee.AllowMultiple = feeUI.AllowMultiple; fee.Order = feeUI.Order; } rockContext.SaveChanges(); AttributeCache.FlushEntityAttributes(); // If this is a new template, give the current user and the Registration Administrators role administrative // rights to this template, and staff, and staff like roles edit rights if ( newTemplate ) { RegistrationTemplate.AllowPerson( Authorization.ADMINISTRATE, CurrentPerson, rockContext ); var registrationAdmins = groupService.Get( Rock.SystemGuid.Group.GROUP_EVENT_REGISTRATION_ADMINISTRATORS.AsGuid() ); RegistrationTemplate.AllowSecurityRole( Authorization.ADMINISTRATE, registrationAdmins, rockContext ); var staffLikeUsers = groupService.Get( Rock.SystemGuid.Group.GROUP_STAFF_LIKE_MEMBERS.AsGuid() ); RegistrationTemplate.AllowSecurityRole( Authorization.EDIT, staffLikeUsers, rockContext ); var staffUsers = groupService.Get( Rock.SystemGuid.Group.GROUP_STAFF_MEMBERS.AsGuid() ); RegistrationTemplate.AllowSecurityRole( Authorization.EDIT, staffUsers, rockContext ); } var qryParams = new Dictionary<string, string>(); qryParams["RegistrationTemplateId"] = RegistrationTemplate.Id.ToString(); NavigateToPage( RockPage.Guid, qryParams ); } }
/// <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 (this.RegistrationTemplate.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 = this.RegistrationTemplate.RequiredSignatureDocumentTemplate.Id; document.AppliesToPersonAliasId = registrant.PersonAliasId.Value; document.AssignedToPersonAliasId = registrant.PersonAliasId.Value; document.Name = string.Format( "{0}_{1}", instance != null ? instance.Name : this.RegistrationTemplate.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 this.RegistrationTemplate.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 && this.RegistrationTemplate.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 == this.RegistrationTemplate.GroupTypeId.Value) { int?groupRoleId = this.RegistrationTemplate.GroupMemberRoleId.HasValue ? this.RegistrationTemplate.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 = this.RegistrationTemplate.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(); }
/// <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 ); RegistrationRegistrant registrant = null; if ( RegistrantState.Id > 0 ) { registrant = registrantService.Get( RegistrantState.Id ); } bool newRegistrant = false; var registrantChanges = new List<string>(); if ( registrant == null ) { newRegistrant = true; registrant = new RegistrationRegistrant(); registrant.RegistrationId = RegistrantState.RegistrationId; registrantService.Add( registrant ); registrantChanges.Add( "Created 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; History.EvaluateChange( registrantChanges, "Person", prevPerson, newPerson ); } 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; } } History.EvaluateChange( registrantChanges, "Cost", registrant.Cost, cbCost.Text.AsDecimal() ); registrant.Cost = cbCost.Text.AsDecimal(); 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.Option == dbFee.Option && f.Quantity > 0 ) ) { registrantChanges.Add( string.Format( "Removed '{0}' Fee (Quantity:{1:N0}, Cost:{2:C2}, Option:{3}", dbFee.RegistrationTemplateFee.Name, dbFee.Quantity, dbFee.Cost, dbFee.Option ) ); 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.Option == uiFeeOption.Option ) .FirstOrDefault(); if ( dbFee == null ) { dbFee = new RegistrationRegistrantFee(); dbFee.RegistrationTemplateFeeId = uiFee.Key; dbFee.Option = uiFeeOption.Option; 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.Option ) ) { feeName = string.Format( "{0} ({1})", feeName, uiFeeOption.Option ); } if ( dbFee.Id <= 0 ) { registrantChanges.Add( feeName + " Fee Added" ); } 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 ( !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(); foreach ( var field in TemplateState.Forms .SelectMany( f => f.Fields .Where( t => t.FieldSource == RegistrationFieldSource.RegistrationAttribute && t.AttributeId.HasValue ) ) ) { var attribute = AttributeCache.Read( 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(); groupMemberService.Add( groupMember ); groupMember.GroupId = reloadedRegistrant.Registration.Group.Id; groupMember.PersonId = ppPerson.PersonId.Value; groupMember.GroupRoleId = groupRoleId.Value; groupMember.GroupMemberStatus = TemplateState.GroupMemberStatus; newRockContext.SaveChanges(); registrantChanges.Add( string.Format( "Registrant added to {0} group", reloadedRegistrant.Registration.Group.Name ) ); } else { registrantChanges.Add( string.Format( "Registrant group member reference updated to existing person in {0} group", reloadedRegistrant.Registration.Group.Name ) ); } reloadedRegistrant.GroupMemberId = groupMember.Id; newRockContext.SaveChanges(); } } } } HistoryService.SaveChanges( rockContext, typeof( Registration ), Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(), registrant.RegistrationId, registrantChanges, "Registrant: " + registrantName, null, null ); } NavigateToRegistration(); }
/// <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 ) { ParseControls( true ); var rockContext = new RockContext(); var service = new RegistrationTemplateService( rockContext ); RegistrationTemplate RegistrationTemplate = null; int? RegistrationTemplateId = hfRegistrationTemplateId.Value.AsIntegerOrNull(); if ( RegistrationTemplateId.HasValue ) { RegistrationTemplate = service.Get( RegistrationTemplateId.Value ); } if ( RegistrationTemplate == null ) { RegistrationTemplate = new RegistrationTemplate(); } RegistrationNotify notify = RegistrationNotify.None; foreach( ListItem li in cblNotify.Items ) { if ( li.Selected ) { notify = notify | (RegistrationNotify)li.Value.AsInteger(); } } RegistrationTemplate.IsActive = cbIsActive.Checked; RegistrationTemplate.Name = tbName.Text; RegistrationTemplate.CategoryId = cpCategory.SelectedValueAsInt(); RegistrationTemplate.GroupTypeId = gtpGroupType.SelectedGroupTypeId; RegistrationTemplate.GroupMemberRoleId = rpGroupTypeRole.GroupRoleId; RegistrationTemplate.GroupMemberStatus = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>(); RegistrationTemplate.Notify = notify; RegistrationTemplate.LoginRequired = cbLoginRequired.Checked; RegistrationTemplate.AllowMultipleRegistrants = cbMultipleRegistrants.Checked; RegistrationTemplate.MaxRegistrants = nbMaxRegistrants.Text.AsInteger(); RegistrationTemplate.RegistrantsSameFamily = rblRegistrantsInSameFamily.SelectedValueAsEnum<RegistrantsSameFamily>(); RegistrationTemplate.Cost = cbCost.Text.AsDecimal(); RegistrationTemplate.MinimumInitialPayment = cbMinimumInitialPayment.Text.AsDecimalOrNull(); RegistrationTemplate.FinancialGatewayId = fgpFinancialGateway.SelectedValueAsInt(); RegistrationTemplate.ConfirmationFromName = tbConfirmationFromName.Text; RegistrationTemplate.ConfirmationFromEmail = tbConfirmationFromEmail.Text; RegistrationTemplate.ConfirmationSubject = tbConfirmationSubject.Text; RegistrationTemplate.ConfirmationEmailTemplate = ceConfirmationEmailTemplate.Text; RegistrationTemplate.ReminderFromName = tbReminderFromName.Text; RegistrationTemplate.ReminderFromEmail = tbReminderFromEmail.Text; RegistrationTemplate.ReminderSubject = tbReminderSubject.Text; RegistrationTemplate.ReminderEmailTemplate = ceReminderEmailTemplate.Text; RegistrationTemplate.RegistrationTerm = string.IsNullOrWhiteSpace( tbRegistrationTerm.Text ) ? "Registration" : tbRegistrationTerm.Text; RegistrationTemplate.RegistrantTerm = string.IsNullOrWhiteSpace( tbRegistrantTerm.Text ) ? "Registrant" : tbRegistrantTerm.Text; RegistrationTemplate.FeeTerm = string.IsNullOrWhiteSpace( tbFeeTerm.Text ) ? "Additional Options" : tbFeeTerm.Text; RegistrationTemplate.DiscountCodeTerm = string.IsNullOrWhiteSpace( tbDiscountCodeTerm.Text ) ? "Discount Code" : tbDiscountCodeTerm.Text; RegistrationTemplate.SuccessTitle = tbSuccessTitle.Text; RegistrationTemplate.SuccessText = ceSuccessText.Text; if ( !Page.IsValid || !RegistrationTemplate.IsValid ) { return; } foreach ( var form in FormState ) { if ( !form.IsValid ) { return; } if ( FormFieldsState.ContainsKey( form.Guid ) ) { foreach( var formField in FormFieldsState[ form.Guid ]) { if ( !formField.IsValid ) { return; } } } } // Get the valid group member attributes var group = new Group(); group.GroupTypeId = gtpGroupType.SelectedGroupTypeId ?? 0; var groupMember = new GroupMember(); groupMember.Group = group; groupMember.LoadAttributes(); var validGroupMemberAttributeIds = groupMember.Attributes.Select( a => a.Value.Id ).ToList(); // Remove any group member attributes that are not valid based on selected group type foreach( var fieldList in FormFieldsState.Select( s => s.Value ) ) { foreach( var formField in fieldList .Where( a => a.FieldSource == RegistrationFieldSource.GroupMemberAttribute && a.AttributeId.HasValue && !validGroupMemberAttributeIds.Contains( a.AttributeId.Value ) ) .ToList() ) { fieldList.Remove( formField ); } } // Perform Validation var validationErrors = new List<string>(); if ( ( RegistrationTemplate.Cost > 0 || FeeState.Any() ) && !RegistrationTemplate.FinancialGatewayId.HasValue ) { validationErrors.Add( "A Financial Gateway is required when the registration has a cost or additional fees." ); } if ( validationErrors.Any() ) { nbValidationError.Visible = true; nbValidationError.Text = "<ul class='list-unstyled'><li>" + validationErrors.AsDelimited( "</li><li>" ) + "</li></ul>"; } else { rockContext.WrapTransaction( () => { // Save the entity field changes to registration template if ( RegistrationTemplate.Id.Equals( 0 ) ) { service.Add( RegistrationTemplate ); } rockContext.SaveChanges(); var attributeService = new AttributeService( rockContext ); var registrationTemplateFormService = new RegistrationTemplateFormService( rockContext ); var registrationTemplateFormFieldService = new RegistrationTemplateFormFieldService( rockContext ); var registrationTemplateDiscountService = new RegistrationTemplateDiscountService( rockContext ); var registrationTemplateFeeService = new RegistrationTemplateFeeService( rockContext ); // delete forms that aren't assigned in the UI anymore var formUiGuids = FormState.Select( f => f.Guid ).ToList(); foreach ( var form in registrationTemplateFormService .Queryable() .Where( f => f.RegistrationTemplateId == RegistrationTemplate.Id && !formUiGuids.Contains( f.Guid ) ) ) { registrationTemplateFormService.Delete( form ); } // delete discounts that aren't assigned in the UI anymore var discountUiGuids = DiscountState.Select( u => u.Guid ).ToList(); foreach ( var discount in registrationTemplateDiscountService .Queryable() .Where( d => d.RegistrationTemplateId == RegistrationTemplate.Id && !discountUiGuids.Contains( d.Guid ) ) ) { registrationTemplateDiscountService.Delete( discount ); } // delete fees that aren't assigned in the UI anymore var feeUiGuids = FeeState.Select( u => u.Guid ).ToList(); foreach ( var fee in registrationTemplateFeeService .Queryable() .Where( d => d.RegistrationTemplateId == RegistrationTemplate.Id && !feeUiGuids.Contains( d.Guid ) ) ) { registrationTemplateFeeService.Delete( fee ); } var attributesUI = FormFieldsState .SelectMany( s => s.Value.Where( a => a.FieldSource == RegistrationFieldSource.RegistrationAttribute && a.Attribute != null ) ) .Select( f => f.Attribute ); int? entityTypeId = EntityTypeCache.Read( typeof( Rock.Model.RegistrationRegistrant ) ).Id; var qualifierColumn = "RegistrationTemplateId"; var qualifierValue = RegistrationTemplate.Id.ToString(); // Get the existing registration attributes for this entity type and qualifier value var attributesDB = attributeService.Get( entityTypeId, qualifierColumn, qualifierValue ); // Delete any of the registration attributes that were removed in the UI var selectedAttributeGuids = attributesUI.Select( a => a.Guid ); foreach ( var attr in attributesDB.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ) ) { attributeService.Delete( attr ); rockContext.SaveChanges(); Rock.Web.Cache.AttributeCache.Flush( attr.Id ); } // Update the registration attributes that were assigned in the UI foreach ( var attr in attributesUI ) { Helper.SaveAttributeEdits( attr, entityTypeId, qualifierColumn, qualifierValue, rockContext ); } // add/updated forms/fields foreach ( var formUI in FormState ) { var form = RegistrationTemplate.Forms.FirstOrDefault( f => f.Guid.Equals( formUI.Guid ) ); if ( form == null ) { form = new RegistrationTemplateForm(); form.Guid = formUI.Guid; RegistrationTemplate.Forms.Add( form ); } form.Name = formUI.Name; form.Order = formUI.Order; if ( FormFieldsState.ContainsKey( form.Guid ) ) { var fieldUiGuids = FormFieldsState[form.Guid].Select( a => a.Guid ).ToList(); foreach ( var formField in registrationTemplateFormFieldService .Queryable() .Where( a => a.RegistrationTemplateForm.Guid.Equals( form.Guid ) && !fieldUiGuids.Contains( a.Guid ) ) ) { registrationTemplateFormFieldService.Delete( formField ); } foreach ( var formFieldUI in FormFieldsState[form.Guid] ) { var formField = form.Fields.FirstOrDefault( a => a.Guid.Equals( formFieldUI.Guid ) ); if ( formField == null ) { formField = new RegistrationTemplateFormField(); formField.Guid = formFieldUI.Guid; form.Fields.Add( formField ); } formField.AttributeId = formFieldUI.AttributeId; if ( !formField.AttributeId.HasValue && formFieldUI.FieldSource == RegistrationFieldSource.RegistrationAttribute && formFieldUI.Attribute != null ) { var attr = AttributeCache.Read( formFieldUI.Attribute.Guid, rockContext ); if ( attr != null ) { formField.AttributeId = attr.Id; } } formField.FieldSource = formFieldUI.FieldSource; formField.PersonFieldType = formFieldUI.PersonFieldType; formField.IsSharedValue = formFieldUI.IsSharedValue; formField.ShowCurrentValue = formFieldUI.ShowCurrentValue; formField.PreText = formFieldUI.PreText; formField.PostText = formFieldUI.PostText; formField.IsGridField = formFieldUI.IsGridField; formField.IsRequired = formFieldUI.IsRequired; formField.Order = formFieldUI.Order; } } } // add/updated discounts foreach ( var discountUI in DiscountState ) { var discount = RegistrationTemplate.Discounts.FirstOrDefault( a => a.Guid.Equals( discountUI.Guid ) ); if ( discount == null ) { discount = new RegistrationTemplateDiscount(); discount.Guid = discountUI.Guid; RegistrationTemplate.Discounts.Add( discount ); } discount.Code = discountUI.Code; discount.DiscountPercentage = discountUI.DiscountPercentage; discount.DiscountAmount = discountUI.DiscountAmount; discount.Order = discountUI.Order; } // add/updated fees foreach ( var feeUI in FeeState ) { var fee = RegistrationTemplate.Fees.FirstOrDefault( a => a.Guid.Equals( feeUI.Guid ) ); if ( fee == null ) { fee = new RegistrationTemplateFee(); fee.Guid = feeUI.Guid; RegistrationTemplate.Fees.Add( fee ); } fee.Name = feeUI.Name; fee.FeeType = feeUI.FeeType; fee.CostValue = feeUI.CostValue; fee.DiscountApplies = feeUI.DiscountApplies; fee.AllowMultiple = feeUI.AllowMultiple; fee.Order = feeUI.Order; } rockContext.SaveChanges(); } ); var qryParams = new Dictionary<string, string>(); qryParams["RegistrationTemplateId"] = RegistrationTemplate.Id.ToString(); NavigateToPage( RockPage.Guid, qryParams ); } }
/// <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); RegistrationRegistrant registrant = null; if (RegistrantState.Id > 0) { registrant = registrantService.Get(RegistrantState.Id); } bool newRegistrant = false; var registrantChanges = new List <string>(); if (registrant == null) { newRegistrant = true; registrant = new RegistrationRegistrant(); registrant.RegistrationId = RegistrantState.RegistrationId; registrantService.Add(registrant); registrantChanges.Add("Created 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; History.EvaluateChange(registrantChanges, "Person", prevPerson, newPerson); } 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; } } History.EvaluateChange(registrantChanges, "Cost", registrant.Cost, cbCost.Text.AsDecimal()); registrant.Cost = cbCost.Text.AsDecimal(); 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.Option == dbFee.Option && f.Quantity > 0)) { registrantChanges.Add(string.Format("Removed '{0}' Fee (Quantity:{1:N0}, Cost:{2:C2}, Option:{3}", dbFee.RegistrationTemplateFee.Name, dbFee.Quantity, dbFee.Cost, dbFee.Option)); 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.Option == uiFeeOption.Option) .FirstOrDefault(); if (dbFee == null) { dbFee = new RegistrationRegistrantFee(); dbFee.RegistrationTemplateFeeId = uiFee.Key; dbFee.Option = uiFeeOption.Option; 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.Option)) { feeName = string.Format("{0} ({1})", feeName, uiFeeOption.Option); } if (dbFee.Id <= 0) { registrantChanges.Add(feeName + " Fee Added"); } 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 (!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(); foreach (var field in TemplateState.Forms .SelectMany(f => f.Fields .Where(t => t.FieldSource == RegistrationFieldSource.RegistrationAttribute && t.AttributeId.HasValue))) { var attribute = AttributeCache.Read(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(); groupMemberService.Add(groupMember); groupMember.GroupId = reloadedRegistrant.Registration.Group.Id; groupMember.PersonId = ppPerson.PersonId.Value; groupMember.GroupRoleId = groupRoleId.Value; groupMember.GroupMemberStatus = TemplateState.GroupMemberStatus; newRockContext.SaveChanges(); registrantChanges.Add(string.Format("Registrant added to {0} group", reloadedRegistrant.Registration.Group.Name)); } else { registrantChanges.Add(string.Format("Registrant group member reference updated to existing person in {0} group", reloadedRegistrant.Registration.Group.Name)); } reloadedRegistrant.GroupMemberId = groupMember.Id; newRockContext.SaveChanges(); } } } } HistoryService.SaveChanges( rockContext, typeof(Registration), Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(), registrant.RegistrationId, registrantChanges, "Registrant: " + registrantName, null, null); } NavigateToRegistration(); }