/// <summary> /// Handles the Click event of the DeleteInstance control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs" /> instance containing the event data.</param> protected void DeleteInstance_Click(object sender, Rock.Web.UI.Controls.RowEventArgs e) { RockContext rockContext = new RockContext(); RegistrationInstanceService instanceService = new RegistrationInstanceService(rockContext); RegistrationInstance instance = instanceService.Get(e.RowKeyId); if (instance != null) { string errorMessage; if (!instanceService.CanDelete(instance, out errorMessage)) { mdGridWarning.Show(errorMessage, ModalAlertType.Information); return; } rockContext.WrapTransaction(() => { new RegistrationService(rockContext).DeleteRange(instance.Registrations); instanceService.Delete(instance); rockContext.SaveChanges(); }); } BindInstancesGrid(); }
/// <summary> /// Binds the Registrations (people who registered) using the RegistrationInstances. /// </summary> /// <param name="rockContext">The RockContext.</param> /// <param name="registrationInstanceId">The id of a RegistrationInstance.</param> /// <param name="setUserPreference">Set to true if you want to remember the item in the users preferences</param> private void BindRegistrationInstances(RockContext rockContext, int?registrationInstanceId) { RegistrationInstanceService registrationInstanceService = new RegistrationInstanceService(rockContext); var registrationInstances = registrationInstanceService.Queryable().AsNoTracking().ToList(); ddlRegistrationInstances.DataSource = registrationInstances; RegistrationInstance emptyRegistrationInstance = new RegistrationInstance { Id = -1, Name = "" }; registrationInstances.Insert(0, emptyRegistrationInstance); ddlRegistrationInstances.DataBind(); // Select the given registrationInstanceId if it still exists in the list if (ddlRegistrationInstances.Items.FindByValue(registrationInstanceId.ToStringSafe()) != null) { ddlRegistrationInstances.SelectedValue = registrationInstanceId.ToStringSafe(); } if (registrationInstances.Count >= 1) { BindRegistrationsUsingRegistrationInstances(registrationInstanceId); } }
/// <summary> /// Binds the dropdown menus /// </summary> private void BindData() { using (var rockContext = new RockContext()) { RegistrationInstanceService registrationInstanceService = new RegistrationInstanceService(rockContext); var registrationInstances = registrationInstanceService.Queryable().Where(ri => ri.IsActive == true).AsNoTracking().ToList(); ddlRegistrationInstances.DataSource = registrationInstances; RegistrationInstance emptyRegistrationInstance = new RegistrationInstance { Id = -1, Name = "" }; registrationInstances.Insert(0, emptyRegistrationInstance); ddlRegistrationInstances.DataBind(); var entityTypes = new EntityTypeService(new RockContext()).GetEntities() .Where(t => t.Guid.ToString() == Rock.SystemGuid.EntityType.GROUP.ToLower() || t.Guid.ToString() == "5cd9c0c8-c047-61a0-4e36-0fdb8496f066" || t.Guid.ToString() == Rock.SystemGuid.EntityType.DATAVIEW.ToLower()) .OrderBy(t => t.FriendlyName) .ToList(); entityTypes.Insert(0, new EntityType() { Id = -1, FriendlyName = "Select One" }); ddlEntityType.DataSource = entityTypes; ddlEntityType.DataBind(); } }
/// <summary> /// Handles the Click event of the btnCancel 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 btnCancel_Click(object sender, EventArgs e) { if (hfRegistrationInstanceId.Value.Equals("0")) { var qryParams = new Dictionary <string, string>(); int?parentTemplateId = PageParameter(PageParameterKey.RegistrationTemplateId).AsIntegerOrNull(); if (parentTemplateId.HasValue) { qryParams[PageParameterKey.RegistrationTemplateId] = parentTemplateId.ToString(); } // Cancelling on Add. Return to Grid NavigateToParentPage(qryParams); } else { // Cancelling on Edit. Return to Details using (var rockContext = new RockContext()) { RegistrationInstanceService service = new RegistrationInstanceService(rockContext); RegistrationInstance item = service.Get(int.Parse(hfRegistrationInstanceId.Value)); ShowReadonlyDetails(item); } } }
/// <summary> /// Sets the edit value from IEntity.Id value /// </summary> /// <param name="control">The control.</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="id">The identifier.</param> public void SetEditValueFromEntityId(Control control, Dictionary <string, ConfigurationValue> configurationValues, int?id) { var item = new RegistrationInstanceService(new RockContext()).Get(id ?? 0); string guidValue = item != null?item.Guid.ToString() : string.Empty; SetEditValue(control, configurationValues, guidValue); }
/// <summary> /// Handles the Click event of the btnDelete 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 btnDelete_Click(object sender, EventArgs e) { using (var rockContext = new RockContext()) { var service = new RegistrationInstanceService(rockContext); var registrationInstance = service.Get(hfRegistrationInstanceId.Value.AsInteger()); if (registrationInstance != null) { int registrationTemplateId = registrationInstance.RegistrationTemplateId; if (UserCanEdit || registrationInstance.IsAuthorized(Authorization.EDIT, CurrentPerson) || registrationInstance.IsAuthorized(Authorization.ADMINISTRATE, this.CurrentPerson)) { rockContext.WrapTransaction(() => { new RegistrationService(rockContext).DeleteRange(registrationInstance.Registrations); service.Delete(registrationInstance); rockContext.SaveChanges(); }); var qryParams = new Dictionary <string, string> { { PageParameterKey.RegistrationTemplateId, registrationTemplateId.ToString() } }; NavigateToParentPage(qryParams); } else { mdDeleteWarning.Show("You are not authorized to delete this registration instance.", ModalAlertType.Information); return; } } } }
/// <summary> /// Formats the selection. 1 is the template, 2 is the registration instance, 3 is the type (registrar or registrant) /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override string FormatSelection(Type entityType, string selection) { string result = "Registrant"; string[] selectionValues = selection.Split('|'); if (selectionValues.Length >= 3) { var registrationType = selectionValues[2].AsIntegerOrNull(); if (registrationType == 1) { result = "Registrar"; } var registrationInstanceGuid = selectionValues[1].AsGuid(); var registrationInstance = new RegistrationInstanceService(new RockContext()).Queryable().Where(a => a.Guid == registrationInstanceGuid).FirstOrDefault(); if (registrationInstance != null) { return(string.Format("{0} in registration instance '{1}'", result, registrationInstance.Name)); } else { var registrationTemplateId = selectionValues[0].AsIntegerOrNull() ?? 0; var registrationTemplate = new RegistrationTemplateService(new RockContext()).Queryable().Where(t => t.Id == registrationTemplateId).FirstOrDefault(); return(string.Format("{0} in any registration instance of template '{1}'", result, registrationTemplate.Name)); } } return(result); }
/// <summary> /// Handles the Click event of the btnSendReminders 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 btnSendReminders_Click(object sender, EventArgs e) { var registrationsSelected = new List <int>(); int sendCount = 0; gRegistrations.SelectedKeys.ToList().ForEach(r => registrationsSelected.Add(r.ToString().AsInteger())); if (registrationsSelected.Any()) { if (_registrationInstance == null) { int?registrationInstanceId = PageParameter("RegistrationInstanceId").AsIntegerOrNull(); using (RockContext rockContext = new RockContext()) { RegistrationInstanceService registrationInstanceService = new RegistrationInstanceService(rockContext); _registrationInstance = registrationInstanceService.Queryable("RegistrationTemplate").AsNoTracking() .Where(r => r.Id == registrationInstanceId).FirstOrDefault(); } foreach (var registrationId in registrationsSelected) { // use a new rockContext for each registration so that ChangeTracker doesn't get bogged down using (RockContext rockContext = new RockContext()) { var registrationService = new RegistrationService(rockContext); var registration = registrationService.Get(registrationId); if (registration != null && !string.IsNullOrWhiteSpace(registration.ConfirmationEmail)) { Dictionary <string, object> mergeObjects = new Dictionary <string, object>(); mergeObjects.Add("Registration", registration); mergeObjects.Add("RegistrationInstance", _registrationInstance); var emailMessage = new RockEmailMessage(GetAttributeValue("ConfirmAccountTemplate").AsGuid()); emailMessage.AdditionalMergeFields = mergeObjects; emailMessage.FromEmail = txtFromEmail.Text; emailMessage.FromName = txtFromName.Text; emailMessage.Subject = txtFromSubject.Text; emailMessage.AddRecipient(registration.GetConfirmationRecipient(mergeObjects)); emailMessage.Message = ceEmailMessage.Text; emailMessage.AppRoot = ResolveRockUrl("~/"); emailMessage.ThemeRoot = ResolveRockUrl("~~/"); emailMessage.CreateCommunicationRecord = true; emailMessage.Send(); registration.LastPaymentReminderDateTime = RockDateTime.Now; rockContext.SaveChanges(); sendCount++; } } } } } pnlSend.Visible = false; pnlComplete.Visible = true; nbResult.Text = string.Format("Payment reminders have been sent to {0}.", "individuals".ToQuantity(sendCount)); }
/// <summary> /// Gets the edit value as the IEntity.Id /// </summary> /// <param name="control">The control.</param> /// <param name="configurationValues">The configuration values.</param> /// <returns></returns> public int?GetEditValueAsEntityId(Control control, Dictionary <string, ConfigurationValue> configurationValues) { Guid guid = GetEditValue(control, configurationValues).AsGuid(); var item = new RegistrationInstanceService(new RockContext()).Get(guid); return(item != null ? item.Id : ( int? )null); }
/// <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 the registration instance RegistrationInstance instance = new RegistrationInstanceService(rockContext).Get(GetAttributeValue(action, "RegistrationInstanceId", true).AsInteger()); if (instance == null) { errorMessages.Add("The Registration Instance could not be determined or found!"); } // determine the person that will be added to the registration instance Person person = null; var personAliasGuid = GetAttributeValue(action, "Registrar", true).AsGuidOrNull(); if (personAliasGuid.HasValue) { person = new PersonAliasService(rockContext).Queryable() .Where(a => a.Guid.Equals(personAliasGuid.Value)) .Select(a => a.Person) .FirstOrDefault(); } if (person == null || !person.PrimaryAliasId.HasValue) { errorMessages.Add("The Person for the Registrar value could not be determined or found!"); } // Add registration if (!errorMessages.Any()) { var registrationService = new RegistrationService(rockContext); var registration = new Registration(); registrationService.Add(registration); registration.RegistrationInstanceId = instance.Id; registration.PersonAliasId = person.PrimaryAliasId.Value; registration.FirstName = person.NickName; registration.LastName = person.LastName; registration.IsTemporary = false; registration.ConfirmationEmail = person.Email; rockContext.SaveChanges(); if (registration.Id > 0) { string resultValue = registration.Id.ToString(); var attribute = SetWorkflowAttributeValue(action, "ResultAttribute", resultValue); if (attribute != null) { action.AddLogEntry(string.Format("Set '{0}' attribute to '{1}'.", attribute.Name, resultValue)); } } } errorMessages.ForEach(m => action.AddLogEntry(m, true)); return(!errorMessages.Any()); }
/// <summary> /// Handles the Click event of the btnEdit 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 btnEdit_Click(object sender, EventArgs e) { using (var rockContext = new RockContext()) { var registrationInstance = new RegistrationInstanceService(rockContext).Get(hfRegistrationInstanceId.Value.AsInteger()); ShowEditDetails(registrationInstance, rockContext); } }
/// <summary> /// Gets the expression. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection) { string[] selectionValues = selection.Split('|'); if (selectionValues.Length >= 1) { List <Guid> registrationTemplateGuids = selectionValues[0].Split(',').AsGuidList(); var registrationInstanceService = new RegistrationInstanceService((RockContext)serviceInstance.Context); var registrationInstanceIds = registrationInstanceService.Queryable().Where(ri => registrationTemplateGuids.Contains(ri.RegistrationTemplate.Guid)).Select(ri => ri.Id).Distinct().ToList(); RegistrationRegistrantService registrationRegistrantService = new RegistrationRegistrantService((RockContext)serviceInstance.Context); bool includeInactiveRegistrationInstances = false; if (selectionValues.Length >= 2) { includeInactiveRegistrationInstances = selectionValues[1].AsBooleanOrNull() ?? true;; } else { // if options where saved before this option was added, set to false, even though it would have included inactive before includeInactiveRegistrationInstances = false; } var registrationRegistrantServiceQry = registrationRegistrantService.Queryable(); if (registrationTemplateGuids.Count > 0) { registrationRegistrantServiceQry = registrationRegistrantServiceQry.Where(xx => registrationInstanceIds.Contains(xx.Registration.RegistrationInstanceId)); } if (selectionValues.Length >= 3) { string slidingDelimitedValues = selectionValues[2].Replace(',', '|'); DateRange dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(slidingDelimitedValues); if (dateRange.Start.HasValue) { registrationRegistrantServiceQry = registrationRegistrantServiceQry.Where(xx => xx.CreatedDateTime >= dateRange.Start.Value); } if (dateRange.End.HasValue) { registrationRegistrantServiceQry = registrationRegistrantServiceQry.Where(xx => xx.CreatedDateTime < dateRange.End.Value); } } var qry = new PersonService((RockContext)serviceInstance.Context).Queryable() .Where(p => registrationRegistrantServiceQry.Any(xx => xx.PersonAlias.PersonId == p.Id)); Expression extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p"); return(extractedFilterExpression); } return(null); }
private Rock.Model.Registration BuildRegistration(RockContext rockContext, DateTime?requestDate) { var registrationInstance = new RegistrationInstanceService(rockContext).Queryable().First(); var registration = new Rock.Model.Registration(); registration.RegistrationInstanceId = registrationInstance.Id; registration.ForeignKey = registrationForiegnKey; registration.CreatedDateTime = requestDate; return(registration); }
/// <summary> /// Handles the SaveClick event of the dlgExistingLinkage 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 dlgExistingLinkage_SaveClick(object sender, EventArgs e) { int?registrationInstanceId = ddlExistingLinkageInstance.SelectedValueAsInt(); if (registrationInstanceId.HasValue) { var rockContext = new RockContext(); var registrationInstance = new RegistrationInstanceService(rockContext).Get(registrationInstanceId.Value); if (registrationInstance != null) { LinkageState.RegistrationInstanceId = registrationInstance.Id; LinkageState.RegistrationInstance = registrationInstance; } int?groupId = gpExistingLinkageGroup.SelectedValueAsInt(); if (groupId.HasValue) { var group = new GroupService(rockContext).Get(groupId.Value); if (group != null) { LinkageState.GroupId = group.Id; LinkageState.Group = group; } } LinkageState.PublicName = tbExistingLinkagePublicName.Text; LinkageState.UrlSlug = tbExistingLinkageUrlSlug.Text; // Set the Guid now (otherwise it will not be valid ) bool isNew = LinkageState.Guid == Guid.Empty; if (isNew) { LinkageState.Guid = Guid.NewGuid(); } if (!LinkageState.IsValid) { // If validation failed and this is new, reset the guid back to empty if (isNew) { LinkageState.Guid = Guid.Empty; } return; } DisplayRegistration(); HideDialog(); } }
/// <summary> /// Loads the registration. /// </summary> private void LoadData() { int?registrationInstanceId = PageParameter("RegistrationInstanceId").AsIntegerOrNull(); if (registrationInstanceId.HasValue) { using (RockContext rockContext = new RockContext()) { RegistrationInstanceService registrationInstanceService = new RegistrationInstanceService(rockContext); // NOTE: Do not use AsNoTracking because lava might need to lazy load some stuff _registrationInstance = registrationInstanceService.Queryable("RegistrationTemplate") .Where(r => r.Id == registrationInstanceId).FirstOrDefault(); var registrationSample = _registrationInstance.Registrations.Where(r => r.BalanceDue > 0).FirstOrDefault(); if (registrationSample != null) { Dictionary <string, object> mergeObjects = new Dictionary <string, object>(); mergeObjects.Add("Registration", registrationSample); mergeObjects.Add("RegistrationInstance", _registrationInstance); ceEmailMessage.Text = _registrationInstance.RegistrationTemplate.PaymentReminderEmailTemplate; ifEmailPreview.Attributes["srcdoc"] = _registrationInstance.RegistrationTemplate.PaymentReminderEmailTemplate.ResolveMergeFields(mergeObjects); // needed to work in IE ifEmailPreview.Src = "javascript: window.frameElement.getAttribute('srcdoc');"; txtFromEmail.Text = _registrationInstance.RegistrationTemplate.PaymentReminderFromEmail.ResolveMergeFields(mergeObjects); txtFromName.Text = _registrationInstance.RegistrationTemplate.PaymentReminderFromName.ResolveMergeFields(mergeObjects); txtFromSubject.Text = _registrationInstance.RegistrationTemplate.PaymentReminderSubject.ResolveMergeFields(mergeObjects); if (_registrationInstance.RegistrationTemplate.PaymentReminderTimeSpan.HasValue) { lBalanceInstructions.Text = string.Format("<p>Below is a list of registrations with outstanding balances. Individuals who have not been reminded of their balance in {0} days have been pre-selected. Those who have been recently added or notified of their balance are greyed out. They can be still be included by either selecting them or selecting all transactions.</p>", _registrationInstance.RegistrationTemplate.PaymentReminderTimeSpan.Value); } } else { pnlPreview.Visible = false; nbMessages.Text = "<strong>Good News!</strong> No registrations have an outstanding balance at this time."; } LoadOutstandingBalances(); } } }
/// <summary> /// Handles the Click event of the lbTemplate 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 lbTemplate_Click(object sender, EventArgs e) { var qryParams = new Dictionary <string, string>(); using (var rockContext = new RockContext()) { var service = new RegistrationInstanceService(rockContext); var registrationInstance = service.Get(hfRegistrationInstanceId.Value.AsInteger()); if (registrationInstance != null) { qryParams.Add(PageParameterKey.RegistrationTemplateId, registrationInstance.RegistrationTemplateId.ToString()); } } NavigateToParentPage(qryParams); }
public virtual HttpResponseMessage DetachPlacementGroup(int groupId, int registrationTemplatePlacementId, int?registrationInstanceId = null) { // since we are doing a delete, create a new RockContext instead of this.Service.Context so that ProxyCreation, etc works var rockContext = new RockContext(); var group = new GroupService(rockContext).Get(groupId); if (group == null) { return(ControllerContext.Request.CreateErrorResponse( HttpStatusCode.NotFound, $"Specified group not found.")); } if (registrationInstanceId.HasValue) { var registrationInstanceService = new RegistrationInstanceService(rockContext); var registrationInstance = registrationInstanceService.Get(registrationInstanceId.Value); if (registrationInstance == null) { return(ControllerContext.Request.CreateErrorResponse( HttpStatusCode.NotFound, $"Specified registration instance not found.")); } registrationInstanceService.DeleteRegistrationInstancePlacementGroup(registrationInstance, group); } else { var registrationTemplatePlacementService = new RegistrationTemplatePlacementService(rockContext); var registrationTemplatePlacement = registrationTemplatePlacementService.Get(registrationTemplatePlacementId); if (registrationTemplatePlacement == null) { return(ControllerContext.Request.CreateErrorResponse( HttpStatusCode.NotFound, $"Specified registration template placement not found.")); } registrationTemplatePlacementService.DeleteRegistrationTemplatePlacementPlacementGroup(registrationTemplatePlacement, group); } rockContext.SaveChanges(); return(new HttpResponseMessage(HttpStatusCode.OK)); }
/// <summary> /// Returns the field's current value(s) /// </summary> /// <param name="parentControl">The parent control.</param> /// <param name="value">Information about the value</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="condensed">Flag indicating if the value should be condensed (i.e. for use in a grid column)</param> /// <returns></returns> public override string FormatValue(Control parentControl, string value, Dictionary <string, ConfigurationValue> configurationValues, bool condensed) { string formattedValue = string.Empty; Guid guid = Guid.Empty; if (Guid.TryParse(value, out guid)) { var registrationInstance = new RegistrationInstanceService(new RockContext()).Get(guid); if (registrationInstance != null) { formattedValue = registrationInstance.Name; } } return(base.FormatValue(parentControl, formattedValue, null, condensed)); }
/// <summary> /// Handles the SelectItem event of the gpLinkageGroup 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 gpLinkageGroup_SelectItem(object sender, EventArgs e) { var rockContext = new RockContext(); var registrationInstance = new RegistrationInstanceService(rockContext).Get(PageParameter("RegistrationInstanceId").AsInteger()); var group = new GroupService(rockContext).Get(gpLinkageGroup.SelectedValue.AsInteger()); bool showGroupTypeWarning = false; if (registrationInstance != null && group != null) { if (registrationInstance.RegistrationTemplate.GroupTypeId != group.GroupTypeId) { showGroupTypeWarning = true; } } nbGroupTypeWarning.Visible = showGroupTypeWarning; }
/// <summary> /// Handles the CheckedChanged event of the tglEmailBodyView 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 tglEmailBodyView_CheckedChanged(object sender, EventArgs e) { if (tglEmailBodyView.Checked) { ceEmailMessage.Visible = false; ifEmailPreview.Visible = true; // reload preview int?registrationInstanceId = PageParameter("RegistrationInstanceId").AsIntegerOrNull(); if (registrationInstanceId.HasValue) { using (RockContext rockContext = new RockContext()) { RegistrationInstanceService registrationInstanceService = new RegistrationInstanceService(rockContext); // NOTE: Do not use AsNoTracking because lava might need to lazy load some stuff _registrationInstance = registrationInstanceService.Queryable("RegistrationTemplate") .Where(r => r.Id == registrationInstanceId).FirstOrDefault(); var registrationSample = _registrationInstance.Registrations.Where(r => r.BalanceDue > 0).FirstOrDefault(); if (registrationSample != null) { Dictionary <string, object> mergeObjects = new Dictionary <string, object>(); mergeObjects.Add("Registration", registrationSample); mergeObjects.Add("RegistrationInstance", _registrationInstance); ifEmailPreview.Attributes["srcdoc"] = ceEmailMessage.Text.ResolveMergeFields(mergeObjects); // needed to work in IE ifEmailPreview.Src = "javascript: window.frameElement.getAttribute('srcdoc');"; } } } } else { ceEmailMessage.Visible = true; ifEmailPreview.Visible = false; } }
/// <summary> /// Sets the value. ( as Guid ) /// </summary> /// <param name="control">The control.</param> /// <param name="configurationValues">The configuration values.</param> /// <param name="value">The value.</param> public override void SetEditValue(System.Web.UI.Control control, Dictionary <string, ConfigurationValue> configurationValues, string value) { var picker = control as RegistrationInstancePicker; if (picker != null) { int? itemId = null; Guid?itemGuid = value.AsGuidOrNull(); if (itemGuid.HasValue) { using (var rockContext = new RockContext()) { itemId = new RegistrationInstanceService(rockContext).Queryable().Where(a => a.Guid == itemGuid.Value).Select(a => ( int? )a.Id).FirstOrDefault(); } } picker.RegistrationInstanceId = itemId; } }
/// <summary> /// Builds the fees controls in the fee placeholder. /// </summary> /// <param name="setValues">if set to <c>true</c> [set values].</param> private void BuildFees(bool setValues) { phFees.Controls.Clear(); var registrationInstance = new RegistrationInstanceService(new RockContext()).GetNoTracking(RegistrationInstanceId); if (this.RegistrationTemplate.Fees != null && this.RegistrationTemplate.Fees.Any()) { divFees.Visible = true; foreach (var fee in this.RegistrationTemplate.Fees.OrderBy(f => f.Order)) { var feeValues = GetFeeValues(fee); fee.AddFeeControl(phFees, registrationInstance, true, feeValues, null); } } else { divFees.Visible = false; } }
/// <summary> /// Formats the selection. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override string FormatSelection(Type entityType, string selection) { SelectionConfig selectionConfig = SelectionConfig.Parse(selection); string filterOptions = selectionConfig.RegistrationType == RegistrationTypeSpecifier.Registrar ? "Registrar" : "Registrant"; var waitlistFilterStatus = selectionConfig.OnWaitList == null ? string.Empty : Convert.ToBoolean(selectionConfig.OnWaitList) ? ", only wait list" : ", no wait list"; var registrationInstance = new RegistrationInstanceService(new RockContext()).Queryable().Where(a => a.Guid == selectionConfig.RegistrationInstanceGuid).FirstOrDefault(); if (registrationInstance != null) { return(string.Format("{0} in registration instance '{1}' {2}", filterOptions, registrationInstance.Name, waitlistFilterStatus)); } else { var registrationTemplate = new RegistrationTemplateService(new RockContext()).Queryable().Where(t => t.Id == selectionConfig.RegistrationTemplateId).FirstOrDefault(); return(string.Format("{0} in any registration instance of template '{1}' {2}", filterOptions, registrationTemplate.Name, waitlistFilterStatus)); } }
/// <summary> /// Reads new values entered by the user for the field ( as Guid ) /// </summary> /// <param name="control">Parent control that controls were added to in the CreateEditControl() method</param> /// <param name="configurationValues">The configuration values.</param> /// <returns></returns> public override string GetEditValue(System.Web.UI.Control control, Dictionary <string, ConfigurationValue> configurationValues) { var picker = control as RegistrationInstancePicker; if (picker != null) { int? itemId = picker.RegistrationInstanceId; Guid?itemGuid = null; if (itemId.HasValue) { using (var rockContext = new RockContext()) { itemGuid = new RegistrationInstanceService(rockContext).Queryable().AsNoTracking().Where(a => a.Id == itemId.Value).Select(a => ( Guid? )a.Guid).FirstOrDefault(); } } return(itemGuid?.ToString() ?? string.Empty); } return(null); }
/// <summary> /// Binds the instances grid. /// </summary> protected void BindInstancesGrid() { pnlInstances.Visible = true; using (var rockContext = new RockContext()) { RegistrationInstanceService instanceService = new RegistrationInstanceService(rockContext); var qry = instanceService.Queryable() .Where(i => (i.StartDateTime <= RockDateTime.Now || !i.StartDateTime.HasValue) && (i.EndDateTime > RockDateTime.Now || !i.EndDateTime.HasValue) && i.IsActive) .AsEnumerable() .Where(g => g.IsAuthorized(Rock.Security.Authorization.VIEW, CurrentPerson)) .AsQueryable() .OrderBy(i => i.StartDateTime); var sortProperty = gRegInstances.SortProperty; if (sortProperty != null) { qry = qry.Sort(sortProperty); } var qryResult = qry .Select(i => new { i.Id, i.Guid, i.Name, i.StartDateTime, i.EndDateTime, i.IsActive, i.Details, Registrants = i.Registrations.Where(r => !r.IsTemporary).SelectMany(r => r.Registrants).Count() }); gRegInstances.SetLinqDataSource(qryResult); gRegInstances.DataBind(); } }
/// <summary> /// Handles the CheckedChanged event of the tglEmailBodyView 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 tglEmailBodyView_CheckedChanged(object sender, EventArgs e) { if (tglEmailBodyView.Checked) { ceEmailMessage.Visible = false; ifEmailPreview.Visible = true; // reload preview int?registrationInstanceId = PageParameter("RegistrationInstanceId").AsIntegerOrNull(); if (registrationInstanceId.HasValue) { using (RockContext rockContext = new RockContext()) { RegistrationInstanceService registrationInstanceService = new RegistrationInstanceService(rockContext); _registrationInstance = registrationInstanceService.Queryable("RegistrationTemplate").AsNoTracking() .Where(r => r.Id == registrationInstanceId).FirstOrDefault(); var registrationSample = _registrationInstance.Registrations.Where(r => r.BalanceDue > 0).FirstOrDefault(); if (registrationSample != null) { Dictionary <string, object> mergeObjects = new Dictionary <string, object>(); mergeObjects.Add("Registration", registrationSample); mergeObjects.Add("RegistrationInstance", _registrationInstance); ifEmailPreview.Attributes["srcdoc"] = ceEmailMessage.Text.ResolveMergeFields(mergeObjects); } } } } else { ceEmailMessage.Visible = true; ifEmailPreview.Visible = false; } }
/// <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> /// Binds the instances grid. /// </summary> protected void BindInstancesGrid() { pnlInstances.Visible = true; using ( var rockContext = new RockContext() ) { RegistrationInstanceService instanceService = new RegistrationInstanceService( rockContext ); var qry = instanceService.Queryable() .Where( i => i.StartDateTime <= RockDateTime.Now && i.EndDateTime > RockDateTime.Now && i.IsActive ) .OrderBy( i => i.StartDateTime ); var sortProperty = gRegInstances.SortProperty; if ( sortProperty != null ) { qry = qry.Sort( sortProperty ); } var qryResult = qry .Select( i => new { i.Id, i.Guid, i.Name, i.StartDateTime, i.EndDateTime, i.IsActive, i.Details, Registrants = i.Registrations.Where( r => !r.IsTemporary ).SelectMany( r => r.Registrants ).Count() } ); gRegInstances.SetLinqDataSource( qryResult ); gRegInstances.DataBind(); } }
/// <summary> /// Handles the Click event of the lbWizardTemplate 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 lbWizardTemplate_Click( object sender, EventArgs e ) { var qryParams = new Dictionary<string, string>(); var pageCache = PageCache.Read( RockPage.PageId ); int templateId = 0; if ( Registration != null && Registration.RegistrationInstance != null ) { templateId = Registration.RegistrationInstance.RegistrationTemplateId; } else { using ( var rockContext = new RockContext() ) { int instanceId = PageParameter( "RegistrationInstanceId" ).AsInteger(); templateId = new RegistrationInstanceService( rockContext ) .Queryable().AsNoTracking() .Where( i => i.Id == instanceId ) .Select( i => i.RegistrationTemplateId ) .FirstOrDefault(); } } if ( pageCache != null && pageCache.ParentPage != null && pageCache.ParentPage.ParentPage != null ) { qryParams.Add( "RegistrationTemplateId", templateId.ToString() ); NavigateToPage( pageCache.ParentPage.ParentPage.Guid, qryParams ); } }
/// <summary> /// Starts the refund process. /// </summary> private void StartRefunds() { long totalMilliseconds = 0; var importTask = new Task(() => { // wait a little so the browser can render and start listening to events System.Threading.Thread.Sleep(1000); _hubContext.Clients.All.showButtons(this.SignalRNotificationKey, false); Stopwatch stopwatch = Stopwatch.StartNew(); List <int> registrationTemplateIds = rtpRegistrationTemplate.ItemIds.AsIntegerList(); registrationTemplateIds.RemoveAll(i => i.Equals(0)); if (registrationTemplateIds.Count > 0) { RockContext rockContext = new RockContext(); List <int> registrationInstanceIds = new List <int>(); if (ddlRegistrationInstance.SelectedValueAsId().HasValue&& ddlRegistrationInstance.SelectedValueAsId() > 0) { registrationInstanceIds.Add(ddlRegistrationInstance.SelectedValueAsId().Value); } else { RegistrationTemplateService registrationTemplateService = new RegistrationTemplateService(rockContext); var templates = registrationTemplateService.GetByIds(rtpRegistrationTemplate.ItemIds.AsIntegerList()); int registrationCount = templates.SelectMany(t => t.Instances).SelectMany(i => i.Registrations).Count(); registrationInstanceIds.AddRange(templates.SelectMany(t => t.Instances).OrderBy(i => i.Name).Select(i => i.Id)); } RegistrationInstanceService registrationInstanceService = new RegistrationInstanceService(rockContext); SystemEmailService systemEmailService = new SystemEmailService(rockContext); // Load the registration instance and then iterate through all registrations. var registrations = registrationInstanceService.Queryable().Where(ri => registrationInstanceIds.Contains(ri.Id)).SelectMany(ri => ri.Registrations); int j = 1; foreach (Registration registration in registrations) { bool issuedRefund = false; OnProgress("Processing registration refund " + j + " of " + registrations.Count()); foreach (var payment in registration.GetPayments(rockContext)) { decimal refundAmount = payment.Amount + payment.Transaction.Refunds.Sum(r => r.FinancialTransaction.TotalAmount); // If refunds totalling the amount of the payments have not already been issued if (payment.Amount > 0 && refundAmount > 0) { string errorMessage; using (var refundRockContext = new RockContext()) { var financialTransactionService = new FinancialTransactionService(refundRockContext); var refundTransaction = financialTransactionService.ProcessRefund(payment.Transaction, refundAmount, dvpRefundReason.SelectedDefinedValueId, tbRefundSummary.Text, true, string.Empty, out errorMessage); if (refundTransaction != null) { refundRockContext.SaveChanges(); } if (!string.IsNullOrWhiteSpace(errorMessage)) { results["Fail"] += string.Format("Failed refund for registration {0}: {1}", registration.FirstName + " " + registration.LastName, errorMessage) + Environment.NewLine; } else { results["Success"] += string.Format("Successfully issued {0} refund for registration {1} payment {2} ({3}) - Refund Transaction Id: {4}, Amount: {5}", refundAmount < payment.Amount?"Partial":"Full", registration.FirstName + " " + registration.LastName, payment.Transaction.TransactionCode, payment.Transaction.TotalAmount, refundTransaction.TransactionCode, refundTransaction.TotalAmount.FormatAsCurrency()) + Environment.NewLine; issuedRefund = true; } } System.Threading.Thread.Sleep(2500); } else if (payment.Transaction.Refunds.Count > 0) { results["Success"] += string.Format("Refund already issued for registration {0} payment {1} ({2})", registration.FirstName + " " + registration.LastName, payment.Transaction.TransactionCode, payment.Transaction.TotalAmount) + Environment.NewLine; } } j++; // Send an email if applicable if (issuedRefund && !string.IsNullOrWhiteSpace(registration.ConfirmationEmail) && ddlSystemEmail.SelectedValueAsInt().HasValue&& ddlSystemEmail.SelectedValueAsInt() > 0) { var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage); mergeFields.Add("Registration", registration); SystemEmail systemEmail = systemEmailService.Get(ddlSystemEmail.SelectedValueAsInt().Value); var emailMessage = new RockEmailMessage(systemEmail); emailMessage.AdditionalMergeFields = mergeFields; emailMessage.AddRecipient(new RecipientData(registration.ConfirmationEmail, mergeFields)); emailMessage.CreateCommunicationRecord = true; emailMessage.Send(); } } } stopwatch.Stop(); totalMilliseconds = stopwatch.ElapsedMilliseconds; _hubContext.Clients.All.showButtons(this.SignalRNotificationKey, true); }); importTask.ContinueWith((t) => { if (t.IsFaulted) { foreach (var exception in t.Exception.InnerExceptions) { LogException(exception); } OnProgress("ERROR: " + t.Exception.Message); } else { OnProgress(string.Format("{0} Complete: [{1}ms]", "All refunds have been issued.", totalMilliseconds)); } }); importTask.Start(); }
/// <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 ) { RegistrationInstance instance = null; bool newInstance = false; using ( var rockContext = new RockContext() ) { var service = new RegistrationInstanceService( rockContext ); int? RegistrationInstanceId = hfRegistrationInstanceId.Value.AsIntegerOrNull(); if ( RegistrationInstanceId.HasValue ) { instance = service.Get( RegistrationInstanceId.Value ); } if ( instance == null ) { instance = new RegistrationInstance(); instance.RegistrationTemplateId = PageParameter( "RegistrationTemplateId" ).AsInteger(); service.Add( instance ); newInstance = true; } rieDetails.GetValue( instance ); if ( !Page.IsValid ) { return; } rockContext.SaveChanges(); } if ( newInstance ) { var qryParams = new Dictionary<string, string>(); qryParams.Add( "RegistrationTemplateId", PageParameter( "RegistrationTemplateId" ) ); qryParams.Add( "RegistrationInstanceId", instance.Id.ToString() ); NavigateToCurrentPage( qryParams ); } else { // Reload instance and show readonly view using ( var rockContext = new RockContext() ) { instance = new RegistrationInstanceService( rockContext ).Get( instance.Id ); ShowReadonlyDetails( instance ); } // show send payment reminder link if ( !string.IsNullOrWhiteSpace( GetAttributeValue( "PaymentReminderPage" ) ) && ( ( instance.RegistrationTemplate.SetCostOnInstance.HasValue && instance.RegistrationTemplate.SetCostOnInstance == true && instance.Cost.HasValue && instance.Cost.Value > 0 ) || instance.RegistrationTemplate.Cost > 0 ) ) { btnSendPaymentReminder.Visible = true; } else { btnSendPaymentReminder.Visible = false; } } }
/// <summary> /// Loads the registration. /// </summary> private void LoadData() { int? registrationInstanceId = PageParameter( "RegistrationInstanceId" ).AsIntegerOrNull(); if ( registrationInstanceId.HasValue ) { using ( RockContext rockContext = new RockContext() ) { RegistrationInstanceService registrationInstanceService = new RegistrationInstanceService( rockContext ); _registrationInstance = registrationInstanceService.Queryable( "RegistrationTemplate" ).AsNoTracking() .Where( r => r.Id == registrationInstanceId ).FirstOrDefault(); var registrationSample = _registrationInstance.Registrations.Where( r => r.BalanceDue > 0 ).FirstOrDefault(); if ( registrationSample != null ) { Dictionary<string, object> mergeObjects = new Dictionary<string, object>(); mergeObjects.Add( "Registration", registrationSample ); mergeObjects.Add( "RegistrationInstance", _registrationInstance ); ceEmailMessage.Text = _registrationInstance.RegistrationTemplate.PaymentReminderEmailTemplate; ifEmailPreview.Attributes["srcdoc"] = _registrationInstance.RegistrationTemplate.PaymentReminderEmailTemplate.ResolveMergeFields( mergeObjects ); txtFromEmail.Text = _registrationInstance.RegistrationTemplate.PaymentReminderFromEmail.ResolveMergeFields( mergeObjects ); txtFromName.Text = _registrationInstance.RegistrationTemplate.PaymentReminderFromName.ResolveMergeFields( mergeObjects ); txtFromSubject.Text = _registrationInstance.RegistrationTemplate.PaymentReminderSubject.ResolveMergeFields( mergeObjects ); if ( _registrationInstance.RegistrationTemplate.PaymentReminderTimeSpan.HasValue ) { lBalanceInstructions.Text = string.Format( "<p>Below is a list of registrations with outstanding balances. Individuals who have not been reminded of their balance in {0} days have been pre-selected. Those who have been recently added or notified of their balance are greyed out. They can be still be included by either selecting them or selecting all transactions.</p>", _registrationInstance.RegistrationTemplate.PaymentReminderTimeSpan.Value ); } } else { pnlPreview.Visible = false; nbMessages.Text = "<strong>Good News!</strong> No registrations have an outstanding balance at this time."; } LoadOutstandingBalances(); } } }
/// <summary> /// Handles the Click event of the btnSendReminders 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 btnSendReminders_Click( object sender, EventArgs e ) { var registrationsSelected = new List<int>(); int sendCount = 0; gRegistrations.SelectedKeys.ToList().ForEach( r => registrationsSelected.Add( r.ToString().AsInteger() ) ); if ( registrationsSelected.Any() ) { var appRoot = Rock.Web.Cache.GlobalAttributesCache.Read().GetValue( "ExternalApplicationRoot" ); if ( _registrationInstance == null ) { int? registrationInstanceId = PageParameter( "RegistrationInstanceId" ).AsIntegerOrNull(); using ( RockContext rockContext = new RockContext() ) { RegistrationInstanceService registrationInstanceService = new RegistrationInstanceService( rockContext ); _registrationInstance = registrationInstanceService.Queryable( "RegistrationTemplate" ).AsNoTracking() .Where( r => r.Id == registrationInstanceId ).FirstOrDefault(); } foreach( var registrationId in registrationsSelected ) { // use a new rockContext for each registration so that ChangeTracker doesn't get bogged down using ( RockContext rockContext = new RockContext() ) { var registrationService = new RegistrationService( rockContext ); var registration = registrationService.Get( registrationId ); if ( registration != null && !string.IsNullOrWhiteSpace(registration.ConfirmationEmail) ) { var recipients = new List<string>(); Dictionary<string, object> mergeObjects = new Dictionary<string, object>(); mergeObjects.Add( "Registration", registration ); mergeObjects.Add( "RegistrationInstance", _registrationInstance ); recipients.Add( registration.ConfirmationEmail ); string message = ceEmailMessage.Text.ResolveMergeFields( mergeObjects ); Email.Send( txtFromEmail.Text, txtFromName.Text, txtFromSubject.Text, recipients, message, appRoot ); registration.LastPaymentReminderDateTime = RockDateTime.Now; rockContext.SaveChanges(); sendCount++; } } } } } pnlSend.Visible = false; pnlComplete.Visible = true; nbResult.Text = string.Format("Payment reminders have been sent to {0}.", "individuals".ToQuantity( sendCount )); }
protected void lbTemplate_Click( object sender, EventArgs e ) { var qryParams = new Dictionary<string, string>(); using ( var rockContext = new RockContext() ) { var service = new RegistrationInstanceService( rockContext ); var registrationInstance = service.Get( hfRegistrationInstanceId.Value.AsInteger() ); if ( registrationInstance != null ) { qryParams.Add( "RegistrationTemplateId", registrationInstance.RegistrationTemplateId.ToString() ); } } NavigateToParentPage( qryParams ); }
private void LoadState() { int? registrantId = PageParameter( "RegistrantId" ).AsIntegerOrNull(); int? registrationId = PageParameter( "RegistrationId" ).AsIntegerOrNull(); if ( RegistrantState == null ) { var rockContext = new RockContext(); RegistrationRegistrant registrant = null; if ( registrantId.HasValue && registrantId.Value != 0 ) { registrant = new RegistrationRegistrantService( rockContext ) .Queryable( "Registration.RegistrationInstance.RegistrationTemplate.Forms.Fields,Registration.RegistrationInstance.RegistrationTemplate.Fees,PersonAlias.Person,Fees" ).AsNoTracking() .Where( r => r.Id == registrantId.Value ) .FirstOrDefault(); if ( registrant != null && registrant.Registration != null && registrant.Registration.RegistrationInstance != null && registrant.Registration.RegistrationInstance.RegistrationTemplate != null ) { RegistrantState = new RegistrantInfo( registrant, rockContext ); TemplateState = registrant.Registration.RegistrationInstance.RegistrationTemplate; RegistrationInstanceId = registrant.Registration.RegistrationInstanceId; lWizardTemplateName.Text = registrant.Registration.RegistrationInstance.RegistrationTemplate.Name; lWizardInstanceName.Text = registrant.Registration.RegistrationInstance.Name; lWizardRegistrationName.Text = registrant.Registration.ToString(); lWizardRegistrantName.Text = registrant.ToString(); tglWaitList.Checked = !registrant.OnWaitList; } } if ( TemplateState == null && registrationId.HasValue && registrationId.Value != 0 ) { var registration = new RegistrationService( rockContext ) .Queryable( "RegistrationInstance.RegistrationTemplate.Forms.Fields,RegistrationInstance.RegistrationTemplate.Fees" ).AsNoTracking() .Where( r => r.Id == registrationId.Value ) .FirstOrDefault(); if ( registration != null && registration.RegistrationInstance != null && registration.RegistrationInstance.RegistrationTemplate != null ) { TemplateState = registration.RegistrationInstance.RegistrationTemplate; RegistrationInstanceId = registration.RegistrationInstanceId; lWizardTemplateName.Text = registration.RegistrationInstance.RegistrationTemplate.Name; lWizardInstanceName.Text = registration.RegistrationInstance.Name; lWizardRegistrationName.Text = registration.ToString(); lWizardRegistrantName.Text = "New Registrant"; } } if ( TemplateState != null ) { tglWaitList.Visible = TemplateState.WaitListEnabled; } if ( TemplateState != null && RegistrantState == null ) { RegistrantState = new RegistrantInfo(); RegistrantState.RegistrationId = registrationId ?? 0; if ( TemplateState.SetCostOnInstance.HasValue && TemplateState.SetCostOnInstance.Value ) { var instance = new RegistrationInstanceService( rockContext ).Get( RegistrationInstanceId ); if ( instance != null ) { RegistrantState.Cost = instance.Cost ?? 0.0m; } } else { RegistrantState.Cost = TemplateState.Cost; } } if ( registrant != null && registrant.PersonAlias != null && registrant.PersonAlias.Person != null ) { ppPerson.SetValue( registrant.PersonAlias.Person ); if ( TemplateState != null && TemplateState.RequiredSignatureDocumentTemplate != null ) { fuSignedDocument.Label = TemplateState.RequiredSignatureDocumentTemplate.Name; if ( TemplateState.RequiredSignatureDocumentTemplate.BinaryFileType != null ) { fuSignedDocument.BinaryFileTypeGuid = TemplateState.RequiredSignatureDocumentTemplate.BinaryFileType.Guid; } var signatureDocument = new SignatureDocumentService( rockContext ) .Queryable().AsNoTracking() .Where( d => d.SignatureDocumentTemplateId == TemplateState.RequiredSignatureDocumentTemplateId.Value && d.AppliesToPersonAlias != null && d.AppliesToPersonAlias.PersonId == registrant.PersonAlias.PersonId && d.LastStatusDate.HasValue && d.Status == SignatureDocumentStatus.Signed && d.BinaryFile != null ) .OrderByDescending( d => d.LastStatusDate.Value ) .FirstOrDefault(); if ( signatureDocument != null ) { hfSignedDocumentId.Value = signatureDocument.Id.ToString(); fuSignedDocument.BinaryFileId = signatureDocument.BinaryFileId; } fuSignedDocument.Visible = true; } else { fuSignedDocument.Visible = false; } } else { ppPerson.SetValue( null ); } if ( RegistrantState != null ) { cbCost.Text = RegistrantState.Cost.ToString( "N2" ); cbDiscountApplies.Checked = RegistrantState.DiscountApplies; } } }
/// <summary> /// Gets the registration instance. /// </summary> /// <param name="registrationInstanceId">The registration instance identifier.</param> /// <param name="rockContext">The rock context.</param> /// <returns></returns> private RegistrationInstance GetRegistrationInstance( int registrationInstanceId, RockContext rockContext = null ) { string key = string.Format( "RegistrationInstance:{0}", registrationInstanceId ); RegistrationInstance registrationInstance = RockPage.GetSharedItem( key ) as RegistrationInstance; if ( registrationInstance == null ) { rockContext = rockContext ?? new RockContext(); registrationInstance = new RegistrationInstanceService( rockContext ) .Queryable( "RegistrationTemplate,Account,RegistrationTemplate.Forms.Fields" ) .AsNoTracking() .FirstOrDefault( i => i.Id == registrationInstanceId ); RockPage.SaveSharedItem( key, registrationInstance ); } return registrationInstance; }
/// <summary> /// Handles the Click event of the btnEdit 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 btnEdit_Click( object sender, EventArgs e ) { using ( var rockContext = new RockContext() ) { var registrationInstance = new RegistrationInstanceService( rockContext ).Get( hfRegistrationInstanceId.Value.AsInteger() ); ShowEditDetails( registrationInstance, rockContext ); } }
/// <summary> /// Handles the Click event of the btnCancel 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 btnCancel_Click( object sender, EventArgs e ) { if ( hfRegistrationInstanceId.Value.Equals( "0" ) ) { var qryParams = new Dictionary<string, string>(); int? parentTemplateId = PageParameter( "RegistrationTemplateId" ).AsIntegerOrNull(); if ( parentTemplateId.HasValue ) { qryParams["RegistrationTemplateId"] = parentTemplateId.ToString(); } // Cancelling on Add. Return to Grid NavigateToParentPage( qryParams ); } else { // Cancelling on Edit. Return to Details using ( var rockContext = new RockContext() ) { RegistrationInstanceService service = new RegistrationInstanceService( rockContext ); RegistrationInstance item = service.Get( int.Parse( hfRegistrationInstanceId.Value ) ); ShowReadonlyDetails( item ); } } }
/// <summary> /// Binds the registrants grid. /// </summary> private void BindRegistrantsGrid( bool isExporting = false ) { int? instanceId = hfRegistrationInstanceId.Value.AsIntegerOrNull(); if ( instanceId.HasValue ) { using ( var rockContext = new RockContext() ) { var registrationInstance = new RegistrationInstanceService( rockContext ).Get( instanceId.Value ); if ( registrationInstance != null && registrationInstance.RegistrationTemplate != null && registrationInstance.RegistrationTemplate.RequiredSignatureDocumentTemplateId.HasValue ) { Signers = new SignatureDocumentService( rockContext ) .Queryable().AsNoTracking() .Where( d => d.SignatureDocumentTemplateId == registrationInstance.RegistrationTemplate.RequiredSignatureDocumentTemplateId.Value && d.Status == SignatureDocumentStatus.Signed && d.BinaryFileId.HasValue && d.AppliesToPersonAlias != null ) .OrderByDescending( d => d.LastStatusDate ) .Select( d => d.AppliesToPersonAlias.PersonId ) .ToList(); } // Start query for registrants var qry = new RegistrationRegistrantService( rockContext ) .Queryable( "PersonAlias.Person.PhoneNumbers.NumberTypeValue,Fees.RegistrationTemplateFee,GroupMember.Group" ).AsNoTracking() .Where( r => r.Registration.RegistrationInstanceId == instanceId.Value && r.PersonAlias != null && r.PersonAlias.Person != null ); // Filter by daterange if ( drpRegistrantDateRange.LowerValue.HasValue ) { qry = qry.Where( r => r.CreatedDateTime.HasValue && r.CreatedDateTime.Value >= drpRegistrantDateRange.LowerValue.Value ); } if ( drpRegistrantDateRange.UpperValue.HasValue ) { qry = qry.Where( r => r.CreatedDateTime.HasValue && r.CreatedDateTime.Value <= drpRegistrantDateRange.UpperValue.Value ); } // Filter by first name if ( !string.IsNullOrWhiteSpace( tbRegistrantFirstName.Text ) ) { string rfname = tbRegistrantFirstName.Text; qry = qry.Where( r => r.PersonAlias.Person.NickName.StartsWith( rfname ) || r.PersonAlias.Person.FirstName.StartsWith( rfname ) ); } // Filter by last name if ( !string.IsNullOrWhiteSpace( tbRegistrantLastName.Text ) ) { string rlname = tbRegistrantLastName.Text; qry = qry.Where( r => r.PersonAlias.Person.LastName.StartsWith( rlname ) ); } // Filter by signed documents if ( Signers != null ) { if ( ddlSignedDocument.SelectedValue.AsBooleanOrNull() == true ) { qry = qry.Where( r => Signers.Contains( r.PersonAlias.PersonId ) ); } else if ( ddlSignedDocument.SelectedValue.AsBooleanOrNull() == false ) { qry = qry.Where( r => !Signers.Contains( r.PersonAlias.PersonId ) ); } } if ( ddlInGroup.SelectedValue.AsBooleanOrNull() == true ) { qry = qry.Where( r => r.GroupMemberId.HasValue ); } else if ( ddlInGroup.SelectedValue.AsBooleanOrNull() == false ) { qry = qry.Where( r => !r.GroupMemberId.HasValue ); } bool preloadCampusValues = false; var registrantAttributes = new List<AttributeCache>(); var personAttributes = new List<AttributeCache>(); var groupMemberAttributes = new List<AttributeCache>(); var registrantAttributeIds = new List<int>(); var personAttributesIds = new List<int>(); var groupMemberAttributesIds = new List<int>(); if ( isExporting ) { // get list of home addresses var personIds = qry.Select( r => r.PersonAlias.PersonId ).ToList(); _homeAddresses = Person.GetHomeLocations( personIds ); } if ( RegistrantFields != null ) { // Filter by any selected foreach ( var personFieldType in RegistrantFields .Where( f => f.FieldSource == RegistrationFieldSource.PersonField && f.PersonFieldType.HasValue ) .Select( f => f.PersonFieldType.Value ) ) { switch ( personFieldType ) { case RegistrationPersonFieldType.Campus: { preloadCampusValues = true; var ddlCampus = phRegistrantFormFieldFilters.FindControl( "ddlCampus" ) as RockDropDownList; if ( ddlCampus != null ) { var campusId = ddlCampus.SelectedValue.AsIntegerOrNull(); if ( campusId.HasValue ) { var familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid(); qry = qry.Where( r => r.PersonAlias.Person.Members.Any( m => m.Group.GroupType.Guid == familyGroupTypeGuid && m.Group.CampusId.HasValue && m.Group.CampusId.Value == campusId ) ); } } break; } case RegistrationPersonFieldType.Email: { var tbEmailFilter = phRegistrantFormFieldFilters.FindControl( "tbEmailFilter" ) as RockTextBox; if ( tbEmailFilter != null && !string.IsNullOrWhiteSpace( tbEmailFilter.Text ) ) { qry = qry.Where( r => r.PersonAlias.Person.Email != null && r.PersonAlias.Person.Email.Contains( tbEmailFilter.Text ) ); } break; } case RegistrationPersonFieldType.Birthdate: { var drpBirthdateFilter = phRegistrantFormFieldFilters.FindControl( "drpBirthdateFilter" ) as DateRangePicker; if ( drpBirthdateFilter != null ) { if ( drpBirthdateFilter.LowerValue.HasValue ) { qry = qry.Where( r => r.PersonAlias.Person.BirthDate.HasValue && r.PersonAlias.Person.BirthDate.Value >= drpBirthdateFilter.LowerValue.Value ); } if ( drpBirthdateFilter.UpperValue.HasValue ) { qry = qry.Where( r => r.PersonAlias.Person.BirthDate.HasValue && r.PersonAlias.Person.BirthDate.Value <= drpBirthdateFilter.UpperValue.Value ); } } break; } case RegistrationPersonFieldType.Grade: { var gpGradeFilter = phRegistrantFormFieldFilters.FindControl( "gpGradeFilter" ) as GradePicker; if ( gpGradeFilter != null ) { int? graduationYear = Person.GraduationYearFromGradeOffset( gpGradeFilter.SelectedValueAsInt( false ) ); if ( graduationYear.HasValue ) { qry = qry.Where( r => r.PersonAlias.Person.GraduationYear.HasValue && r.PersonAlias.Person.GraduationYear == graduationYear.Value ); } } break; } case RegistrationPersonFieldType.Gender: { var ddlGenderFilter = phRegistrantFormFieldFilters.FindControl( "ddlGenderFilter" ) as RockDropDownList; if ( ddlGenderFilter != null ) { var gender = ddlGenderFilter.SelectedValue.ConvertToEnumOrNull<Gender>(); if ( gender.HasValue ) { qry = qry.Where( r => r.PersonAlias.Person.Gender == gender ); } } break; } case RegistrationPersonFieldType.MaritalStatus: { var ddlMaritalStatusFilter = phRegistrantFormFieldFilters.FindControl( "ddlMaritalStatusFilter" ) as RockDropDownList; if ( ddlMaritalStatusFilter != null ) { var maritalStatusId = ddlMaritalStatusFilter.SelectedValue.AsIntegerOrNull(); if ( maritalStatusId.HasValue ) { qry = qry.Where( r => r.PersonAlias.Person.MaritalStatusValueId.HasValue && r.PersonAlias.Person.MaritalStatusValueId.Value == maritalStatusId.Value ); } } break; } case RegistrationPersonFieldType.MobilePhone: { var tbPhoneFilter = phRegistrantFormFieldFilters.FindControl( "tbPhoneFilter" ) as RockTextBox; if ( tbPhoneFilter != null && !string.IsNullOrWhiteSpace( tbPhoneFilter.Text ) ) { string numericPhone = tbPhoneFilter.Text.AsNumeric(); qry = qry.Where( r => r.PersonAlias.Person.PhoneNumbers != null && r.PersonAlias.Person.PhoneNumbers.Any( n => n.Number.Contains( numericPhone ) ) ); } break; } } } // Get all the registrant attributes selected to be on grid registrantAttributes = RegistrantFields .Where( f => f.Attribute != null && f.FieldSource == RegistrationFieldSource.RegistrationAttribute ) .Select( f => f.Attribute ) .ToList(); registrantAttributeIds = registrantAttributes.Select( a => a.Id ).Distinct().ToList(); // Filter query by any configured registrant attribute filters if ( registrantAttributes != null && registrantAttributes.Any() ) { var attributeValueService = new AttributeValueService( rockContext ); var parameterExpression = attributeValueService.ParameterExpression; foreach ( var attribute in registrantAttributes ) { var filterControl = phRegistrantFormFieldFilters.FindControl( "filter_" + attribute.Id.ToString() ); if ( filterControl != null ) { var filterValues = attribute.FieldType.Field.GetFilterValues( filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter ); var expression = attribute.FieldType.Field.AttributeFilterExpression( attribute.QualifierValues, filterValues, parameterExpression ); if ( expression != null ) { var attributeValues = attributeValueService .Queryable() .Where( v => v.Attribute.Id == attribute.Id ); attributeValues = attributeValues.Where( parameterExpression, expression, null ); qry = qry .Where( r => attributeValues.Select( v => v.EntityId ).Contains( r.Id ) ); } } } } // Get all the person attributes selected to be on grid personAttributes = RegistrantFields .Where( f => f.Attribute != null && f.FieldSource == RegistrationFieldSource.PersonAttribute ) .Select( f => f.Attribute ) .ToList(); personAttributesIds = personAttributes.Select( a => a.Id ).Distinct().ToList(); // Filter query by any configured person attribute filters if ( personAttributes != null && personAttributes.Any() ) { var attributeValueService = new AttributeValueService( rockContext ); var parameterExpression = attributeValueService.ParameterExpression; foreach ( var attribute in personAttributes ) { var filterControl = phRegistrantFormFieldFilters.FindControl( "filter_" + attribute.Id.ToString() ); if ( filterControl != null ) { var filterValues = attribute.FieldType.Field.GetFilterValues( filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter ); var expression = attribute.FieldType.Field.AttributeFilterExpression( attribute.QualifierValues, filterValues, parameterExpression ); if ( expression != null ) { var attributeValues = attributeValueService .Queryable() .Where( v => v.Attribute.Id == attribute.Id ); attributeValues = attributeValues.Where( parameterExpression, expression, null ); qry = qry .Where( r => attributeValues.Select( v => v.EntityId ).Contains( r.PersonAlias.PersonId ) ); } } } } // Get all the group member attributes selected to be on grid groupMemberAttributes = RegistrantFields .Where( f => f.Attribute != null && f.FieldSource == RegistrationFieldSource.GroupMemberAttribute ) .Select( f => f.Attribute ) .ToList(); groupMemberAttributesIds = groupMemberAttributes.Select( a => a.Id ).Distinct().ToList(); // Filter query by any configured person attribute filters if ( groupMemberAttributes != null && groupMemberAttributes.Any() ) { var attributeValueService = new AttributeValueService( rockContext ); var parameterExpression = attributeValueService.ParameterExpression; foreach ( var attribute in groupMemberAttributes ) { var filterControl = phRegistrantFormFieldFilters.FindControl( "filter_" + attribute.Id.ToString() ); if ( filterControl != null ) { var filterValues = attribute.FieldType.Field.GetFilterValues( filterControl, attribute.QualifierValues, Rock.Reporting.FilterMode.SimpleFilter ); var expression = attribute.FieldType.Field.AttributeFilterExpression( attribute.QualifierValues, filterValues, parameterExpression ); if ( expression != null ) { var attributeValues = attributeValueService .Queryable() .Where( v => v.Attribute.Id == attribute.Id ); attributeValues = attributeValues.Where( parameterExpression, expression, null ); qry = qry .Where( r => r.GroupMemberId.HasValue && attributeValues.Select( v => v.EntityId ).Contains( r.GroupMemberId.Value ) ); } } } } } // Sort the query IOrderedQueryable<RegistrationRegistrant> orderedQry = null; SortProperty sortProperty = gRegistrants.SortProperty; if ( sortProperty != null ) { orderedQry = qry.Sort( sortProperty ); } else { orderedQry = qry .OrderBy( r => r.PersonAlias.Person.LastName ) .ThenBy( r => r.PersonAlias.Person.NickName ); } // increase the timeout just in case. A complex filter on the grid might slow things down rockContext.Database.CommandTimeout = 180; // Set the grids LinqDataSource which will run query and set results for current page gRegistrants.SetLinqDataSource<RegistrationRegistrant>( orderedQry ); if ( RegistrantFields != null ) { // Get the query results for the current page var currentPageRegistrants = gRegistrants.DataSource as List<RegistrationRegistrant>; if ( currentPageRegistrants != null ) { // Get all the registrant ids in current page of query results var registrantIds = currentPageRegistrants .Select( r => r.Id ) .Distinct() .ToList(); // Get all the person ids in current page of query results var personIds = currentPageRegistrants .Select( r => r.PersonAlias.PersonId ) .Distinct() .ToList(); // Get all the group member ids and the group id in current page of query results var groupMemberIds = new List<int>(); GroupLinks = new Dictionary<int, string>(); foreach ( var groupMember in currentPageRegistrants .Where( m => m.GroupMember != null && m.GroupMember.Group != null ) .Select( m => m.GroupMember ) ) { groupMemberIds.Add( groupMember.Id ); GroupLinks.AddOrIgnore( groupMember.GroupId, isExporting ? groupMember.Group.Name : string.Format( "<a href='{0}'>{1}</a>", LinkedPageUrl( "GroupDetailPage", new Dictionary<string, string> { { "GroupId", groupMember.GroupId.ToString() } } ), groupMember.Group.Name ) ); } // If the campus column was selected to be displayed on grid, preload all the people's // campuses so that the databind does not need to query each row if ( preloadCampusValues ) { PersonCampusIds = new Dictionary<int, List<int>>(); Guid familyGroupTypeGuid = Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid(); foreach ( var personCampusList in new GroupMemberService( rockContext ) .Queryable().AsNoTracking() .Where( m => m.Group.GroupType.Guid == familyGroupTypeGuid && personIds.Contains( m.PersonId ) ) .GroupBy( m => m.PersonId ) .Select( m => new { PersonId = m.Key, CampusIds = m .Where( g => g.Group.CampusId.HasValue ) .Select( g => g.Group.CampusId.Value ) .ToList() } ) ) { PersonCampusIds.Add( personCampusList.PersonId, personCampusList.CampusIds ); } } // If there are any attributes that were selected to be displayed, we're going // to try and read all attribute values in one query and then put them into a // custom grid ObjectList property so that the AttributeField columns don't need // to do the LoadAttributes and querying of values for each row/column if ( personAttributesIds.Any() || groupMemberAttributesIds.Any() || registrantAttributeIds.Any() ) { // Query the attribute values for all rows and attributes var attributeValues = new AttributeValueService( rockContext ) .Queryable( "Attribute" ).AsNoTracking() .Where( v => v.EntityId.HasValue && ( ( personAttributesIds.Contains( v.AttributeId ) && personIds.Contains( v.EntityId.Value ) ) || ( groupMemberAttributesIds.Contains( v.AttributeId ) && groupMemberIds.Contains( v.EntityId.Value ) ) || ( registrantAttributeIds.Contains( v.AttributeId ) && registrantIds.Contains( v.EntityId.Value ) ) ) ) .ToList(); // Get the attributes to add to each row's object var attributes = new Dictionary<string, AttributeCache>(); RegistrantFields .Where( f => f.Attribute != null ) .Select( f => f.Attribute ) .ToList() .ForEach( a => attributes .Add( a.Id.ToString() + a.Key, a ) ); // Initialize the grid's object list gRegistrants.ObjectList = new Dictionary<string, object>(); // Loop through each of the current page's registrants and build an attribute // field object for storing attributes and the values for each of the registrants foreach ( var registrant in currentPageRegistrants ) { // Create a row attribute object var attributeFieldObject = new AttributeFieldObject(); // Add the attributes to the attribute object attributeFieldObject.Attributes = attributes; // Add any person attribute values to object attributeValues .Where( v => personAttributesIds.Contains( v.AttributeId ) && v.EntityId.Value == registrant.PersonAlias.PersonId ) .ToList() .ForEach( v => attributeFieldObject.AttributeValues .Add( v.AttributeId.ToString() + v.Attribute.Key, new AttributeValueCache( v ) ) ); // Add any group member attribute values to object if ( registrant.GroupMemberId.HasValue ) { attributeValues .Where( v => groupMemberAttributesIds.Contains( v.AttributeId ) && v.EntityId.Value == registrant.GroupMemberId.Value ) .ToList() .ForEach( v => attributeFieldObject.AttributeValues .Add( v.AttributeId.ToString() + v.Attribute.Key, new AttributeValueCache( v ) ) ); } // Add any registrant attribute values to object attributeValues .Where( v => registrantAttributeIds.Contains( v.AttributeId ) && v.EntityId.Value == registrant.Id ) .ToList() .ForEach( v => attributeFieldObject.AttributeValues .Add( v.AttributeId.ToString() + v.Attribute.Key, new AttributeValueCache( v ) ) ); // Add row attribute object to grid's object list gRegistrants.ObjectList.Add( registrant.Id.ToString(), attributeFieldObject ); } } } } gRegistrants.DataBind(); } } }
/// <summary> /// Sets the registration state /// </summary> private bool SetRegistrationState() { string registrationSlug = PageParameter( SLUG_PARAM_NAME ); int? registrationInstanceId = PageParameter( REGISTRATION_INSTANCE_ID_PARAM_NAME ).AsIntegerOrNull(); int? registrationId = PageParameter( REGISTRATION_ID_PARAM_NAME ).AsIntegerOrNull(); int? groupId = PageParameter( GROUP_ID_PARAM_NAME ).AsIntegerOrNull(); int? campusId = PageParameter( CAMPUS_ID_PARAM_NAME ).AsIntegerOrNull(); int? eventOccurrenceId = PageParameter( EVENT_OCCURRENCE_ID_PARAM_NAME ).AsIntegerOrNull(); // Not inside a "using" due to serialization needing context to still be active var rockContext = new RockContext(); // An existing registration id was specified if ( registrationId.HasValue ) { var registrationService = new RegistrationService( rockContext ); var registration = registrationService .Queryable( "Registrants.PersonAlias.Person,Registrants.GroupMember,RegistrationInstance.Account,RegistrationInstance.RegistrationTemplate.Fees,RegistrationInstance.RegistrationTemplate.Discounts,RegistrationInstance.RegistrationTemplate.Forms.Fields.Attribute,RegistrationInstance.RegistrationTemplate.FinancialGateway" ) .Where( r => r.Id == registrationId.Value ) .FirstOrDefault(); if ( registration == null ) { ShowError( "Error", "Registration not found" ); return false; } if ( CurrentPersonId == null ) { ShowWarning( "Please log in", "You must be logged in to access this registration." ); return false; } // Only allow the person that was logged in when this registration was created. // If the logged in person, registered on someone elses behalf (for example, husband logged in, but entered wife's name as the Registrar), // also allow that person to access the regisratiuon if ( ( registration.PersonAlias != null && registration.PersonAlias.PersonId == CurrentPersonId.Value ) || ( registration.CreatedByPersonAlias != null && registration.CreatedByPersonAlias.PersonId == CurrentPersonId.Value ) ) { RegistrationInstanceState = registration.RegistrationInstance; RegistrationState = new RegistrationInfo( registration, rockContext ); RegistrationState.PreviousPaymentTotal = registrationService.GetTotalPayments( registration.Id ); } else { ShowWarning( "Sorry", "You are not allowed to view or edit the selected registration since you are not the one who created the registration." ); return false; } // set the max number of steps in the progress bar numHowMany.Value = registration.Registrants.Count(); this.ProgressBarSteps = numHowMany.Value * FormCount + 2; // set group id if ( groupId.HasValue ) { GroupId = groupId; } else if ( !string.IsNullOrWhiteSpace( registrationSlug ) ) { var dateTime = RockDateTime.Now; var linkage = new EventItemOccurrenceGroupMapService( rockContext ) .Queryable().AsNoTracking() .Where( l => l.UrlSlug == registrationSlug && l.RegistrationInstance != null && l.RegistrationInstance.IsActive && l.RegistrationInstance.RegistrationTemplate != null && l.RegistrationInstance.RegistrationTemplate.IsActive && ( !l.RegistrationInstance.StartDateTime.HasValue || l.RegistrationInstance.StartDateTime <= dateTime ) && ( !l.RegistrationInstance.EndDateTime.HasValue || l.RegistrationInstance.EndDateTime > dateTime ) ) .FirstOrDefault(); if ( linkage != null ) { GroupId = linkage.GroupId; } } } // A registration slug was specified if ( RegistrationState == null && !string.IsNullOrWhiteSpace( registrationSlug ) ) { var dateTime = RockDateTime.Now; var linkage = new EventItemOccurrenceGroupMapService( rockContext ) .Queryable( "RegistrationInstance.Account,RegistrationInstance.RegistrationTemplate.Fees,RegistrationInstance.RegistrationTemplate.Discounts,RegistrationInstance.RegistrationTemplate.Forms.Fields.Attribute,RegistrationInstance.RegistrationTemplate.FinancialGateway" ) .Where( l => l.UrlSlug == registrationSlug && l.RegistrationInstance != null && l.RegistrationInstance.IsActive && l.RegistrationInstance.RegistrationTemplate != null && l.RegistrationInstance.RegistrationTemplate.IsActive && ( !l.RegistrationInstance.StartDateTime.HasValue || l.RegistrationInstance.StartDateTime <= dateTime ) && ( !l.RegistrationInstance.EndDateTime.HasValue || l.RegistrationInstance.EndDateTime > dateTime ) ) .FirstOrDefault(); if ( linkage != null ) { RegistrationInstanceState = linkage.RegistrationInstance; GroupId = linkage.GroupId; RegistrationState = new RegistrationInfo( CurrentPerson ); } } // A group id and campus id were specified if ( RegistrationState == null && groupId.HasValue && campusId.HasValue ) { var dateTime = RockDateTime.Now; var linkage = new EventItemOccurrenceGroupMapService( rockContext ) .Queryable( "RegistrationInstance.Account,RegistrationInstance.RegistrationTemplate.Fees,RegistrationInstance.RegistrationTemplate.Discounts,RegistrationInstance.RegistrationTemplate.Forms.Fields.Attribute,RegistrationInstance.RegistrationTemplate.FinancialGateway" ) .Where( l => l.GroupId == groupId && l.EventItemOccurrence != null && l.EventItemOccurrence.CampusId == campusId && l.RegistrationInstance != null && l.RegistrationInstance.IsActive && l.RegistrationInstance.RegistrationTemplate != null && l.RegistrationInstance.RegistrationTemplate.IsActive && ( !l.RegistrationInstance.StartDateTime.HasValue || l.RegistrationInstance.StartDateTime <= dateTime ) && ( !l.RegistrationInstance.EndDateTime.HasValue || l.RegistrationInstance.EndDateTime > dateTime ) ) .FirstOrDefault(); CampusId = campusId; if ( linkage != null ) { RegistrationInstanceState = linkage.RegistrationInstance; GroupId = linkage.GroupId; RegistrationState = new RegistrationInfo( CurrentPerson ); } } // A registration instance id was specified if ( RegistrationState == null && registrationInstanceId.HasValue ) { var dateTime = RockDateTime.Now; RegistrationInstanceState = new RegistrationInstanceService( rockContext ) .Queryable( "Account,RegistrationTemplate.Fees,RegistrationTemplate.Discounts,RegistrationTemplate.Forms.Fields.Attribute,RegistrationTemplate.FinancialGateway" ) .Where( r => r.Id == registrationInstanceId.Value && r.IsActive && r.RegistrationTemplate != null && r.RegistrationTemplate.IsActive && ( !r.StartDateTime.HasValue || r.StartDateTime <= dateTime ) && ( !r.EndDateTime.HasValue || r.EndDateTime > dateTime ) ) .FirstOrDefault(); if ( RegistrationInstanceState != null ) { RegistrationState = new RegistrationInfo( CurrentPerson ); } } // If registration instance id and event occurrence were specified, but a group (linkage) hasn't been loaded, find the first group for the event occurrence if ( RegistrationInstanceState != null && eventOccurrenceId.HasValue && !groupId.HasValue ) { var eventItemOccurrence = new EventItemOccurrenceService( rockContext ) .Queryable() .Where( o => o.Id == eventOccurrenceId.Value ) .FirstOrDefault(); if ( eventItemOccurrence != null ) { CampusId = eventItemOccurrence.CampusId; var linkage = eventItemOccurrence.Linkages .Where( l => l.RegistrationInstanceId == RegistrationInstanceState.Id ) .FirstOrDefault(); if ( linkage != null ) { GroupId = linkage.GroupId; } } } if ( RegistrationState != null && RegistrationState.FamilyGuid == Guid.Empty && RegistrationTemplate != null && RegistrationTemplate.RegistrantsSameFamily != RegistrantsSameFamily.Ask ) { RegistrationState.FamilyGuid = Guid.NewGuid(); } if ( RegistrationState != null && !RegistrationState.Registrants.Any() ) { SetRegistrantState( 1 ); } if ( RegistrationTemplate != null && RegistrationTemplate.FinancialGateway != null ) { var threeStepGateway = RegistrationTemplate.FinancialGateway.GetGatewayComponent() as ThreeStepGatewayComponent; Using3StepGateway = threeStepGateway != null; if ( Using3StepGateway ) { Step2IFrameUrl = ResolveRockUrl( threeStepGateway.Step2FormUrl ); } } return true; }
/// <summary> /// Shows the view. /// </summary> /// <param name="groupId">The group identifier.</param> protected void ShowView(int groupId) { pnlView.Visible = true; hfGroupId.Value = groupId.ToString(); var rockContext = new RockContext(); var group = new GroupService(rockContext).Get(groupId); if (group == null) { pnlView.Visible = false; return; } group.LoadAttributes(rockContext); var opportunityType = DefinedValueCache.Get(group.GetAttributeValue("OpportunityType").AsGuid()); if (this.GetAttributeValue("SetPageTitletoOpportunityTitle").AsBoolean()) { RockPage.Title = group.GetAttributeValue("OpportunityTitle"); RockPage.BrowserTitle = group.GetAttributeValue("OpportunityTitle"); RockPage.Header.Title = group.GetAttributeValue("OpportunityTitle"); } var mergeFields = LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson, new CommonMergeFieldsOptions { GetLegacyGlobalMergeFields = false }); mergeFields.Add("Block", this.BlockCache); mergeFields.Add("Group", group); // Left Sidebar var photoGuid = group.GetAttributeValue("OpportunityPhoto").AsGuidOrNull(); imgOpportunityPhoto.Visible = photoGuid.HasValue; imgOpportunityPhoto.ImageUrl = string.Format("~/GetImage.ashx?Guid={0}", photoGuid); var groupMembers = group.Members.ToList(); foreach (var gm in groupMembers) { gm.LoadAttributes(rockContext); } // only show the 'Donate to a Participant' button if there are participants that are taking contribution requests btnDonateToParticipant.Visible = groupMembers.Where(a => !a.GetAttributeValue("DisablePublicContributionRequests").AsBoolean()).Any(); if (!string.IsNullOrWhiteSpace(opportunityType.GetAttributeValue("core_DonateButtonText"))) { btnDonateToParticipant.Text = opportunityType.GetAttributeValue("core_DonateButtonText"); } RegistrationInstance registrationInstance = null; var registrationInstanceId = group.GetAttributeValue("RegistrationInstance").AsIntegerOrNull(); if (registrationInstanceId.HasValue) { registrationInstance = new RegistrationInstanceService(rockContext).Get(registrationInstanceId.Value); } mergeFields.Add("RegistrationPage", LinkedPageRoute("RegistrationPage")); if (registrationInstance != null) { mergeFields.Add("RegistrationInstance", registrationInstance); mergeFields.Add("RegistrationInstanceLinkages", registrationInstance.Linkages); // populate merge fields for Registration Counts var maxRegistrantCount = 0; var currentRegistrationCount = 0; if (registrationInstance.MaxAttendees != 0) { maxRegistrantCount = registrationInstance.MaxAttendees; } currentRegistrationCount = new RegistrationRegistrantService(rockContext).Queryable().AsNoTracking() .Where(r => r.Registration.RegistrationInstanceId == registrationInstance.Id && r.OnWaitList == false) .Count(); mergeFields.Add("CurrentRegistrationCount", currentRegistrationCount); if (maxRegistrantCount != 0) { mergeFields.Add("MaxRegistrantCount", maxRegistrantCount); mergeFields.Add("RegistrationSpotsAvailable", maxRegistrantCount - currentRegistrationCount); } } string sidebarLavaTemplate = this.GetAttributeValue("SidebarLavaTemplate"); lSidebarHtml.Text = sidebarLavaTemplate.ResolveMergeFields(mergeFields); SetActiveTab("Details"); // Top Main string summaryLavaTemplate = this.GetAttributeValue("SummaryLavaTemplate"); lMainTopContentHtml.Text = summaryLavaTemplate.ResolveMergeFields(mergeFields); // only show the leader toolbox link of the currentperson has a leader role in the group btnLeaderToolbox.Visible = group.Members.Any(a => a.PersonId == this.CurrentPersonId && a.GroupRole.IsLeader); //// Participant Actions // only show if the current person is a group member var groupMember = group.Members.FirstOrDefault(a => a.PersonId == this.CurrentPersonId); if (groupMember != null) { hfGroupMemberId.Value = groupMember.Id.ToString(); pnlParticipantActions.Visible = true; } else { hfGroupMemberId.Value = null; pnlParticipantActions.Visible = false; } mergeFields.Add("GroupMember", groupMember); // Progress if (groupMember != null && pnlParticipantActions.Visible) { var entityTypeIdGroupMember = EntityTypeCache.GetId <Rock.Model.GroupMember>(); var contributionTotal = new FinancialTransactionDetailService(rockContext).Queryable() .Where(d => d.EntityTypeId == entityTypeIdGroupMember && d.EntityId == groupMember.Id) .Sum(a => (decimal?)a.Amount) ?? 0.00M; var individualFundraisingGoal = groupMember.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull(); if (!individualFundraisingGoal.HasValue) { individualFundraisingGoal = group.GetAttributeValue("IndividualFundraisingGoal").AsDecimalOrNull(); } var amountLeft = individualFundraisingGoal - contributionTotal; var percentMet = individualFundraisingGoal > 0 ? contributionTotal * 100 / individualFundraisingGoal : 100; mergeFields.Add("AmountLeft", amountLeft); mergeFields.Add("PercentMet", percentMet); var queryParams = new Dictionary <string, string>(); queryParams.Add("GroupId", hfGroupId.Value); queryParams.Add("GroupMemberId", hfGroupMemberId.Value); mergeFields.Add("MakeDonationUrl", LinkedPageUrl("DonationPage", queryParams)); mergeFields.Add("ParticipantPageUrl", LinkedPageUrl("ParticipantPage", queryParams)); string makeDonationButtonText = null; if (groupMember.PersonId == this.CurrentPersonId) { makeDonationButtonText = "Make Payment"; } else { makeDonationButtonText = string.Format("Contribute to {0} {1}", RockFilters.Possessive(groupMember.Person.NickName), opportunityType); } mergeFields.Add("MakeDonationButtonText", makeDonationButtonText); var participantLavaTemplate = this.GetAttributeValue("ParticipantLavaTemplate"); lParticipantActionsHtml.Text = participantLavaTemplate.ResolveMergeFields(mergeFields); } // Tab:Details lDetailsHtml.Text = group.GetAttributeValue("OpportunityDetails"); btnDetailsTab.Text = string.Format("{0} Details", opportunityType); // Tab:Updates liUpdatesTab.Visible = false; var updatesContentChannelGuid = group.GetAttributeValue("UpdateContentChannel").AsGuidOrNull(); if (updatesContentChannelGuid.HasValue) { var contentChannel = new ContentChannelService(rockContext).Get(updatesContentChannelGuid.Value); if (contentChannel != null) { liUpdatesTab.Visible = true; string updatesLavaTemplate = this.GetAttributeValue("UpdatesLavaTemplate"); var contentChannelItems = new ContentChannelItemService(rockContext).Queryable().Where(a => a.ContentChannelId == contentChannel.Id).AsNoTracking().ToList(); mergeFields.Add("ContentChannelItems", contentChannelItems); lUpdatesContentItemsHtml.Text = updatesLavaTemplate.ResolveMergeFields(mergeFields); btnUpdatesTab.Text = string.Format("{0} Updates ({1})", opportunityType, contentChannelItems.Count()); } } // Tab:Comments var noteType = NoteTypeCache.Get(this.GetAttributeValue("NoteType").AsGuid()); if (noteType != null) { notesCommentsTimeline.NoteOptions.SetNoteTypes(new List <NoteTypeCache> { noteType }); } notesCommentsTimeline.NoteOptions.EntityId = groupId; // show the Add button on comments for any logged in person notesCommentsTimeline.AddAllowed = true; var enableCommenting = group.GetAttributeValue("EnableCommenting").AsBoolean(); btnCommentsTab.Text = string.Format("Comments ({0})", notesCommentsTimeline.NoteCount); if (CurrentPerson == null) { notesCommentsTimeline.Visible = enableCommenting && (notesCommentsTimeline.NoteCount > 0); lNoLoginNoCommentsYet.Visible = notesCommentsTimeline.NoteCount == 0; liCommentsTab.Visible = enableCommenting; btnLoginToComment.Visible = enableCommenting; } else { lNoLoginNoCommentsYet.Visible = false; notesCommentsTimeline.Visible = enableCommenting; liCommentsTab.Visible = enableCommenting; btnLoginToComment.Visible = false; } // if btnDetailsTab is the only visible tab, hide the tab since there is nothing else to tab to if (!liCommentsTab.Visible && !liUpdatesTab.Visible) { tlTabList.Visible = false; } }
private void LoadState() { int? registrantId = PageParameter( "RegistrantId" ).AsIntegerOrNull(); int? registrationId = PageParameter( "RegistrationId" ).AsIntegerOrNull(); if ( RegistrantState == null ) { var rockContext = new RockContext(); RegistrationRegistrant registrant = null; if ( registrantId.HasValue && registrantId.Value != 0 ) { registrant = new RegistrationRegistrantService( rockContext ) .Queryable( "Registration.RegistrationInstance.RegistrationTemplate.Forms.Fields,Registration.RegistrationInstance.RegistrationTemplate.Fees,PersonAlias.Person,Fees" ).AsNoTracking() .Where( r => r.Id == registrantId.Value ) .FirstOrDefault(); if ( registrant != null && registrant.Registration != null && registrant.Registration.RegistrationInstance != null && registrant.Registration.RegistrationInstance.RegistrationTemplate != null ) { RegistrantState = new RegistrantInfo( registrant, rockContext ); TemplateState = registrant.Registration.RegistrationInstance.RegistrationTemplate; RegistrationInstanceId = registrant.Registration.RegistrationInstanceId; lWizardTemplateName.Text = registrant.Registration.RegistrationInstance.RegistrationTemplate.Name; lWizardInstanceName.Text = registrant.Registration.RegistrationInstance.Name; lWizardRegistrationName.Text = registrant.Registration.ToString(); lWizardRegistrantName.Text = registrant.ToString(); } } if ( TemplateState == null && registrationId.HasValue && registrationId.Value != 0 ) { var registration = new RegistrationService( rockContext ) .Queryable( "RegistrationInstance.RegistrationTemplate.Forms.Fields,RegistrationInstance.RegistrationTemplate.Fees" ).AsNoTracking() .Where( r => r.Id == registrationId.Value ) .FirstOrDefault(); if ( registration != null && registration.RegistrationInstance != null && registration.RegistrationInstance.RegistrationTemplate != null ) { TemplateState = registration.RegistrationInstance.RegistrationTemplate; RegistrationInstanceId = registration.RegistrationInstanceId; lWizardTemplateName.Text = registration.RegistrationInstance.RegistrationTemplate.Name; lWizardInstanceName.Text = registration.RegistrationInstance.Name; lWizardRegistrationName.Text = registration.ToString(); lWizardRegistrantName.Text = "New Registrant"; } } if ( TemplateState != null && RegistrantState == null ) { RegistrantState = new RegistrantInfo(); RegistrantState.RegistrationId = registrationId ?? 0; if ( TemplateState.SetCostOnInstance.HasValue && TemplateState.SetCostOnInstance.Value ) { var instance = new RegistrationInstanceService( rockContext ).Get( RegistrationInstanceId ); if ( instance != null ) { RegistrantState.Cost = instance.Cost ?? 0.0m; } } else { RegistrantState.Cost = TemplateState.Cost; } } if ( registrant != null && registrant.PersonAlias != null && registrant.PersonAlias.Person != null ) { ppPerson.SetValue( registrant.PersonAlias.Person ); } else { ppPerson.SetValue( null ); } if ( RegistrantState != null ) { cbCost.Text = RegistrantState.Cost.ToString( "N2" ); } } }
/// <summary> /// Binds the registrations grid. /// </summary> private void BindRegistrationsGrid() { int? instanceId = hfRegistrationInstanceId.Value.AsIntegerOrNull(); if ( instanceId.HasValue ) { using ( var rockContext = new RockContext() ) { var registrationEntityType = EntityTypeCache.Read( typeof( Rock.Model.Registration ) ); var instance = new RegistrationInstanceService( rockContext ).Get( instanceId.Value ); _instanceHasCost = instance != null && instance.RegistrationTemplate.Cost > 0.0m; var qry = new RegistrationService( rockContext ) .Queryable( "PersonAlias.Person,Registrants.PersonAlias.Person,Registrants.Fees.RegistrationTemplateFee" ) .AsNoTracking() .Where( r => r.RegistrationInstanceId == instanceId.Value ); if ( drpRegistrationDateRange.LowerValue.HasValue ) { qry = qry.Where( r => r.CreatedDateTime.HasValue && r.CreatedDateTime.Value >= drpRegistrationDateRange.LowerValue.Value ); } if ( drpRegistrationDateRange.UpperValue.HasValue ) { qry = qry.Where( r => r.CreatedDateTime.HasValue && r.CreatedDateTime.Value <= drpRegistrationDateRange.UpperValue.Value ); } if ( !string.IsNullOrWhiteSpace( tbRegistrationRegisteredByFirstName.Text ) ) { string pfname = tbRegistrationRegisteredByFirstName.Text; qry = qry.Where( r => r.FirstName.StartsWith( pfname ) || r.PersonAlias.Person.NickName.StartsWith( pfname ) || r.PersonAlias.Person.FirstName.StartsWith( pfname ) ); } if ( !string.IsNullOrWhiteSpace( tbRegistrationRegisteredByLastName.Text ) ) { string plname = tbRegistrationRegisteredByLastName.Text; qry = qry.Where( r => r.LastName.StartsWith( plname ) || r.PersonAlias.Person.LastName.StartsWith( plname ) ); } if ( !string.IsNullOrWhiteSpace( tbRegistrationRegistrantFirstName.Text ) ) { string rfname = tbRegistrationRegistrantFirstName.Text; qry = qry.Where( r => r.Registrants.Any( p => p.PersonAlias.Person.NickName.StartsWith( rfname ) || p.PersonAlias.Person.FirstName.StartsWith( rfname ) ) ); } if ( !string.IsNullOrWhiteSpace( tbRegistrationRegistrantLastName.Text ) ) { string rlname = tbRegistrationRegistrantLastName.Text; qry = qry.Where( r => r.Registrants.Any( p => p.PersonAlias.Person.LastName.StartsWith( rlname ) ) ); } // If filtering on payment status, need to do some sub-querying... if ( ddlRegistrationPaymentStatus.SelectedValue != "" && registrationEntityType != null ) { // Get all the registrant costs var rCosts = new Dictionary<int, decimal>(); qry .Select( r => new { RegistrationId = r.Id, Costs = r.Registrants.Sum( p => p.Cost ), Fees = r.Registrants.SelectMany( p => p.Fees ).Sum( f => f.Cost ) } ).ToList() .ForEach( c => rCosts.AddOrReplace( c.RegistrationId, c.Costs + c.Fees ) ); var rPayments = new Dictionary<int, decimal>(); new FinancialTransactionDetailService( rockContext ) .Queryable().AsNoTracking() .Where( d => d.EntityTypeId.HasValue && d.EntityId.HasValue && d.EntityTypeId.Value == registrationEntityType.Id && rCosts.Keys.Contains( d.EntityId.Value ) ) .Select( d => new { RegistrationId = d.EntityId.Value, Payment = d.Amount } ) .ToList() .GroupBy( d => d.RegistrationId ) .Select( d => new { RegistrationId = d.Key, Payments = d.Sum( p => p.Payment ) } ) .ToList() .ForEach( p => rPayments.AddOrReplace( p.RegistrationId, p.Payments ) ); var rPmtSummary = rCosts .Join( rPayments, c => c.Key, p => p.Key, ( c, p ) => new { RegistrationId = c.Key, Costs = c.Value, Payments = p.Value } ) .ToList(); var ids = new List<int>(); if ( ddlRegistrationPaymentStatus.SelectedValue == "Paid in Full" ) { ids = rPmtSummary .Where( r => r.Costs <= r.Payments ) .Select( r => r.RegistrationId ) .ToList(); } else { ids = rPmtSummary .Where( r => r.Costs > r.Payments ) .Select( r => r.RegistrationId ) .ToList(); } qry = qry.Where( r => ids.Contains( r.Id ) ); } IOrderedQueryable<Registration> orderedQry = null; SortProperty sortProperty = gRegistrations.SortProperty; if ( sortProperty != null ) { orderedQry = qry.Sort( sortProperty ); } else { orderedQry = qry.OrderByDescending( r => r.CreatedDateTime ); } gRegistrations.SetLinqDataSource( orderedQry ); // Get all the payments for any registrations being displayed on the current page. // This is used in the RowDataBound event but queried now so that each row does // not have to query for the data. var currentPageRegistrations = gRegistrations.DataSource as List<Registration>; if ( currentPageRegistrations != null && registrationEntityType != null ) { var registrationIds = currentPageRegistrations .Select( r => r.Id ) .ToList(); RegistrationPayments = new FinancialTransactionDetailService( rockContext ) .Queryable().AsNoTracking() .Where( d => d.EntityTypeId.HasValue && d.EntityId.HasValue && d.EntityTypeId.Value == registrationEntityType.Id && registrationIds.Contains( d.EntityId.Value ) ) .ToList(); } gRegistrations.DataBind(); } } }
private void LoadState() { if ( !RegistrationInstanceId.HasValue ) { Title = "New Registration"; RegistrationInstanceId = PageParameter( "RegistrationInstanceId" ).AsIntegerOrNull(); RegistrationId = PageParameter( "RegistrationId" ).AsIntegerOrNull(); var rockContext = new RockContext(); if ( RegistrationId.HasValue ) { Registration = GetRegistration( RegistrationId.Value, rockContext ); if ( Registration != null ) { Title = Registration.ToString(); RegistrationInstanceId = Registration.RegistrationInstanceId; RegistrationTemplateState = Registration.RegistrationInstance.RegistrationTemplate; lWizardTemplateName.Text = Registration.RegistrationInstance.RegistrationTemplate.Name; lWizardInstanceName.Text = Registration.RegistrationInstance.Name; lWizardRegistrationName.Text = Registration.ToString(); } } EditAllowed = IsUserAuthorized( Authorization.EDIT ) || ( Registration != null && Registration.IsAuthorized( Authorization.EDIT, CurrentPerson ) ); if ( RegistrationTemplateState == null && RegistrationInstanceId.HasValue ) { var registrationInstance = new RegistrationInstanceService( rockContext ) .Queryable( "RegistrationTemplate" ).AsNoTracking() .Where( i => i.Id == RegistrationInstanceId.Value ) .FirstOrDefault(); if ( registrationInstance != null ) { lWizardTemplateName.Text = registrationInstance.RegistrationTemplate.Name; lWizardInstanceName.Text = registrationInstance.Name; lWizardRegistrationName.Text = "New Registration"; RegistrationTemplateState = registrationInstance.RegistrationTemplate; EditAllowed = EditAllowed || registrationInstance.RegistrationTemplate.IsAuthorized( Authorization.EDIT, CurrentPerson ); } } } }
/// <summary> /// Handles the Click event of the btnDelete 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 btnDelete_Click( object sender, EventArgs e ) { using ( var rockContext = new RockContext() ) { var service = new RegistrationInstanceService( rockContext ); var registrationInstance = service.Get( hfRegistrationInstanceId.Value.AsInteger() ); if ( registrationInstance != null ) { int registrationTemplateId = registrationInstance.RegistrationTemplateId; if ( !registrationInstance.IsAuthorized( Authorization.ADMINISTRATE, this.CurrentPerson ) ) { mdDeleteWarning.Show( "You are not authorized to delete this registration instance.", ModalAlertType.Information ); return; } rockContext.WrapTransaction( () => { new RegistrationService( rockContext ).DeleteRange( registrationInstance.Registrations ); service.Delete( registrationInstance ); rockContext.SaveChanges(); } ); var qryParams = new Dictionary<string, string> { { "RegistrationTemplateId", registrationTemplateId.ToString() } }; NavigateToParentPage( qryParams ); } } }
/// <summary> /// Gets the expression. /// </summary> /// <param name="entityType">Type of the entity.</param> /// <param name="serviceInstance">The service instance.</param> /// <param name="parameterExpression">The parameter expression.</param> /// <param name="selection">The selection.</param> /// <returns></returns> public override Expression GetExpression( Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection ) { string[] selectionValues = selection.Split( '|' ); if ( selectionValues.Length >= 1 ) { List<Guid> registrationTemplateGuids = selectionValues[0].Split( ',' ).AsGuidList(); var registrationInstanceService = new RegistrationInstanceService( (RockContext)serviceInstance.Context ); var registrationInstanceIds = registrationInstanceService.Queryable().Where( ri => registrationTemplateGuids.Contains( ri.RegistrationTemplate.Guid ) ).Select( ri => ri.Id ).Distinct().ToList(); RegistrationRegistrantService registrationRegistrantService = new RegistrationRegistrantService( (RockContext)serviceInstance.Context ); bool includeInactiveRegistrationInstances = false; if ( selectionValues.Length >= 2 ) { includeInactiveRegistrationInstances = selectionValues[1].AsBooleanOrNull() ?? true; ; } else { // if options where saved before this option was added, set to false, even though it would have included inactive before includeInactiveRegistrationInstances = false; } var registrationRegistrantServiceQry = registrationRegistrantService.Queryable(); if ( registrationTemplateGuids.Count > 0 ) { registrationRegistrantServiceQry = registrationRegistrantServiceQry.Where( xx => registrationInstanceIds.Contains( xx.Registration.RegistrationInstanceId ) ); } if ( selectionValues.Length >= 3 ) { string slidingDelimitedValues = selectionValues[2].Replace( ',', '|' ); DateRange dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( slidingDelimitedValues ); if ( dateRange.Start.HasValue ) { registrationRegistrantServiceQry = registrationRegistrantServiceQry.Where( xx => xx.CreatedDateTime >= dateRange.Start.Value ); } if ( dateRange.End.HasValue ) { registrationRegistrantServiceQry = registrationRegistrantServiceQry.Where( xx => xx.CreatedDateTime < dateRange.End.Value ); } } var qry = new PersonService( (RockContext)serviceInstance.Context ).Queryable() .Where( p => registrationRegistrantServiceQry.Any( xx => xx.PersonAlias.PersonId == p.Id ) ); Expression extractedFilterExpression = FilterExpressionExtractor.Extract<Rock.Model.Person>( qry, parameterExpression, "p" ); return extractedFilterExpression; } return null; }
/// <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 ) { using ( var rockContext = new RockContext() ) { var service = new RegistrationInstanceService( rockContext ); RegistrationInstance instance = null; int? RegistrationInstanceId = hfRegistrationInstanceId.Value.AsIntegerOrNull(); if ( RegistrationInstanceId.HasValue ) { instance = service.Get( RegistrationInstanceId.Value ); } if ( instance == null ) { instance = new RegistrationInstance(); instance.RegistrationTemplateId = PageParameter( "RegistrationTemplateId" ).AsInteger(); service.Add( instance ); } rieDetails.GetValue( instance ); if ( !Page.IsValid ) { return; } rockContext.SaveChanges(); // Reload instance and show readonly view instance = service.Get( instance.Id ); ShowReadonlyDetails( instance ); } }
/// <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 ) { EventItemOccurrence eventItemOccurrence = null; using ( var rockContext = new RockContext() ) { bool newItem = false; var eventItemOccurrenceService = new EventItemOccurrenceService( rockContext ); var eventItemOccurrenceGroupMapService = new EventItemOccurrenceGroupMapService( rockContext ); var registrationInstanceService = new RegistrationInstanceService( rockContext ); var scheduleService = new ScheduleService( rockContext ); int eventItemOccurrenceId = hfEventItemOccurrenceId.ValueAsInt(); if ( eventItemOccurrenceId != 0 ) { eventItemOccurrence = eventItemOccurrenceService .Queryable( "Linkages" ) .Where( i => i.Id == eventItemOccurrenceId ) .FirstOrDefault(); } if ( eventItemOccurrence == null ) { newItem = true; eventItemOccurrence = new EventItemOccurrence{ EventItemId = PageParameter("EventItemId").AsInteger() }; eventItemOccurrenceService.Add( eventItemOccurrence ); } int? newCampusId = ddlCampus.SelectedValueAsInt(); if ( eventItemOccurrence.CampusId != newCampusId ) { eventItemOccurrence.CampusId = newCampusId; if ( newCampusId.HasValue ) { var campus = new CampusService( rockContext ).Get( newCampusId.Value ); eventItemOccurrence.Campus = campus; } else { eventItemOccurrence.Campus = null; } } eventItemOccurrence.Location = tbLocation.Text; string iCalendarContent = sbSchedule.iCalendarContent; var calEvent = ScheduleICalHelper.GetCalenderEvent( iCalendarContent ); if ( calEvent != null && calEvent.DTStart != null ) { if ( eventItemOccurrence.Schedule == null ) { eventItemOccurrence.Schedule = new Schedule(); } eventItemOccurrence.Schedule.iCalendarContent = iCalendarContent; } else { if ( eventItemOccurrence.ScheduleId.HasValue ) { var oldSchedule = scheduleService.Get( eventItemOccurrence.ScheduleId.Value ); if ( oldSchedule != null ) { scheduleService.Delete( oldSchedule ); } } } if ( !eventItemOccurrence.ContactPersonAliasId.Equals( ppContact.PersonAliasId )) { PersonAlias personAlias = null; eventItemOccurrence.ContactPersonAliasId = ppContact.PersonAliasId; if ( eventItemOccurrence.ContactPersonAliasId.HasValue ) { personAlias = new PersonAliasService( rockContext ).Get( eventItemOccurrence.ContactPersonAliasId.Value ); } if ( personAlias != null ) { eventItemOccurrence.ContactPersonAlias = personAlias; } } eventItemOccurrence.ContactPhone = PhoneNumber.FormattedNumber( PhoneNumber.DefaultCountryCode(), pnPhone.Number ); eventItemOccurrence.ContactEmail = tbEmail.Text; eventItemOccurrence.Note = htmlOccurrenceNote.Text; // Remove any linkage no longer in UI Guid uiLinkageGuid = LinkageState != null ? LinkageState.Guid : Guid.Empty; foreach( var linkage in eventItemOccurrence.Linkages.Where( l => !l.Guid.Equals(uiLinkageGuid)).ToList()) { eventItemOccurrence.Linkages.Remove( linkage ); eventItemOccurrenceGroupMapService.Delete( linkage ); } // Add/Update linkage in UI if ( !uiLinkageGuid.Equals( Guid.Empty )) { var linkage = eventItemOccurrence.Linkages.Where( l => l.Guid.Equals( uiLinkageGuid)).FirstOrDefault(); if ( linkage == null ) { linkage = new EventItemOccurrenceGroupMap(); eventItemOccurrence.Linkages.Add( linkage ); } linkage.CopyPropertiesFrom( LinkageState ); // update registration instance if ( LinkageState.RegistrationInstance != null ) { if ( LinkageState.RegistrationInstance.Id != 0 ) { linkage.RegistrationInstance = registrationInstanceService.Get( LinkageState.RegistrationInstance.Id ); } if ( linkage.RegistrationInstance == null ) { var registrationInstance = new RegistrationInstance(); registrationInstanceService.Add( registrationInstance ); linkage.RegistrationInstance = registrationInstance; } linkage.RegistrationInstance.CopyPropertiesFrom( LinkageState.RegistrationInstance ); } } if ( !Page.IsValid ) { return; } if ( !eventItemOccurrence.IsValid ) { // Controls will render the error messages return; } rockContext.SaveChanges(); var qryParams = new Dictionary<string, string>(); qryParams.Add( "EventCalendarId", PageParameter( "EventCalendarId" ) ); qryParams.Add( "EventItemId", PageParameter( "EventItemId" ) ); if ( newItem ) { NavigateToParentPage( qryParams ); } else { qryParams.Add( "EventItemOccurrenceId", eventItemOccurrence.Id.ToString() ); NavigateToPage( RockPage.Guid, qryParams ); } } }
private void BindOtherInstances() { int? currentValue = ddlNewRegistrationInstance.SelectedValueAsInt(); // list other registration instances using ( var rockContext = new RockContext() ) { var otherRegistrationInstances = new RegistrationInstanceService( rockContext ).Queryable() .Where( i => i.RegistrationTemplateId == Registration.RegistrationInstance.RegistrationTemplateId && i.Id != Registration.RegistrationInstanceId ); if ( !cbShowAll.Checked ) { otherRegistrationInstances = otherRegistrationInstances .Where( i => i.IsActive == true && ( i.EndDateTime >= RockDateTime.Now || i.EndDateTime == null ) ); } var instances = otherRegistrationInstances .Select( i => new { Value = i.Id, Text = i.Name } ) .ToList(); ddlNewRegistrationInstance.DataSource = instances; ddlNewRegistrationInstance.DataBind(); ddlNewRegistrationInstance.Items.Insert( 0, new ListItem( String.Empty, String.Empty ) ); ddlNewRegistrationInstance.SetValue( currentValue ); } }
/// <summary> /// Handles the SaveClick event of the dlgExistingLinkage 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 dlgExistingLinkage_SaveClick( object sender, EventArgs e ) { int? registrationInstanceId = ddlExistingLinkageInstance.SelectedValueAsInt(); if ( registrationInstanceId.HasValue ) { var rockContext = new RockContext(); var registrationInstance = new RegistrationInstanceService( rockContext ).Get( registrationInstanceId.Value ); if ( registrationInstance != null ) { LinkageState.RegistrationInstanceId = registrationInstance.Id; LinkageState.RegistrationInstance = registrationInstance; } int? groupId = gpExistingLinkageGroup.SelectedValueAsInt(); if ( groupId.HasValue ) { var group = new GroupService( rockContext ).Get( groupId.Value ); if ( group != null ) { LinkageState.GroupId = group.Id; LinkageState.Group = group; } } LinkageState.PublicName = tbExistingLinkagePublicName.Text; LinkageState.UrlSlug = tbExistingLinkageUrlSlug.Text; // Set the Guid now (otherwise it will not be valid ) bool isNew = LinkageState.Guid == Guid.Empty; if ( isNew ) { LinkageState.Guid = Guid.NewGuid(); } if ( !LinkageState.IsValid ) { // If validation failed and this is new, reset the guid back to empty if ( isNew ) { LinkageState.Guid = Guid.Empty; } return; } DisplayRegistration(); HideDialog(); } }
/// <summary> /// Handles the CheckedChanged event of the tglEmailBodyView 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 tglEmailBodyView_CheckedChanged( object sender, EventArgs e ) { if ( tglEmailBodyView.Checked ) { ceEmailMessage.Visible = false; ifEmailPreview.Visible = true; // reload preview int? registrationInstanceId = PageParameter( "RegistrationInstanceId" ).AsIntegerOrNull(); if ( registrationInstanceId.HasValue ) { using ( RockContext rockContext = new RockContext() ) { RegistrationInstanceService registrationInstanceService = new RegistrationInstanceService( rockContext ); _registrationInstance = registrationInstanceService.Queryable( "RegistrationTemplate" ).AsNoTracking() .Where( r => r.Id == registrationInstanceId ).FirstOrDefault(); var registrationSample = _registrationInstance.Registrations.Where( r => r.BalanceDue > 0 ).FirstOrDefault(); if ( registrationSample != null ) { Dictionary<string, object> mergeObjects = new Dictionary<string, object>(); mergeObjects.Add( "Registration", registrationSample ); mergeObjects.Add( "RegistrationInstance", _registrationInstance ); ifEmailPreview.Attributes["srcdoc"] = ceEmailMessage.Text.ResolveMergeFields( mergeObjects ); } } } } else { ceEmailMessage.Visible = true; ifEmailPreview.Visible = false; } }
protected void ddlNewRegistrationInstance_SelectedIndexChanged( object sender, EventArgs e ) { ddlMoveGroup.Items.Clear(); int? instanceId = ddlNewRegistrationInstance.SelectedValueAsInt(); if ( instanceId.HasValue ) { using ( var rockContext = new RockContext() ) { var instance = new RegistrationInstanceService( rockContext ).Get( instanceId.Value ); if ( instance != null ) { var groups = instance.Linkages .Where( l => l.Group != null ) .Select( l => new { Value = l.Group.Id, Text = l.Group.Name } ) .ToList(); ddlMoveGroup.DataSource = groups; ddlMoveGroup.DataBind(); ddlMoveGroup.Items.Insert( 0, new ListItem( String.Empty, String.Empty ) ); } } } ddlMoveGroup.Visible = ddlMoveGroup.Items.Count > 0; }
/// <summary> /// Loads the outstanding balances. /// </summary> private void LoadOutstandingBalances() { using ( RockContext rockContext = new RockContext() ) { if ( _registrationInstance == null ) { int? registrationInstanceId = PageParameter( "RegistrationInstanceId" ).AsIntegerOrNull(); RegistrationInstanceService registrationInstanceService = new RegistrationInstanceService( rockContext ); _registrationInstance = registrationInstanceService.Queryable( "RegistrationTemplate" ).AsNoTracking() .Where( r => r.Id == registrationInstanceId ).FirstOrDefault(); } var outstandingBalances = _registrationInstance.Registrations.Where( r => r.BalanceDue > 0 ); var sortProperty = gRegistrations.SortProperty; if ( sortProperty != null ) { switch ( sortProperty.Property ) { case "BalanceDue": { if ( sortProperty.Direction == SortDirection.Ascending ) { outstandingBalances = outstandingBalances.OrderBy( b => b.BalanceDue ); } else { outstandingBalances = outstandingBalances.OrderByDescending( b => b.BalanceDue ); } break; } case "LastPaymentReminderDateTime": { if ( sortProperty.Direction == SortDirection.Ascending ) { outstandingBalances = outstandingBalances.OrderBy( b => b.LastPaymentReminderDateTime ); } else { outstandingBalances = outstandingBalances.OrderByDescending( b => b.LastPaymentReminderDateTime ); } break; } case "CreatedDateTime": { if ( sortProperty.Direction == SortDirection.Ascending ) { outstandingBalances = outstandingBalances.OrderBy( b => b.CreatedDateTime ); } else { outstandingBalances = outstandingBalances.OrderByDescending( b => b.CreatedDateTime ); } break; } case "Name": { if ( sortProperty.Direction == SortDirection.Ascending ) { outstandingBalances = outstandingBalances.OrderBy( b => b.LastName ).ThenBy(b=> b.FirstName); } else { outstandingBalances = outstandingBalances.OrderByDescending( b => b.LastName ).ThenBy( b => b.FirstName ); } break; } } } gRegistrations.DataSource = outstandingBalances; gRegistrations.DataBind(); } }
/// <summary> /// Handles the Click event of the DeleteInstance control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs" /> instance containing the event data.</param> protected void DeleteInstance_Click( object sender, Rock.Web.UI.Controls.RowEventArgs e ) { RockContext rockContext = new RockContext(); RegistrationInstanceService instanceService = new RegistrationInstanceService( rockContext ); RegistrationInstance instance = instanceService.Get( e.RowKeyId ); if ( instance != null ) { string errorMessage; if ( !instanceService.CanDelete( instance, out errorMessage ) ) { mdGridWarning.Show( errorMessage, ModalAlertType.Information ); return; } rockContext.WrapTransaction( () => { new RegistrationService( rockContext ).DeleteRange( instance.Registrations ); instanceService.Delete( instance ); rockContext.SaveChanges(); } ); } BindInstancesGrid(); }
/// <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 ); } 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.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 ( 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(); 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> /// Binds the group members grid. /// </summary> protected void BindInstancesGrid() { if ( _template != null ) { pnlInstances.Visible = true; lHeading.Text = string.Format( "{0} Instances", _template.Name ); var rockContext = new RockContext(); RegistrationInstanceService instanceService = new RegistrationInstanceService( rockContext ); var qry = instanceService.Queryable().AsNoTracking() .Where( i => i.RegistrationTemplateId == _template.Id ); // Date Range var drp = new DateRangePicker(); drp.DelimitedValues = rFilter.GetUserPreference( "Date Range" ); if ( drp.LowerValue.HasValue ) { qry = qry.Where( i => i.StartDateTime >= drp.LowerValue.Value ); } if ( drp.UpperValue.HasValue ) { DateTime upperDate = drp.UpperValue.Value.Date.AddDays( 1 ); qry = qry.Where( i => i.StartDateTime < upperDate ); } string statusFilter = rFilter.GetUserPreference( "Active Status" ); if ( !string.IsNullOrWhiteSpace(statusFilter)) { if ( statusFilter == "inactive") { qry = qry.Where( i => i.IsActive == false ); } else { qry = qry.Where( i => i.IsActive == true ); } } SortProperty sortProperty = gInstances.SortProperty; if ( sortProperty != null ) { qry = qry.Sort( sortProperty ); } else { qry = qry.OrderByDescending( a => a.StartDateTime ); } var instanceQry = qry.Select( i => new { i.Id, i.Guid, i.Name, i.StartDateTime, i.EndDateTime, i.IsActive, Details = string.Empty, Registrants = i.Registrations.SelectMany( r => r.Registrants ).Count() }); gInstances.SetLinqDataSource( instanceQry ); gInstances.DataBind(); } else { pnlInstances.Visible = false; } }
/// <summary> /// Sets the registration state /// </summary> private void SetRegistrationState() { string registrationSlug = PageParameter( REGISTRATION_SLUG_PARAM_NAME ); int? registrationInstanceId = PageParameter( REGISTRATION_INSTANCE_ID_PARAM_NAME ).AsIntegerOrNull(); int? registrationId = PageParameter( REGISTRATION_ID_PARAM_NAME ).AsIntegerOrNull(); int? groupId = PageParameter( REGISTRATION_GROUP_ID_PARAM_NAME ).AsIntegerOrNull(); int? campusId = PageParameter( REGISTRATION_CAMPUS_ID_PARAM_NAME ).AsIntegerOrNull(); // Not inside a "using" due to serialization needing context to still be active var rockContext = new RockContext(); // An existing registration id was specified if ( registrationId.HasValue ) { var registrationService = new RegistrationService( rockContext ); var registration = registrationService .Queryable( "Registrants.PersonAlias.Person,Registrants.GroupMember,RegistrationInstance.Account,RegistrationInstance.RegistrationTemplate.Fees,RegistrationInstance.RegistrationTemplate.Discounts,RegistrationInstance.RegistrationTemplate.Forms.Fields.Attribute,RegistrationInstance.RegistrationTemplate.FinancialGateway" ) .Where( r => r.Id == registrationId.Value ) .FirstOrDefault(); if ( registration != null ) { RegistrationInstanceState = registration.RegistrationInstance; RegistrationState = new RegistrationInfo( registration, rockContext ); RegistrationState.PreviousPaymentTotal = registrationService.GetTotalPayments( registration.Id ); } } // A registration slug was specified if ( RegistrationState == null && !string.IsNullOrWhiteSpace( registrationSlug ) ) { var dateTime = RockDateTime.Now; var linkage = new EventItemOccurrenceGroupMapService( rockContext ) .Queryable( "RegistrationInstance.Account,RegistrationInstance.RegistrationTemplate.Fees,RegistrationInstance.RegistrationTemplate.Discounts,RegistrationInstance.RegistrationTemplate.Forms.Fields.Attribute,RegistrationInstance.RegistrationTemplate.FinancialGateway" ) .Where( l => l.UrlSlug == registrationSlug && l.RegistrationInstance != null && l.RegistrationInstance.IsActive && l.RegistrationInstance.RegistrationTemplate != null && l.RegistrationInstance.RegistrationTemplate.IsActive && (!l.RegistrationInstance.StartDateTime.HasValue || l.RegistrationInstance.StartDateTime <= dateTime ) && (!l.RegistrationInstance.EndDateTime.HasValue || l.RegistrationInstance.EndDateTime > dateTime ) ) .FirstOrDefault(); if ( linkage != null ) { RegistrationInstanceState = linkage.RegistrationInstance; GroupId = linkage.GroupId; RegistrationState = new RegistrationInfo( CurrentPerson ); } } // A group id and campus id were specified if ( RegistrationState == null && groupId.HasValue && campusId.HasValue ) { var dateTime = RockDateTime.Now; var linkage = new EventItemOccurrenceGroupMapService( rockContext ) .Queryable( "RegistrationInstance.Account,RegistrationInstance.RegistrationTemplate.Fees,RegistrationInstance.RegistrationTemplate.Discounts,RegistrationInstance.RegistrationTemplate.Forms.Fields.Attribute,RegistrationInstance.RegistrationTemplate.FinancialGateway" ) .Where( l => l.GroupId == groupId && l.EventItemOccurrence != null && l.EventItemOccurrence.CampusId == campusId && l.RegistrationInstance != null && l.RegistrationInstance.IsActive && l.RegistrationInstance.RegistrationTemplate != null && l.RegistrationInstance.RegistrationTemplate.IsActive && ( !l.RegistrationInstance.StartDateTime.HasValue || l.RegistrationInstance.StartDateTime <= dateTime ) && ( !l.RegistrationInstance.EndDateTime.HasValue || l.RegistrationInstance.EndDateTime > dateTime ) ) .FirstOrDefault(); if ( linkage != null ) { RegistrationInstanceState = linkage.RegistrationInstance; GroupId = linkage.GroupId; RegistrationState = new RegistrationInfo( CurrentPerson ); } } // A registratio instance id was specified if ( RegistrationState == null && registrationInstanceId.HasValue ) { var dateTime = RockDateTime.Now; RegistrationInstanceState = new RegistrationInstanceService( rockContext ) .Queryable( "Account,RegistrationTemplate.Fees,RegistrationTemplate.Discounts,RegistrationTemplate.Forms.Fields.Attribute,RegistrationTemplate.FinancialGateway" ) .Where( r => r.Id == registrationInstanceId.Value && r.IsActive && r.RegistrationTemplate != null && r.RegistrationTemplate.IsActive && ( !r.StartDateTime.HasValue || r.StartDateTime <= dateTime ) && ( !r.EndDateTime.HasValue || r.EndDateTime > dateTime ) ) .FirstOrDefault(); if ( RegistrationInstanceState != null ) { RegistrationState = new RegistrationInfo( CurrentPerson ); } } if ( RegistrationState != null && !RegistrationState.Registrants.Any() ) { SetRegistrantState( 1 ); } }
/// <summary> /// Binds the registrations grid. /// </summary> private void BindRegistrationsGrid() { int? instanceId = hfRegistrationInstanceId.Value.AsIntegerOrNull(); if ( instanceId.HasValue ) { using ( var rockContext = new RockContext() ) { var registrationEntityType = EntityTypeCache.Read( typeof( Rock.Model.Registration ) ); var instance = new RegistrationInstanceService( rockContext ).Get( instanceId.Value ); decimal cost = instance.RegistrationTemplate.Cost; if ( instance.RegistrationTemplate.SetCostOnInstance ?? false ) { cost = instance.Cost ?? 0.0m; } _instanceHasCost = cost > 0.0m; var qry = new RegistrationService( rockContext ) .Queryable( "PersonAlias.Person,Registrants.PersonAlias.Person,Registrants.Fees.RegistrationTemplateFee" ) .AsNoTracking() .Where( r => r.RegistrationInstanceId == instanceId.Value && !r.IsTemporary ); if ( drpRegistrationDateRange.LowerValue.HasValue ) { qry = qry.Where( r => r.CreatedDateTime.HasValue && r.CreatedDateTime.Value >= drpRegistrationDateRange.LowerValue.Value ); } if ( drpRegistrationDateRange.UpperValue.HasValue ) { qry = qry.Where( r => r.CreatedDateTime.HasValue && r.CreatedDateTime.Value <= drpRegistrationDateRange.UpperValue.Value ); } if ( !string.IsNullOrWhiteSpace( tbRegistrationRegisteredByFirstName.Text ) ) { string pfname = tbRegistrationRegisteredByFirstName.Text; qry = qry.Where( r => r.FirstName.StartsWith( pfname ) || r.PersonAlias.Person.NickName.StartsWith( pfname ) || r.PersonAlias.Person.FirstName.StartsWith( pfname ) ); } if ( !string.IsNullOrWhiteSpace( tbRegistrationRegisteredByLastName.Text ) ) { string plname = tbRegistrationRegisteredByLastName.Text; qry = qry.Where( r => r.LastName.StartsWith( plname ) || r.PersonAlias.Person.LastName.StartsWith( plname ) ); } if ( !string.IsNullOrWhiteSpace( tbRegistrationRegistrantFirstName.Text ) ) { string rfname = tbRegistrationRegistrantFirstName.Text; qry = qry.Where( r => r.Registrants.Any( p => p.PersonAlias.Person.NickName.StartsWith( rfname ) || p.PersonAlias.Person.FirstName.StartsWith( rfname ) ) ); } if ( !string.IsNullOrWhiteSpace( tbRegistrationRegistrantLastName.Text ) ) { string rlname = tbRegistrationRegistrantLastName.Text; qry = qry.Where( r => r.Registrants.Any( p => p.PersonAlias.Person.LastName.StartsWith( rlname ) ) ); } // If filtering on payment status, need to do some sub-querying... if ( ddlRegistrationPaymentStatus.SelectedValue != "" && registrationEntityType != null ) { // Get all the registrant costs var rCosts = new Dictionary<int, decimal>(); qry.ToList() .Select( r => new { RegistrationId = r.Id, DiscountCosts = r.Registrants.Sum( p => (decimal?)( p.DiscountedCost( r.DiscountPercentage, r.DiscountAmount) ) ) ?? 0.0m, } ).ToList() .ForEach( c => rCosts.AddOrReplace( c.RegistrationId, c.DiscountCosts ) ); var rPayments = new Dictionary<int, decimal>(); new FinancialTransactionDetailService( rockContext ) .Queryable().AsNoTracking() .Where( d => d.EntityTypeId.HasValue && d.EntityId.HasValue && d.EntityTypeId.Value == registrationEntityType.Id && rCosts.Keys.Contains( d.EntityId.Value ) ) .Select( d => new { RegistrationId = d.EntityId.Value, Payment = d.Amount } ) .ToList() .GroupBy( d => d.RegistrationId ) .Select( d => new { RegistrationId = d.Key, Payments = d.Sum( p => p.Payment ) } ) .ToList() .ForEach( p => rPayments.AddOrReplace( p.RegistrationId, p.Payments ) ); var rPmtSummary = rCosts .Join( rPayments, c => c.Key, p => p.Key, ( c, p ) => new { RegistrationId = c.Key, Costs = c.Value, Payments = p.Value } ) .ToList(); var ids = new List<int>(); if ( ddlRegistrationPaymentStatus.SelectedValue == "Paid in Full" ) { ids = rPmtSummary .Where( r => r.Costs <= r.Payments ) .Select( r => r.RegistrationId ) .ToList(); } else { ids = rPmtSummary .Where( r => r.Costs > r.Payments ) .Select( r => r.RegistrationId ) .ToList(); } qry = qry.Where( r => ids.Contains( r.Id ) ); } SortProperty sortProperty = gRegistrations.SortProperty; if ( sortProperty != null ) { // If sorting by Total Cost or Balance Due, the database query needs to be run first without ordering, // and then ordering needs to be done in memory since TotalCost and BalanceDue are not databae fields. if ( sortProperty.Property == "TotalCost" ) { if ( sortProperty.Direction == SortDirection.Ascending ) { gRegistrations.SetLinqDataSource( qry.ToList().OrderBy( r => r.TotalCost ).AsQueryable() ); } else { gRegistrations.SetLinqDataSource( qry.ToList().OrderByDescending( r => r.TotalCost ).AsQueryable() ); } } else if ( sortProperty.Property == "BalanceDue" ) { if ( sortProperty.Direction == SortDirection.Ascending ) { gRegistrations.SetLinqDataSource( qry.ToList().OrderBy( r => r.BalanceDue ).AsQueryable() ); } else { gRegistrations.SetLinqDataSource( qry.ToList().OrderByDescending( r => r.BalanceDue ).AsQueryable() ); } } else { gRegistrations.SetLinqDataSource( qry.Sort( sortProperty ) ); } } else { gRegistrations.SetLinqDataSource( qry.OrderByDescending( r => r.CreatedDateTime ) ); } // Get all the payments for any registrations being displayed on the current page. // This is used in the RowDataBound event but queried now so that each row does // not have to query for the data. var currentPageRegistrations = gRegistrations.DataSource as List<Registration>; if ( currentPageRegistrations != null && registrationEntityType != null ) { var registrationIds = currentPageRegistrations .Select( r => r.Id ) .ToList(); RegistrationPayments = new FinancialTransactionDetailService( rockContext ) .Queryable().AsNoTracking() .Where( d => d.EntityTypeId.HasValue && d.EntityId.HasValue && d.EntityTypeId.Value == registrationEntityType.Id && registrationIds.Contains( d.EntityId.Value ) ) .ToList(); } var discountCodeHeader = gRegistrations.Columns.GetColumnByHeaderText( "Discount Code" ); if ( discountCodeHeader != null ) { discountCodeHeader.Visible = GetAttributeValue( "DisplayDiscountCodes" ).AsBoolean(); } gRegistrations.DataBind(); } } }
public virtual HttpResponseMessage CanPlaceRegistrant(int registrantId, int registrationTemplatePlacementId, int groupId) { var rockContext = this.Service.Context as RockContext; RegistrationTemplatePlacementService registrationTemplatePlacementService = new RegistrationTemplatePlacementService(rockContext); var registrationTemplatePlacement = registrationTemplatePlacementService.Get(registrationTemplatePlacementId); // make sure the specified registrant, registrationTemplatePlacement, and group are found if (registrationTemplatePlacement == null) { return(ControllerContext.Request.CreateErrorResponse( HttpStatusCode.NotFound, $"Specified RegistrationTemplatePlacement not found.")); } var group = new GroupService(rockContext).Get(groupId); if (group == null) { return(ControllerContext.Request.CreateErrorResponse( HttpStatusCode.NotFound, $"Specified group not found.")); } var registrantInfo = new RegistrationRegistrantService(rockContext).GetSelect(registrantId, s => new { s.PersonAlias.Person, s.Registration.RegistrationInstance }); if (registrantInfo == null) { return(ControllerContext.Request.CreateErrorResponse( HttpStatusCode.NotFound, $"Specified registrant not found.")); } if (registrationTemplatePlacement.GroupTypeId != group.GroupTypeId) { return(ControllerContext.Request.CreateErrorResponse( HttpStatusCode.BadRequest, $"Specified group's group type does not match the group type of the registration placement.")); } RegistrationInstanceService registrationInstanceService = new RegistrationInstanceService(rockContext); var sharedGroupsQuery = registrationTemplatePlacementService.GetRegistrationTemplatePlacementPlacementGroups(registrationTemplatePlacement); var instanceGroupsQuery = registrationInstanceService.GetRegistrationInstancePlacementGroups(registrantInfo.RegistrationInstance).Where(a => a.GroupTypeId == registrationTemplatePlacement.GroupTypeId); var placementGroupsQuery = sharedGroupsQuery.Union(instanceGroupsQuery); // make sure the specified group is one of the placement groups if (!placementGroupsQuery.Any(a => a.Id == groupId)) { return(ControllerContext.Request.CreateErrorResponse( HttpStatusCode.NotFound, $"{group.Name} is not a placement group for this registration template or instance.")); } // If multiple placements are allowed, and there are no more things to check, we can return an OK if (registrationTemplatePlacement.AllowMultiplePlacements) { return(new HttpResponseMessage(HttpStatusCode.OK)); } else { var personAlreadyInPlacementGroup = placementGroupsQuery.Where(a => a.Id != groupId).Any(a => a.Members.Any(m => m.PersonId == registrantInfo.Person.Id)); if (personAlreadyInPlacementGroup) { return(ControllerContext.Request.CreateErrorResponse( HttpStatusCode.BadRequest, $"{registrantInfo.Person} can not be in more than one {registrationTemplatePlacement.Name} group")); } } return(new HttpResponseMessage(HttpStatusCode.OK)); }
/// <summary> /// Adds any registration instances given in the XML file. /// </summary> /// <param name="elemRegistrationInstances"></param> /// <param name="rockContext"></param> private void AddRegistrationInstances( XElement elemRegistrationInstances, RockContext rockContext ) { if ( elemRegistrationInstances == null ) { return; } foreach ( var element in elemRegistrationInstances.Elements( "registrationInstance" ) ) { // skip any illegally formatted items if ( element.Attribute( "templateGuid" ) == null ) { continue; } // Now find the matching registration template RegistrationInstanceService registrationInstanceService = new RegistrationInstanceService( rockContext ); RegistrationTemplateService registrationTemplateService = new RegistrationTemplateService( rockContext ); Guid templateGuid = element.Attribute( "templateGuid" ).Value.AsGuid(); var registrationTemplate = registrationTemplateService.Queryable() .Where( g => g.Guid == templateGuid ) .FirstOrDefault(); if ( registrationTemplate == null ) { throw new NotSupportedException( string.Format( "unknown registration template: {0}", templateGuid ) ); } // Merge lava fields // LAVA additionalReminderDetails Dictionary<string, object> mergeObjects = new Dictionary<string, object>(); DateTime? registrationStartsDate = null; DateTime? registrationEndsDate = null; DateTime? sendReminderDate = null; var additionalReminderDetails = string.Empty; var additionalConfirmationDetails = string.Empty; if ( element.Attribute( "registrationStarts" ) != null ) { var y = element.Attribute( "registrationStarts" ).Value.ResolveMergeFields( mergeObjects ); registrationStartsDate = DateTime.Parse( y ); } if ( element.Attribute( "registrationEnds" ) != null ) { registrationEndsDate = DateTime.Parse( element.Attribute( "registrationEnds" ).Value.ResolveMergeFields( mergeObjects ) ); } if ( element.Attribute( "sendReminderDate" ) != null ) { sendReminderDate = DateTime.Parse( element.Attribute( "sendReminderDate" ).Value.ResolveMergeFields( mergeObjects ) ); } if ( element.Attribute( "additionalReminderDetails" ) != null ) { additionalReminderDetails = element.Attribute( "additionalReminderDetails" ).Value; additionalReminderDetails = additionalReminderDetails.ResolveMergeFields( mergeObjects ); } if ( element.Attribute( "additionalConfirmationDetails" ) != null ) { additionalConfirmationDetails = element.Attribute( "additionalConfirmationDetails" ).Value; additionalConfirmationDetails = additionalConfirmationDetails.ResolveMergeFields( mergeObjects ); } // Get the contact info int? contactPersonAliasId = null; if ( element.Attribute( "contactPersonGuid" ) != null ) { var guid = element.Attribute( "contactPersonGuid" ).Value.AsGuid(); if ( _peopleAliasDictionary.ContainsKey( guid ) ) { contactPersonAliasId = _peopleAliasDictionary[element.Attribute( "contactPersonGuid" ).Value.AsGuid()]; } } // Find the matching account FinancialAccountService financialGatewayService = new FinancialAccountService( rockContext ); string accountName = element.Attribute( "account" ) != null ? element.Attribute( "account" ).Value : string.Empty; var account = financialGatewayService.Queryable() .Where( g => g.Name == accountName ) .FirstOrDefault(); RegistrationInstance registrationInstance = new RegistrationInstance() { Guid = ( element.Attribute( "guid" ) != null ) ? element.Attribute( "guid" ).Value.Trim().AsGuid() : Guid.NewGuid(), Name = ( element.Attribute( "name" ) != null ) ? element.Attribute( "name" ).Value.Trim() : "New " + registrationTemplate.Name, IsActive = true, RegistrationTemplateId = registrationTemplate.Id, StartDateTime = registrationStartsDate, EndDateTime = registrationEndsDate, MaxAttendees = element.Attribute( "maxAttendees" ) != null ? element.Attribute( "maxAttendees" ).Value.AsInteger() : 0, SendReminderDateTime = sendReminderDate, ContactPersonAliasId = contactPersonAliasId, ContactPhone = element.Attribute( "contactPhone" ) != null ? element.Attribute( "contactPhone" ).Value : string.Empty, ContactEmail = element.Attribute( "contactEmail" ) != null ? element.Attribute( "contactEmail" ).Value : string.Empty, AccountId = ( account != null ) ? (int?)account.Id : null, AdditionalReminderDetails = HttpUtility.HtmlDecode( additionalReminderDetails ), AdditionalConfirmationDetails = HttpUtility.HtmlDecode( additionalConfirmationDetails ), CreatedDateTime = RockDateTime.Now, ModifiedDateTime = RockDateTime.Now, }; registrationInstanceService.Add( registrationInstance ); } }