/// <summary>
        /// Reads new values entered by the user for the field
        /// </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(Control control, Dictionary <string, ConfigurationValue> configurationValues)
        {
            var picker = control as RegistrationTemplatePicker;

            if (picker == null)
            {
                return(null);
            }

            string result = null;

            var ids = picker.SelectedValuesAsInt().ToList();

            using (var rockContext = new RockContext())
            {
                var registrationTemplates = new RegistrationTemplateService(rockContext).GetByIds(ids).ToList();

                if (registrationTemplates.Any())
                {
                    result = registrationTemplates.Select(s => s.Guid.ToString()).ToList().AsDelimited(",");
                }
            }

            return(result);
        }
        /// <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>
        /// 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)
        {
            var guid = GetEditValue(control, configurationValues).AsGuid();
            var item = new RegistrationTemplateService(new RockContext()).Get(guid);

            return(item != null ? item.Id : ( int? )null);
        }
        /// <summary>
        /// Sets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <param name="selection">The selection.</param>
        public override void SetSelection(Type entityType, Control[] controls, string selection)
        {
            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 1)
            {
                int registrationTemplateId = selectionValues[0].AsInteger();
                var registrationTemplate   = new RegistrationTemplateService(new RockContext()).Get(registrationTemplateId);
                if (registrationTemplate != null)
                {
                    (controls[0] as RockDropDownList).SetValue(registrationTemplateId);
                }

                ddlRegistrationTemplate_SelectedIndexChanged(this, new EventArgs());

                var ddlRegistrationInstance = controls[1] as RockDropDownList;
                if (selectionValues.Length >= 2)
                {
                    ddlRegistrationInstance.SetValue(selectionValues[1]);
                }
                else
                {
                    ddlRegistrationInstance.SetValue(string.Empty);
                }

                var rblRegistrationType = controls[2] as RockRadioButtonList;
                if (selectionValues.Length >= 3)
                {
                    rblRegistrationType.SetValue(selectionValues[2]);
                }
                else
                {
                    rblRegistrationType.SetValue("2");
                }
            }
        }
Ejemplo n.º 5
0
        protected void ddlNewLinkageTemplate_SelectedIndexChanged(object sender, EventArgs e)
        {
            int?registrationTemplateId = ddlNewLinkageTemplate.SelectedValueAsInt();

            if (registrationTemplateId.HasValue)
            {
                var rockContext = new RockContext();

                if (LinkageState.RegistrationInstance == null)
                {
                    LinkageState.RegistrationInstance          = new RegistrationInstance();
                    LinkageState.RegistrationInstance.IsActive = true;
                }

                LinkageState.RegistrationInstance.RegistrationTemplateId = registrationTemplateId.Value;
                if (LinkageState.RegistrationInstance.RegistrationTemplate == null)
                {
                    LinkageState.RegistrationInstance.RegistrationTemplate = new RegistrationTemplate();
                }

                var registrationTemplate = new RegistrationTemplateService(rockContext).Get(registrationTemplateId.Value);
                if (registrationTemplate != null)
                {
                    LinkageState.RegistrationInstance.RegistrationTemplate.CopyPropertiesFrom(registrationTemplate);
                }

                rieNewLinkage.GetValue(LinkageState.RegistrationInstance);
                rieNewLinkage.SetValue(LinkageState.RegistrationInstance);
            }
        }
        /// <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 RegistrationTemplateService(new RockContext()).Get(id ?? 0);
            var guidValue = item != null?item.Guid.ToString() : string.Empty;

            SetEditValue(control, configurationValues, guidValue);
        }
        /// <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;

            if (!string.IsNullOrWhiteSpace(value))
            {
                var names = new List <string>();
                var guids = new List <Guid>();

                foreach (string guidValue in value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    Guid?guid = guidValue.AsGuidOrNull();
                    if (guid.HasValue)
                    {
                        guids.Add(guid.Value);
                    }
                }

                if (!guids.Any())
                {
                    return(base.FormatValue(parentControl, formattedValue, null, condensed));
                }

                using (var rockContext = new RockContext())
                {
                    var registrationTemplates = new RegistrationTemplateService(rockContext).Queryable().AsNoTracking().Where(a => guids.Contains(a.Guid));
                    if (registrationTemplates.Any())
                    {
                        formattedValue = string.Join(", ", (from registrationTemplate in registrationTemplates select registrationTemplate.Name).ToArray());
                    }
                }
            }

            return(base.FormatValue(parentControl, formattedValue, null, condensed));
        }
Ejemplo n.º 8
0
        private void BindData()
        {
            RockContext rockContext = new RockContext();

            dvpRefundReason.DefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_REFUND_REASON.AsGuid(), rockContext).Id;

            if (!ddlSystemCommunication.SelectedValueAsInt().HasValue)
            {
                SystemCommunicationService systemCommunicationService = new SystemCommunicationService(rockContext);
                var systemCommunications = systemCommunicationService.Queryable().Where(c => c.IsActive == true).Select(e => new { Title = e.Category.Name + " - " + e.Title, e.Id }).OrderBy(e => e.Title).ToList();
                systemCommunications.Insert(0, new { Title = "", Id = 0 });
                ddlSystemCommunication.DataSource     = systemCommunications;
                ddlSystemCommunication.DataValueField = "Id";
                ddlSystemCommunication.DataTextField  = "Title";
                ddlSystemCommunication.DataBind();
            }

            List <int> registrationTemplateIds = rtpRegistrationTemplate.ItemIds.AsIntegerList();

            registrationTemplateIds.RemoveAll(i => i.Equals(0));
            int     itemCount     = 0;
            decimal totalPayments = 0;

            if (liRegistration.Visible == true && registrationTemplateIds.Count > 0)
            {
                RegistrationTemplateService registrationTemplateService = new RegistrationTemplateService(rockContext);
                var templates = registrationTemplateService.GetByIds(rtpRegistrationTemplate.ItemIds.AsIntegerList());
                var instances = templates.SelectMany(t => t.Instances);
                if (ddlRegistrationInstance.SelectedValueAsId().HasValue&& ddlRegistrationInstance.SelectedValueAsId() > 0)
                {
                    var instanceId = ddlRegistrationInstance.SelectedValueAsId();
                    instances = instances.Where(i => i.Id == instanceId);
                }
                itemCount     = instances.SelectMany(i => i.Registrations).Count();
                totalPayments = instances.SelectMany(i => i.Registrations).ToList().SelectMany(r => r.Payments).Sum(p => p.Transaction.TotalAmount);

                if (!ddlRegistrationInstance.SelectedValueAsInt().HasValue)
                {
                    var instanceList = templates.SelectMany(t => t.Instances).OrderBy(i => i.Name).Select(i => new { i.Id, i.Name }).ToList();
                    instanceList.Insert(0, new { Id = 0, Name = "" });
                    ddlRegistrationInstance.DataSource     = instanceList;
                    ddlRegistrationInstance.DataValueField = "Id";
                    ddlRegistrationInstance.DataTextField  = "Name";
                    ddlRegistrationInstance.DataBind();
                }
            }

            if (liTransactionCodes.Visible == true && tbTransactionCodes.Text.Length > 0)
            {
                var codes = tbTransactionCodes.Text.SplitDelimitedValues();
                FinancialTransactionService financialTransactionService = new FinancialTransactionService(rockContext);
                var transactions = financialTransactionService.Queryable().Where(ft => codes.Contains(ft.TransactionCode));
                totalPayments = transactions.SelectMany(t => t.TransactionDetails).Sum(td => td.Amount);
                itemCount     = transactions.Count();
            }
            lAlert.Text = itemCount + (pnlRegistration.Visible?" Registrations - ": " Transactions - ") + totalPayments.FormatAsCurrency() + " Total";
        }
        /// <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 = value.AsGuidOrNull();

            if (guid.HasValue)
            {
                var registrationTemplate = new RegistrationTemplateService(new RockContext()).GetSelect(guid.Value, a => a.Name);
                if (registrationTemplate != null)
                {
                    formattedValue = registrationTemplate;
                }
            }

            return(base.FormatValue(parentControl, formattedValue, configurationValues, condensed));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Gets the registration template.
        /// </summary>
        /// <param name="registrationTemplateId">The registration template identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private RegistrationTemplate GetRegistrationTemplate(int registrationTemplateId, RockContext rockContext = null)
        {
            string key = string.Format("RegistrationTemplate:{0}", registrationTemplateId);
            RegistrationTemplate registrationTemplate = RockPage.GetSharedItem(key) as RegistrationTemplate;

            if (registrationTemplate == null)
            {
                rockContext          = rockContext ?? new RockContext();
                registrationTemplate = new RegistrationTemplateService(rockContext)
                                       .Queryable("GroupType.Roles")
                                       .AsNoTracking()
                                       .FirstOrDefault(i => i.Id == registrationTemplateId);
                RockPage.SaveSharedItem(key, registrationTemplate);
            }

            return(registrationTemplate);
        }
        private void BindData()
        {
            RockContext rockContext = new RockContext();

            dvpRefundReason.DefinedTypeId = DefinedTypeCache.Get(Rock.SystemGuid.DefinedType.FINANCIAL_TRANSACTION_REFUND_REASON.AsGuid(), rockContext).Id;

            if (!ddlSystemEmail.SelectedValueAsInt().HasValue)
            {
                SystemEmailService systemEmailService = new SystemEmailService(rockContext);
                var systemEmails = systemEmailService.Queryable().Select(e => new { Title = e.Category.Name + " - " + e.Title, e.Id }).OrderBy(e => e.Title).ToList();
                systemEmails.Insert(0, new { Title = "", Id = 0 });
                ddlSystemEmail.DataSource     = systemEmails;
                ddlSystemEmail.DataValueField = "Id";
                ddlSystemEmail.DataTextField  = "Title";
                ddlSystemEmail.DataBind();
            }

            List <int> registrationTemplateIds = rtpRegistrationTemplate.ItemIds.AsIntegerList();

            registrationTemplateIds.RemoveAll(i => i.Equals(0));

            if (registrationTemplateIds.Count > 0)
            {
                RegistrationTemplateService registrationTemplateService = new RegistrationTemplateService(rockContext);
                var templates = registrationTemplateService.GetByIds(rtpRegistrationTemplate.ItemIds.AsIntegerList());
                var instances = templates.SelectMany(t => t.Instances);
                if (ddlRegistrationInstance.SelectedValueAsId().HasValue&& ddlRegistrationInstance.SelectedValueAsId() > 0)
                {
                    var instanceId = ddlRegistrationInstance.SelectedValueAsId();
                    instances = instances.Where(i => i.Id == instanceId);
                }
                int registrationCount = instances.SelectMany(i => i.Registrations).Count();
                var totalPayments     = instances.SelectMany(i => i.Registrations).ToList().SelectMany(r => r.Payments).Sum(p => p.Transaction.TotalAmount);
                lAlert.Text = registrationCount + " Registrations - " + totalPayments.FormatAsCurrency() + " Total";

                if (!ddlRegistrationInstance.SelectedValueAsInt().HasValue)
                {
                    var instanceList = templates.SelectMany(t => t.Instances).OrderBy(i => i.Name).Select(i => new { i.Id, i.Name }).ToList();
                    instanceList.Insert(0, new { Id = 0, Name = "" });
                    ddlRegistrationInstance.DataSource     = instanceList;
                    ddlRegistrationInstance.DataValueField = "Id";
                    ddlRegistrationInstance.DataTextField  = "Name";
                    ddlRegistrationInstance.DataBind();
                }
            }
        }
        /// <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)
        {
            string result = "Registrant";

            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 1)
            {
                var rockContext = new RockContext();
                var registrationTemplateGuids = selectionValues[0].Split(',').AsGuidList();
                var registrationTemplates     = new RegistrationTemplateService(rockContext).GetByGuids(registrationTemplateGuids);

                SlidingDateRangePicker fakeSlidingDateRangePicker = null;

                bool includeInactiveRegistrationInstances = false;
                if (selectionValues.Length >= 2)
                {
                    includeInactiveRegistrationInstances = selectionValues[1].AsBooleanOrNull() ?? false;

                    if (selectionValues.Length >= 3)
                    {
                        fakeSlidingDateRangePicker = new SlidingDateRangePicker();

                        // convert comma delimited to pipe
                        fakeSlidingDateRangePicker.DelimitedValues = selectionValues[2].Replace(',', '|');
                    }
                }

                if (registrationTemplates != null)
                {
                    result = string.Format(registrationTemplates.Count() > 0 ? "In Registration Templates: {0}" : "In a Registration", registrationTemplates.Select(a => a.Name).ToList().AsDelimited(", ", " or "));

                    if (includeInactiveRegistrationInstances)
                    {
                        result += ", including inactive registration instances";
                    }

                    if (fakeSlidingDateRangePicker != null)
                    {
                        result += string.Format(", registered in Date Range: {0}", SlidingDateRangePicker.FormatDelimitedValues(fakeSlidingDateRangePicker.DelimitedValues));
                    }
                }
            }

            return(result);
        }
        /// <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 RegistrationTemplatePicker;

            if (picker != null)
            {
                int? itemId   = null;
                Guid?itemGuid = value.AsGuidOrNull();
                if (itemGuid.HasValue)
                {
                    using (var rockContext = new RockContext())
                    {
                        itemId = new RegistrationTemplateService(rockContext).Queryable().Where(a => a.Guid == itemGuid.Value).Select(a => ( int? )a.Id).FirstOrDefault();
                    }
                }

                picker.SetValue(itemId);
            }
        }
Ejemplo n.º 14
0
        /// <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 RegistrationTemplatePicker;

            if (picker != null)
            {
                int? itemId   = picker.SelectedValueAsId();
                Guid?itemGuid = null;
                if (itemId.HasValue)
                {
                    using (var rockContext = new RockContext())
                    {
                        itemGuid = new RegistrationTemplateService(rockContext).Queryable().AsNoTracking().Where(a => a.Id == itemId.Value).Select(a => ( Guid? )a.Guid).FirstOrDefault();
                    }
                }

                return(itemGuid?.ToString() ?? string.Empty);
            }

            return(null);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Sets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <param name="selection">The selection.</param>
        public override void SetSelection(Type entityType, Control[] controls, string selection)
        {
            SelectionConfig selectionConfig = SelectionConfig.Parse(selection);

            var registrationTemplate    = new RegistrationTemplateService(new RockContext()).Get(selectionConfig.RegistrationTemplateId);
            var ddlRegistrationTemplate = controls[0] as RockDropDownList;

            if (registrationTemplate != null)
            {
                ddlRegistrationTemplate.SetValue(selectionConfig.RegistrationTemplateId);
            }

            ddlRegistrationTemplate_SelectedIndexChanged(ddlRegistrationTemplate, new EventArgs());

            var ddlRegistrationInstance = controls[1] as RockDropDownList;

            if (selectionConfig.RegistrationInstanceGuid != null)
            {
                ddlRegistrationInstance.SetValue(selectionConfig.RegistrationInstanceGuid);
            }
            else
            {
                ddlRegistrationInstance.SetValue(string.Empty);
            }

            var rblRegistrationType = controls[2] as RockRadioButtonList;

            rblRegistrationType.SetValue(selectionConfig.RegistrationType.ConvertToInt());

            var ddlOnWaitList = controls[3] as RockDropDownList;

            if (selectionConfig.OnWaitList != null)
            {
                ddlOnWaitList.SetValue(selectionConfig.OnWaitList.ToString());
            }
            else
            {
                ddlOnWaitList.SetValue(string.Empty);
            }
        }
        /// <summary>
        /// Sets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <param name="selection">The selection.</param>
        public override void SetSelection(Type entityType, Control[] controls, string selection)
        {
            if (controls.Count() < 3)
            {
                return;
            }

            RegistrationTemplatePicker registrationTemplatePicker = controls[0] as RegistrationTemplatePicker;
            RockCheckBox           cbIncludeInactive           = controls[1] as RockCheckBox;
            SlidingDateRangePicker registeredOnDateRangePicker = controls[2] as SlidingDateRangePicker;

            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 1)
            {
                List <Guid> registrationTemplateGuids = selectionValues[0].Split(',').AsGuidList();
                var         registrationTemplates     = new RegistrationTemplateService(new RockContext()).GetByGuids(registrationTemplateGuids);
                if (registrationTemplates != null)
                {
                    registrationTemplatePicker.SetValues(registrationTemplates);
                }

                if (selectionValues.Length >= 2)
                {
                    cbIncludeInactive.Checked = selectionValues[1].AsBooleanOrNull() ?? false;
                }
                else
                {
                    // if options where saved before this option was added, set to false, even though it would have included inactive before
                    cbIncludeInactive.Checked = false;
                }

                if (selectionValues.Length >= 3)
                {
                    // convert comma delimited to pipe
                    registeredOnDateRangePicker.DelimitedValues = selectionValues[2].Replace(',', '|');
                }
            }
        }
        /// <summary>
        /// Sets the value.
        /// </summary>
        /// <param name="control">The control.</param>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="value">The value.</param>
        public override void SetEditValue(Control control, Dictionary <string, ConfigurationValue> configurationValues, string value)
        {
            var picker = control as RegistrationTemplatePicker;

            if (picker != null)
            {
                var guids = value?.SplitDelimitedValues().AsGuidList() ?? new List <Guid>();

                if (guids.Any())
                {
                    using (var rockContext = new RockContext())
                    {
                        var registrationTemplates = new RegistrationTemplateService(rockContext).GetByGuids(guids).ToList();
                        picker.SetValues(registrationTemplates);
                    }
                }
                else
                {
                    // make sure that no registration templates are selected
                    picker.SetValues(new List <RegistrationTemplate>());
                }
            }
        }
        /// <summary>
        /// Gets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <returns></returns>
        public override string GetSelection(Type entityType, Control[] controls)
        {
            if (controls.Count() < 3)
            {
                return(null);
            }

            RegistrationTemplatePicker registrationTemplatePicker  = controls[0] as RegistrationTemplatePicker;
            RockCheckBox           cbInactiveRegistrationInstances = controls[1] as RockCheckBox;
            SlidingDateRangePicker registeredOnDateRangePicker     = controls[2] as SlidingDateRangePicker;

            List <int> registrationTemplateIdList = registrationTemplatePicker.SelectedValues.AsIntegerList();
            var        registrationTemplateGuids  = new RegistrationTemplateService(new RockContext()).GetByIds(registrationTemplateIdList).Select(a => a.Guid).Distinct().ToList();

            // convert pipe to comma delimited
            var delimitedValues = registeredOnDateRangePicker.DelimitedValues.Replace("|", ",");

            return(string.Format(
                       "{0}|{1}|{2}",
                       registrationTemplateGuids.AsDelimited(","),
                       cbInactiveRegistrationInstances.Checked.ToString(),
                       delimitedValues));
        }
        /// <summary>
        /// Gets the registration template.
        /// </summary>
        /// <param name="registrationTemplateId">The registration template identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        private RegistrationTemplate GetRegistrationTemplate( int registrationTemplateId, RockContext rockContext = null )
        {
            string key = string.Format( "RegistrationTemplate:{0}", registrationTemplateId );
            RegistrationTemplate registrationTemplate = RockPage.GetSharedItem( key ) as RegistrationTemplate;
            if ( registrationTemplate == null )
            {
                rockContext = rockContext ?? new RockContext();
                registrationTemplate = new RegistrationTemplateService( rockContext )
                    .Queryable( "GroupType.Roles" )
                    .AsNoTracking()
                    .FirstOrDefault( i => i.Id == registrationTemplateId );
                RockPage.SaveSharedItem( key, registrationTemplate );
            }

            return registrationTemplate;
        }
Ejemplo n.º 21
0
        /// <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));

                RockContext rockContext = new RockContext();

                SystemCommunicationService systemCommunicationService = new SystemCommunicationService(rockContext);

                if (pnlRegistration.Visible && registrationTemplateIds.Count > 0)
                {
                    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);

                    // 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))
                        {
                            issuedRefund = issueRefund(payment.Transaction, "Registration", registration.FirstName + " " + registration.LastName);
                        }
                        j++;

                        // Send an email if applicable
                        if (issuedRefund && !string.IsNullOrWhiteSpace(registration.ConfirmationEmail) && ddlSystemCommunication.SelectedValueAsInt().HasValue&& ddlSystemCommunication.SelectedValueAsInt() > 0)
                        {
                            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage);
                            mergeFields.Add("Registration", registration);

                            SystemCommunication systemCommunication = systemCommunicationService.Get(ddlSystemCommunication.SelectedValueAsInt().Value);

                            var emailMessage = new RockEmailMessage(systemCommunication);
                            emailMessage.AdditionalMergeFields = mergeFields;

                            emailMessage.AddRecipient(RockEmailMessageRecipient.CreateAnonymous(registration.ConfirmationEmail, mergeFields));
                            emailMessage.CreateCommunicationRecord = true;
                            emailMessage.Send();
                        }
                    }
                }

                if (pnlTransactionCodes.Visible && tbTransactionCodes.Text.Length > 0)
                {
                    var codes = tbTransactionCodes.Text.SplitDelimitedValues();
                    FinancialTransactionService financialTransactionService = new FinancialTransactionService(rockContext);
                    var transactions = financialTransactionService.Queryable().Where(ft => codes.Contains(ft.TransactionCode));
                    int j            = 0;
                    foreach (var transaction in transactions)
                    {
                        OnProgress("Processing transaction refund " + j + " of " + transactions.Count());
                        var issuedRefund = issueRefund(transaction, "Transaction", transaction.AuthorizedPersonAlias != null ? transaction.AuthorizedPersonAlias.Person.FullName : "Unknown");

                        // Send an email if applicable
                        if (issuedRefund && transaction.AuthorizedPersonAlias != null && !string.IsNullOrWhiteSpace(transaction.AuthorizedPersonAlias.Person.Email) && ddlSystemCommunication.SelectedValueAsInt().HasValue&& ddlSystemCommunication.SelectedValueAsInt() > 0)
                        {
                            var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage);
                            mergeFields.Add("Transaction", transaction);

                            SystemCommunication systemCommunication = systemCommunicationService.Get(ddlSystemCommunication.SelectedValueAsInt().Value);

                            var emailMessage = new RockEmailMessage(systemCommunication);
                            emailMessage.AdditionalMergeFields = mergeFields;
                            emailMessage.FromEmail             = ebEmail.Text;
                            emailMessage.AddRecipient(new RockEmailMessageRecipient(transaction.AuthorizedPersonAlias.Person, 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();
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Sets the value on select.
        /// </summary>
        protected override void SetValueOnSelect()
        {
            var registrationTemplate = new RegistrationTemplateService(new RockContext()).Get(int.Parse(ItemId));

            SetValue(registrationTemplate);
        }
Ejemplo n.º 23
0
        /// <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 dlgNewLinkage_SaveClick(object sender, EventArgs e)
        {
            int?registrationTemplateId = ddlNewLinkageTemplate.SelectedValueAsInt();

            if (registrationTemplateId.HasValue)
            {
                var rockContext = new RockContext();

                if (LinkageState.RegistrationInstance == null)
                {
                    LinkageState.RegistrationInstance          = new RegistrationInstance();
                    LinkageState.RegistrationInstance.IsActive = true;
                }

                LinkageState.RegistrationInstance.RegistrationTemplateId = registrationTemplateId.Value;
                if (LinkageState.RegistrationInstance.RegistrationTemplate == null)
                {
                    LinkageState.RegistrationInstance.RegistrationTemplate = new RegistrationTemplate();
                }

                var registrationTemplate = new RegistrationTemplateService(rockContext).Get(registrationTemplateId.Value);
                if (registrationTemplate != null)
                {
                    LinkageState.RegistrationInstance.RegistrationTemplate.CopyPropertiesFrom(registrationTemplate);
                }

                rieNewLinkage.GetValue(LinkageState.RegistrationInstance);

                int?groupId = gpNewLinkageGroup.SelectedValueAsInt();
                if (groupId.HasValue)
                {
                    var group = new GroupService(rockContext).Get(groupId.Value);
                    if (group != null)
                    {
                        LinkageState.GroupId = group.Id;
                        LinkageState.Group   = group;
                    }
                }

                LinkageState.PublicName = rieNewLinkage.Name;
                LinkageState.UrlSlug    = rieNewLinkage.UrlSlug;

                // 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();
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Sets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <param name="selection">The selection.</param>
        public override void SetSelection( Type entityType, Control[] controls, string selection )
        {
            string[] selectionValues = selection.Split( '|' );
            if ( selectionValues.Length >= 1 )
            {
                int registrationTemplateId = selectionValues[0].AsInteger();
                var registrationTemplate = new RegistrationTemplateService( new RockContext() ).Get( registrationTemplateId );
                if ( registrationTemplate  != null )
                {
                    ( controls[0] as RockDropDownList ).SetValue( registrationTemplateId );
                }

                ddlRegistrationTemplate_SelectedIndexChanged( this, new EventArgs() );

                var ddlRegistrationInstance = controls[1] as RockDropDownList;
                if ( selectionValues.Length >= 2 )
                {
                    ddlRegistrationInstance.SetValue( selectionValues[1] );
                }
                else
                {
                    ddlRegistrationInstance.SetValue( string.Empty );
                }

                var rblRegistrationType = controls[2] as RockRadioButtonList;
                if ( selectionValues.Length >= 3 )
                {
                    rblRegistrationType.SetValue( selectionValues[2] );
                }
                else
                {
                    rblRegistrationType.SetValue( "2" );
                }
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            var mergeFields = GetMergeFields(action);

            var registrationTemplateService         = new RegistrationTemplateService(rockContext);
            var registrationTemplateDiscountService = new RegistrationTemplateDiscountService(rockContext);

            var registrationTemplate = registrationTemplateService.Get(GetAttributeValue(action, "RegistrationTemplate").ResolveMergeFields(mergeFields).AsGuid());

            if (registrationTemplate == null)
            {
                errorMessages.Add("Could not find selected registration template");
                return(false);
            }

            var length = GetAttributeValue(action, "DiscountCodeLength", true).ResolveMergeFields(mergeFields).AsInteger();

            if (length < 3)
            {
                length = 3;
            }

            string code = GetRandomCode(length);

            while (registrationTemplateDiscountService
                   .Queryable().AsNoTracking()
                   .Any(d =>
                        d.RegistrationTemplateId == registrationTemplate.Id &&
                        d.Code == code))
            {
                code = GetRandomCode(length);
            }

            var discountCode = new RegistrationTemplateDiscount();

            discountCode.Code = code;

            //Set discount value
            var     discountType   = GetAttributeValue(action, "DiscountType");
            decimal discountAmount = GetAttributeValue(action, "DiscountAmount", true).ResolveMergeFields(mergeFields).AsDecimal();

            if (discountType == "Percent")
            {
                discountCode.DiscountPercentage = discountAmount / 100;
            }
            if (discountType == "Amount")
            {
                discountCode.DiscountAmount = discountAmount;
            }

            var maximumUsage = GetAttributeValue(action, "MaximumUsage", true).ResolveMergeFields(mergeFields).AsInteger();

            if (maximumUsage > 0)
            {
                discountCode.MaxUsage = maximumUsage;
            }

            var maximumRegistrants = GetAttributeValue(action, "MaximumRegistrants", true).ResolveMergeFields(mergeFields).AsInteger();

            if (maximumRegistrants > 0)
            {
                discountCode.MaxRegistrants = maximumRegistrants;
            }

            var minimumRegistrants = GetAttributeValue(action, "MinimumRegistrants", true).ResolveMergeFields(mergeFields).AsInteger();

            if (minimumRegistrants < 0)
            {
                discountCode.MinRegistrants = minimumRegistrants;
            }

            var effectiveDates = GetAttributeValue(action, "EffectiveDates", true);

            if (!string.IsNullOrWhiteSpace(effectiveDates))
            {
                var dates = effectiveDates.Split(',');
                if (dates.Length > 1 &&
                    !string.IsNullOrWhiteSpace(dates[0]) &&
                    !string.IsNullOrWhiteSpace(dates[1]))
                {
                    discountCode.StartDate = dates[0].AsDateTime();
                    discountCode.EndDate   = dates[1].AsDateTime();
                }
            }

            registrationTemplate.Discounts.Add(discountCode);
            rockContext.SaveChanges();
            SetWorkflowAttributeValue(action, "DiscountCodeAttribute", code);
            return(true);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Deletes the registration templates.
        /// </summary>
        /// <param name="elemRegistrationTemplate">The elem registration template.</param>
        /// <param name="rockContext">The rock context.</param>
        private void DeleteRegistrationTemplates( XElement elemRegistrationTemplates, RockContext rockContext )
        {
            if ( elemRegistrationTemplates == null )
            {
                return;
            }

            var service = new RegistrationTemplateService( rockContext );

            foreach ( var elemRegistrationTemplate in elemRegistrationTemplates.Elements( "registrationTemplate" ) )
            {
                Guid guid = elemRegistrationTemplate.Attribute( "guid" ).Value.Trim().AsGuid();
                var registrationTemplate = service.Get( guid );

                rockContext.WrapTransaction( () =>
                {
                    if ( registrationTemplate != null )
                    {
                        if ( registrationTemplate.Instances != null )
                        {
                            AttributeService attributeService = new AttributeService( rockContext );
                            if ( registrationTemplate.Forms != null )
                            {
                                foreach ( var id in registrationTemplate.Forms.SelectMany( f => f.Fields ).Where( ff => ff.FieldSource == RegistrationFieldSource.RegistrationAttribute ).Select( f => f.AttributeId ) )
                                {
                                    if ( id != null )
                                    {
                                        Rock.Model.Attribute attribute = attributeService.Get( id ?? -1 );
                                        if ( attribute != null )
                                        {
                                            attributeService.Delete( attribute );
                                        }
                                    }
                                }
                            }
                            var registrations = registrationTemplate.Instances.SelectMany( i => i.Registrations );
                            new RegistrationService( rockContext ).DeleteRange( registrations );
                            new RegistrationInstanceService( rockContext ).DeleteRange( registrationTemplate.Instances );
                        }

                        service.Delete( registrationTemplate );
                        rockContext.SaveChanges();
                    }
                } );
            }
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Adds any registration templates given in the XML file.
        /// </summary>
        /// <param name="elemFamilies"></param>
        /// <param name="rockContext"></param>
        private void AddRegistrationTemplates( XElement elemRegistrationTemplates, RockContext rockContext )
        {
            if ( elemRegistrationTemplates == null )
            {
                return;
            }

            // Get attribute values from RegistrationTemplateDetail block
            // Get instance of the attribute.
            string defaultConfirmationEmail = string.Empty;
            string defaultReminderEmail = string.Empty;
            string defaultSuccessText = string.Empty;
            string defaultPaymentReminderEmail = string.Empty;

            //CodeEditorFieldAttribute MyAttribute = (CodeEditorFieldAttribute)System.Attribute.GetCustomAttribute( typeof( RockWeb.Blocks.Event.RegistrationTemplateDetail ), typeof( CodeEditorFieldAttribute ) );
            var blockAttributes = System.Attribute.GetCustomAttributes( typeof( RockWeb.Blocks.Event.RegistrationTemplateDetail ), typeof( CodeEditorFieldAttribute ) );
            foreach ( CodeEditorFieldAttribute blockAttribute in blockAttributes )
            {
                switch ( blockAttribute.Name )
                {
                    case "Default Confirmation Email":
                        defaultConfirmationEmail = blockAttribute.DefaultValue;
                        break;

                    case "Default Reminder Email":
                        defaultReminderEmail = blockAttribute.DefaultValue;
                        break;

                    case "Default Success Text":
                        defaultSuccessText = blockAttribute.DefaultValue;
                        break;

                    case "Default Payment Reminder Email":
                        defaultPaymentReminderEmail = blockAttribute.DefaultValue;
                        break;

                    default:
                        break;
                }
            }

            RegistrationTemplateService registrationTemplateService = new RegistrationTemplateService( rockContext );

            // Add a template for each...
            foreach ( var element in elemRegistrationTemplates.Elements( "registrationTemplate" ) )
            {
                // skip any illegally formatted items
                if ( element.Attribute( "guid" ) == null )
                {
                    continue;
                }

                int categoryId = CategoryCache.Read( element.Attribute( "categoryGuid" ).Value.Trim().AsGuid() ).Id;

                // Find the group type and
                var groupType = GroupTypeCache.Read( element.Attribute( "groupTypeGuid" ).Value.Trim().AsGuid() );

                RegistrantsSameFamily registrantsSameFamily;
                if ( element.Attribute( "registrantsInSameFamily" ) != null )
                {
                    Enum.TryParse( element.Attribute( "registrantsInSameFamily" ).Value.Trim(), out registrantsSameFamily );
                }
                else
                {
                    registrantsSameFamily = RegistrantsSameFamily.Ask;
                }

                bool setCostOnInstance = true;
                if ( element.Attribute( "setCostOn" ).Value.Trim() == "template" )
                {
                    setCostOnInstance = false;
                }

                RegistrationNotify notify = RegistrationNotify.None;
                RegistrationNotify matchNotify;
                foreach ( string item in element.Attribute( "notify" ).Value.SplitDelimitedValues( whitespace: false ) )
                {
                    if ( Enum.TryParse( item.Replace( " ", string.Empty ), out matchNotify ) )
                    {
                        notify = notify | matchNotify;
                    }
                }

                // Now find the matching financial gateway
                FinancialGatewayService financialGatewayService = new FinancialGatewayService( rockContext );
                string gatewayName = element.Attribute( "financialGateway" ) != null ? element.Attribute( "financialGateway" ).Value : "Test Gateway";
                var financialGateway = financialGatewayService.Queryable()
                    .Where( g => g.Name == gatewayName )
                    .FirstOrDefault();

                RegistrationTemplate registrationTemplate = new RegistrationTemplate()
                {
                    Guid = element.Attribute( "guid" ).Value.Trim().AsGuid(),
                    Name = element.Attribute( "name" ).Value.Trim(),
                    IsActive = true,
                    CategoryId = categoryId,
                    GroupTypeId = groupType.Id,
                    GroupMemberRoleId = groupType.DefaultGroupRoleId,
                    GroupMemberStatus = GroupMemberStatus.Active,
                    Notify = notify,
                    AddPersonNote = element.Attribute( "addPersonNote" ) != null ? element.Attribute( "addPersonNote" ).Value.AsBoolean() : false,
                    LoginRequired = element.Attribute( "loginRequired" ) != null ? element.Attribute( "loginRequired" ).Value.AsBoolean() : false,
                    AllowExternalRegistrationUpdates = element.Attribute( "allowExternalUpdatesToSavedRegistrations" ) != null ? element.Attribute( "allowExternalUpdatesToSavedRegistrations" ).Value.AsBoolean() : false,
                    AllowGroupPlacement = element.Attribute( "allowGroupPlacement" ) != null ? element.Attribute( "allowGroupPlacement" ).Value.AsBoolean() : false,
                    AllowMultipleRegistrants = element.Attribute( "allowMultipleRegistrants" ) != null ? element.Attribute( "allowMultipleRegistrants" ).Value.AsBoolean() : false,
                    MaxRegistrants = element.Attribute( "maxRegistrants" ).Value.AsInteger(),
                    RegistrantsSameFamily = registrantsSameFamily,
                    SetCostOnInstance = setCostOnInstance,
                    FinancialGatewayId = financialGateway.Id,
                    BatchNamePrefix = element.Attribute( "batchNamePrefix" ) != null ? element.Attribute( "batchNamePrefix" ).Value.Trim() : string.Empty,
                    Cost = element.Attribute( "cost" ).Value.AsDecimal(),
                    MinimumInitialPayment = element.Attribute( "minInitialPayment" ).Value.AsDecimal(),
                    RegistrationTerm = element.Attribute( "registrationTerm" ) != null ? element.Attribute( "registrationTerm" ).Value.Trim() : "Registration",
                    RegistrantTerm = element.Attribute( "registrantTerm" ) != null ? element.Attribute( "registrantTerm" ).Value.Trim() : "Registrant",
                    FeeTerm = element.Attribute( "feeTerm" ) != null ? element.Attribute( "feeTerm" ).Value.Trim() : "Additional Options",
                    DiscountCodeTerm = element.Attribute( "discountCodeTerm" ) != null ? element.Attribute( "discountCodeTerm" ).Value.Trim() : "Discount Code",
                    ConfirmationFromName = "{{ RegistrationInstance.ContactPersonAlias.Person.FullName }}",
                    ConfirmationFromEmail = "{{ RegistrationInstance.ContactEmail }}",
                    ConfirmationSubject = "{{ RegistrationInstance.Name }} Confirmation",
                    ConfirmationEmailTemplate = defaultConfirmationEmail,
                    ReminderFromName = "{{ RegistrationInstance.ContactPersonAlias.Person.FullName }}",
                    ReminderFromEmail = "{{ RegistrationInstance.ContactEmail }}",
                    ReminderSubject = "{{ RegistrationInstance.Name }} Reminder",
                    ReminderEmailTemplate = defaultReminderEmail,
                    SuccessTitle = "Congratulations {{ Registration.FirstName }}",
                    SuccessText = defaultSuccessText,
                    PaymentReminderEmailTemplate = defaultPaymentReminderEmail,
                    PaymentReminderFromEmail = "{{ RegistrationInstance.ContactEmail }}",
                    PaymentReminderFromName = "{{ RegistrationInstance.ContactPersonAlias.Person.FullName }}",
                    PaymentReminderSubject = "{{ RegistrationInstance.Name }} Payment Reminder",
                    PaymentReminderTimeSpan = element.Attribute( "paymentReminderTimeSpan" ) != null ? element.Attribute( "paymentReminderTimeSpan" ).Value.AsInteger() : 0,
                    CreatedDateTime = RockDateTime.Now,
                    ModifiedDateTime = RockDateTime.Now,
                };

                registrationTemplateService.Add( registrationTemplate );

                rockContext.SaveChanges();
                var x = registrationTemplate.Id;

                string name = element.Attribute( "name" ).Value.Trim();
                bool allowExternalUpdatesToSavedRegistrations = element.Attribute( "allowExternalUpdatesToSavedRegistrations" ).Value.AsBoolean();
                bool addPersonNote = element.Attribute( "addPersonNote" ).Value.AsBoolean();
                bool loginRequired = element.Attribute( "loginRequired" ).Value.AsBoolean();
                Guid guid = element.Attribute( "guid" ).Value.Trim().AsGuid();

                // Find any Form elements and add them to the template
                int formOrder = 0;
                var registrationAttributeQualifierColumn = "RegistrationTemplateId";
                int? registrationRegistrantEntityTypeId = EntityTypeCache.Read( typeof( Rock.Model.RegistrationRegistrant ) ).Id;
                if ( element.Elements( "forms" ).Count() > 0 )
                {
                    foreach ( var formElement in element.Elements( "forms" ).Elements( "form" ) )
                    {
                        formOrder++;
                        var form = new RegistrationTemplateForm();
                        form.Guid = formElement.Attribute( "guid" ).Value.Trim().AsGuid();
                        registrationTemplate.Forms.Add( form );
                        form.Name = formElement.Attribute( "name" ).Value.Trim();
                        form.Order = formOrder;

                        int ffOrder = 0;
                        if ( formElement.Elements( "formFields" ).Count() > 0 )
                        {
                            foreach ( var formFieldElement in formElement.Elements( "formFields" ).Elements( "field" ) )
                            {
                                ffOrder++;
                                var formField = new RegistrationTemplateFormField();
                                formField.Guid = Guid.NewGuid();
                                formField.CreatedDateTime = RockDateTime.Now;

                                form.Fields.Add( formField );

                                switch ( formFieldElement.Attribute( "source" ).Value.Trim().ToLowerInvariant() )
                                {
                                    case "person field":
                                        formField.FieldSource = RegistrationFieldSource.PersonField;
                                        break;
                                    case "person attribute":
                                        formField.FieldSource = RegistrationFieldSource.PersonAttribute;
                                        break;
                                    case "group member attribute":
                                        formField.FieldSource = RegistrationFieldSource.GroupMemberAttribute;
                                        break;
                                    case "registration attribute":
                                        formField.FieldSource = RegistrationFieldSource.RegistrationAttribute;

                                        //var qualifierValue = RegistrationTemplate.Id.ToString();
                                        var attrState = new Rock.Model.Attribute();

                                        attrState.Guid = formFieldElement.Attribute( "guid" ).Value.AsGuid();
                                        attrState.Name = formFieldElement.Attribute( "name" ).Value.Trim();
                                        attrState.Key = attrState.Name.RemoveSpecialCharacters().Replace( " ", string.Empty );
                                        var type = formFieldElement.Attribute( "type" ).Value.Trim();
                                        var fieldType = FieldTypeCache.All().Where( f => f.Name == type ).FirstOrDefault();
                                        attrState.FieldTypeId = fieldType.Id;
                                        var attribute = Helper.SaveAttributeEdits( attrState, registrationRegistrantEntityTypeId, registrationAttributeQualifierColumn, registrationTemplate.Id.ToString(), rockContext );
                                        //rockContext.ChangeTracker.DetectChanges();
                                        rockContext.SaveChanges( disablePrePostProcessing: true );
                                        formField.Attribute = attribute;

                                        break;
                                    default:
                                        throw new NotSupportedException( string.Format( "unknown form field source: {0}", formFieldElement.Attribute( "source" ).Value ) );
                                }

                                formField.AttributeId = null;
                                if ( !formField.AttributeId.HasValue &&
                                    formField.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                                    formField.Attribute != null )
                                {
                                    var attr = AttributeCache.Read( formField.Attribute.Guid, rockContext );
                                    if ( attr != null )
                                    {
                                        formField.AttributeId = attr.Id;
                                    }
                                }

                                RegistrationPersonFieldType registrationPersonFieldType;
                                if ( formField.FieldSource == RegistrationFieldSource.PersonField && formFieldElement.Attribute( "name" ) != null &&
                                    Enum.TryParse( formFieldElement.Attribute( "name" ).Value.Replace( " ", string.Empty ).Trim(), out registrationPersonFieldType ) )
                                {
                                    formField.PersonFieldType = registrationPersonFieldType;
                                }

                                formField.IsInternal = formFieldElement.Attribute( "isInternal" ) != null ? formFieldElement.Attribute( "isInternal" ).Value.AsBoolean() : false;
                                formField.IsSharedValue = formFieldElement.Attribute( "isCommon" ) != null ? formFieldElement.Attribute( "isCommon" ).Value.AsBoolean() : false;
                                formField.ShowCurrentValue = formFieldElement.Attribute( "showCurrentValue" ) != null ? formFieldElement.Attribute( "showCurrentValue" ).Value.AsBoolean() : false;
                                formField.PreText = formFieldElement.Attribute( "preText" ) != null ? formFieldElement.Attribute( "preText" ).Value : string.Empty;
                                formField.PostText = formFieldElement.Attribute( "postText" ) != null ? formFieldElement.Attribute( "postText" ).Value : string.Empty;
                                formField.IsGridField = formFieldElement.Attribute( "showOnGrid" ) != null ? formFieldElement.Attribute( "showOnGrid" ).Value.AsBoolean() : false;
                                formField.IsRequired = formFieldElement.Attribute( "isRequired" ) != null ? formFieldElement.Attribute( "isRequired" ).Value.AsBoolean() : false;
                                formField.Order = ffOrder;
                                formField.CreatedDateTime = RockDateTime.Now;
                            }
                        }
                    }
                }

                // Discounts
                int discountOrder = 0;
                if ( element.Elements( "discounts" ) != null )
                {
                    foreach ( var discountElement in element.Elements( "discounts" ).Elements( "discount" ) )
                    {
                        discountOrder++;
                        var discount = new RegistrationTemplateDiscount();
                        discount.Guid = Guid.NewGuid();
                        registrationTemplate.Discounts.Add( discount );

                        discount.Code = discountElement.Attribute( "code" ).Value;

                        switch ( discountElement.Attribute( "type" ).Value.Trim().ToLowerInvariant() )
                        {
                            case "percentage":
                                discount.DiscountPercentage = discountElement.Attribute( "value" ).Value.Trim().AsDecimal() * 0.01m;
                                discount.DiscountAmount = 0.0m;
                                break;
                            case "amount":
                                discount.DiscountPercentage = 0.0m;
                                discount.DiscountAmount = discountElement.Attribute( "value" ).Value.Trim().AsDecimal();
                                break;
                            default:
                                throw new NotSupportedException( string.Format( "unknown discount type: {0}", discountElement.Attribute( "type" ).Value ) );
                        }
                        discount.Order = discountOrder;
                    }
                }

                // Fees
                int feeOrder = 0;
                if ( element.Elements( "fees" ) != null )
                {
                    foreach ( var feeElement in element.Elements( "fees" ).Elements( "fee" ) )
                    {
                        feeOrder++;
                        var fee = new RegistrationTemplateFee();
                        fee.Guid = Guid.NewGuid();
                        registrationTemplate.Fees.Add( fee );

                        switch ( feeElement.Attribute( "type" ).Value.Trim().ToLowerInvariant() )
                        {
                            case "multiple":
                                fee.FeeType = RegistrationFeeType.Multiple;
                                fee.CostValue = FormatMultipleFeeCosts( feeElement.Elements( "option" ) );
                                break;
                            case "single":
                                fee.FeeType = RegistrationFeeType.Single;
                                fee.CostValue = feeElement.Attribute( "cost" ).Value.Trim();
                                break;
                            default:
                                throw new NotSupportedException( string.Format( "unknown fee type: {0}", feeElement.Attribute( "type" ).Value ) );
                        }

                        fee.Name = feeElement.Attribute( "name" ).Value.Trim();
                        fee.DiscountApplies = feeElement.Attribute( "discountApplies" ).Value.AsBoolean();
                        fee.AllowMultiple = feeElement.Attribute( "enableQuantity" ).Value.AsBoolean();
                        fee.Order = feeOrder;
                    }
                }
            }
        }
Ejemplo n.º 28
0
        /// <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 );
            }
        }
        /// <summary>
        /// Gets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <returns></returns>
        public override string GetSelection( Type entityType, Control[] controls )
        {
            if ( controls.Count() < 3 )
            {
                return null;
            }

            RegistrationTemplatePicker registrationTemplatePicker = controls[0] as RegistrationTemplatePicker;
            RockCheckBox cbInactiveRegistrationInstances = controls[1] as RockCheckBox;
            SlidingDateRangePicker registeredOnDateRangePicker = controls[2] as SlidingDateRangePicker;

            List<int> registrationTemplateIdList = registrationTemplatePicker.SelectedValues.AsIntegerList();
            var registrationTemplateGuids = new RegistrationTemplateService( new RockContext() ).GetByIds( registrationTemplateIdList ).Select( a => a.Guid ).Distinct().ToList();

            // convert pipe to comma delimited
            var delimitedValues = registeredOnDateRangePicker.DelimitedValues.Replace( "|", "," );

            return string.Format(
                "{0}|{1}|{2}",
                registrationTemplateGuids.AsDelimited( "," ),
                cbIncludeInactiveRegistrationInstances.Checked.ToString(),
                delimitedValues );
        }
        /// <summary>
        /// Sets the selection.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="controls">The controls.</param>
        /// <param name="selection">The selection.</param>
        public override void SetSelection( Type entityType, Control[] controls, string selection )
        {
            if ( controls.Count() < 3 )
            {
                return;
            }

            RegistrationTemplatePicker registrationTemplatePicker = controls[0] as RegistrationTemplatePicker;
            RockCheckBox cbIncludeInactive = controls[1] as RockCheckBox;
            SlidingDateRangePicker registeredOnDateRangePicker = controls[2] as SlidingDateRangePicker;

            string[] selectionValues = selection.Split( '|' );
            if ( selectionValues.Length >= 1 )
            {
                List<Guid> registrationTemplateGuids = selectionValues[0].Split( ',' ).AsGuidList();
                var registrationTemplates = new RegistrationTemplateService( new RockContext() ).GetByGuids( registrationTemplateGuids );
                if ( registrationTemplates != null )
                {
                    registrationTemplatePicker.SetValues( registrationTemplates );
                }

                if ( selectionValues.Length >= 2 )
                {
                    cbIncludeInactiveRegistrationInstances.Checked = selectionValues[6].AsBooleanOrNull() ?? false;
                }
                else
                {
                    // if options where saved before this option was added, set to false, even though it would have included inactive before
                    cbIncludeInactiveRegistrationInstances.Checked = false;
                }

                if ( selectionValues.Length >= 3 )
                {
                    // convert comma delimited to pipe
                    registeredOnDateRangePicker.DelimitedValues = selectionValues[7].Replace( ',', '|' );
                }
            }
        }
        /// <summary>
        /// Handles the Click event of the btnCopy 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 btnCopy_Click( object sender, EventArgs e )
        {
            var rockContext = new RockContext();
            var RegistrationTemplate = new RegistrationTemplateService( rockContext ).Get( hfRegistrationTemplateId.Value.AsInteger() );

            if ( RegistrationTemplate != null )
            {
                // Load the state objects for the source registration template
                LoadStateDetails( RegistrationTemplate, rockContext );

                // clone the registration template
                var newRegistrationTemplate = RegistrationTemplate.Clone( false );
                newRegistrationTemplate.CreatedByPersonAlias = null;
                newRegistrationTemplate.CreatedByPersonAliasId = null;
                newRegistrationTemplate.CreatedDateTime = RockDateTime.Now;
                newRegistrationTemplate.ModifiedByPersonAlias = null;
                newRegistrationTemplate.ModifiedByPersonAliasId = null;
                newRegistrationTemplate.ModifiedDateTime = RockDateTime.Now;
                newRegistrationTemplate.Id = 0;
                newRegistrationTemplate.Guid = Guid.NewGuid();
                newRegistrationTemplate.Name = RegistrationTemplate.Name + " - Copy";

                // Create temporary state objects for the new registration template
                var newFormState = new List<RegistrationTemplateForm>();
                var newFormFieldsState = new Dictionary<Guid, List<RegistrationTemplateFormField>>();
                var newDiscountState = new List<RegistrationTemplateDiscount>();
                var newFeeState = new List<RegistrationTemplateFee>();

                foreach ( var form in FormState )
                {
                    var newForm = form.Clone( false );
                    newForm.RegistrationTemplateId = 0;
                    newForm.Id = 0;
                    newForm.Guid = Guid.NewGuid();
                    newFormState.Add( newForm );

                    if ( FormFieldsState.ContainsKey( form.Guid ) )
                    {
                        newFormFieldsState.Add( newForm.Guid, new List<RegistrationTemplateFormField>() );
                        foreach ( var formField in FormFieldsState[form.Guid] )
                        {
                            var newFormField = formField.Clone( false );
                            newFormField.RegistrationTemplateFormId = 0;
                            newFormField.Id = 0;
                            newFormField.Guid = Guid.NewGuid();
                            newFormFieldsState[newForm.Guid].Add( newFormField );

                            if ( formField.FieldSource != RegistrationFieldSource.PersonField )
                            {
                                newFormField.Attribute = formField.Attribute;
                            }

                            if ( formField.FieldSource == RegistrationFieldSource.RegistrationAttribute && formField.Attribute != null )
                            {
                                var newAttribute = formField.Attribute.Clone( false );
                                newAttribute.Id = 0;
                                newAttribute.Guid = Guid.NewGuid();
                                newAttribute.IsSystem = false;

                                newFormField.AttributeId = null;
                                newFormField.Attribute = newAttribute;

                                foreach ( var qualifier in formField.Attribute.AttributeQualifiers )
                                {
                                    var newQualifier = qualifier.Clone( false );
                                    newQualifier.Id = 0;
                                    newQualifier.Guid = Guid.NewGuid();
                                    newQualifier.IsSystem = false;
                                    newAttribute.AttributeQualifiers.Add( qualifier );
                                }
                            }
                        }
                    }
                }

                foreach ( var discount in DiscountState )
                {
                    var newDiscount = discount.Clone( false );
                    newDiscount.RegistrationTemplateId = 0;
                    newDiscount.Id = 0;
                    newDiscount.Guid = Guid.NewGuid();
                    newDiscountState.Add( newDiscount );
                }

                foreach ( var fee in FeeState )
                {
                    var newFee = fee.Clone( false );
                    newFee.RegistrationTemplateId = 0;
                    newFee.Id = 0;
                    newFee.Guid = Guid.NewGuid();
                    newFeeState.Add( newFee );
                }

                FormState = newFormState;
                FormFieldsState = newFormFieldsState;
                DiscountState = newDiscountState;
                FeeState = newFeeState;

                hfRegistrationTemplateId.Value = newRegistrationTemplate.Id.ToString();
                ShowEditDetails( newRegistrationTemplate, rockContext );
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Create an EntityField for an Attribute.
        /// </summary>
        /// <param name="attribute">The attribute.</param>
        /// <param name="limitToFilterableAttributes"></param>
        public static EntityField GetEntityFieldForAttribute(AttributeCache attribute, bool limitToFilterableAttributes = true)
        {
            // Ensure field name only has Alpha, Numeric and underscore chars
            string fieldName = attribute.Key.RemoveSpecialCharacters().Replace(".", "");

            EntityField entityField = null;

            // Make sure that the attributes field type actually renders a filter control if limitToFilterableAttributes
            var fieldType = FieldTypeCache.Get(attribute.FieldTypeId);

            if (fieldType != null && (!limitToFilterableAttributes || fieldType.Field.HasFilterControl()))
            {
                entityField       = new EntityField(fieldName, FieldKind.Attribute, typeof(string), attribute.Guid, fieldType);
                entityField.Title = attribute.Name;
                entityField.TitleWithoutQualifier = entityField.Title;

                foreach (var config in attribute.QualifierValues)
                {
                    entityField.FieldConfig.Add(config.Key, config.Value);
                }

                // Special processing for Entity Type "Group" or "GroupMember" to handle sub-types that are distinguished by GroupTypeId.
                if ((attribute.EntityTypeId == EntityTypeCache.GetId(typeof(Group)) || attribute.EntityTypeId == EntityTypeCache.GetId(typeof(GroupMember)) && attribute.EntityTypeQualifierColumn == "GroupTypeId"))
                {
                    var groupType = GroupTypeCache.Get(attribute.EntityTypeQualifierValue.AsInteger());
                    if (groupType != null)
                    {
                        // Append the Qualifier to the title
                        entityField.AttributeEntityTypeQualifierName = groupType.Name;
                        entityField.Title = string.Format("{0} ({1})", attribute.Name, groupType.Name);
                    }
                }

                // Special processing for Entity Type "ConnectionRequest" to handle sub-types that are distinguished by ConnectionOpportunityId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(ConnectionRequest)) && attribute.EntityTypeQualifierColumn == "ConnectionOpportunityId")
                {
                    using (var rockContext = new RockContext())
                    {
                        var connectionOpportunityName = new ConnectionOpportunityService(rockContext).GetSelect(attribute.EntityTypeQualifierValue.AsInteger(), s => s.Name);
                        if (connectionOpportunityName != null)
                        {
                            // Append the Qualifier to the title
                            entityField.AttributeEntityTypeQualifierName = connectionOpportunityName;
                            entityField.Title = string.Format("{0} (Opportunity: {1})", attribute.Name, connectionOpportunityName);
                        }
                    }
                }

                // Special processing for Entity Type "ContentChannelItem" to handle sub-types that are distinguished by ContentChannelTypeId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(ContentChannelItem)) && attribute.EntityTypeQualifierColumn == "ContentChannelTypeId")
                {
                    using (var rockContext = new RockContext())
                    {
                        var contentChannelTypeName = new ContentChannelTypeService(rockContext).GetSelect(attribute.EntityTypeQualifierValue.AsInteger(), s => s.Name);
                        if (contentChannelTypeName != null)
                        {
                            // Append the Qualifier to the title
                            entityField.AttributeEntityTypeQualifierName = contentChannelTypeName;
                            entityField.Title = string.Format("{0} (ChannelType: {1})", attribute.Name, contentChannelTypeName);
                        }
                    }
                }

                // Special processing for Entity Type "Registration" to handle sub-types that are distinguished by RegistrationTemplateId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(Registration)) && attribute.EntityTypeQualifierColumn == "RegistrationTemplateId")
                {
                    using (var rockContext = new RockContext())
                    {
                        var RegistrationTemplateName = new RegistrationTemplateService(rockContext).GetSelect(attribute.EntityTypeQualifierValue.AsInteger(), s => s.Name);
                        if (RegistrationTemplateName != null)
                        {
                            // Append the Qualifier to the title
                            entityField.AttributeEntityTypeQualifierName = RegistrationTemplateName;
                            entityField.Title = string.Format("{0} (Registration Template: {1})", attribute.Name, RegistrationTemplateName);
                        }
                    }
                }

                // Special processing for Entity Type "ContentChannelItem" to handle sub-types that are distinguished by ContentChannelId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(ContentChannelItem)) && attribute.EntityTypeQualifierColumn == "ContentChannelId")
                {
                    var contentChannel = ContentChannelCache.Get(attribute.EntityTypeQualifierValue.AsInteger());
                    if (contentChannel != null)
                    {
                        // Append the Qualifier to the title
                        entityField.AttributeEntityTypeQualifierName = contentChannel.Name;
                        entityField.Title = string.Format("{0} (Channel: {1})", attribute.Name, contentChannel.Name);
                    }
                }

                // Special processing for Entity Type "Workflow" to handle sub-types that are distinguished by WorkflowTypeId.
                if (attribute.EntityTypeId == EntityTypeCache.GetId(typeof(Rock.Model.Workflow)) && attribute.EntityTypeQualifierColumn == "WorkflowTypeId")
                {
                    int workflowTypeId = attribute.EntityTypeQualifierValue.AsInteger();
                    if (_workflowTypeNameLookup == null)
                    {
                        using (var rockContext = new RockContext())
                        {
                            _workflowTypeNameLookup = new WorkflowTypeService(rockContext).Queryable().ToDictionary(k => k.Id, v => v.Name);
                        }
                    }

                    var workflowTypeName = _workflowTypeNameLookup.ContainsKey(workflowTypeId) ? _workflowTypeNameLookup[workflowTypeId] : null;
                    if (workflowTypeName != null)
                    {
                        // Append the Qualifier to the title for Workflow Attributes
                        entityField.AttributeEntityTypeQualifierName = workflowTypeName;
                        entityField.Title = string.Format("({1}) {0} ", attribute.Name, workflowTypeName);
                    }
                }
            }

            return(entityField);
        }
        /// <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 )
        {
            var rockContext = new RockContext();
            var registrationTemplate = new RegistrationTemplateService( rockContext ).Get( hfRegistrationTemplateId.Value.AsInteger() );

            if ( registrationTemplate != null && ( UserCanEdit || registrationTemplate.IsAuthorized( Authorization.ADMINISTRATE, this.CurrentPerson ) ) )
            {
                LoadStateDetails( registrationTemplate, rockContext );
                ShowEditDetails( registrationTemplate, rockContext );
            }
        }
Ejemplo n.º 34
0
        /// <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 )
        {
            var rockContext = new RockContext();
            var RegistrationTemplate = new RegistrationTemplateService( rockContext ).Get( hfRegistrationTemplateId.Value.AsInteger() );

            LoadStateDetails( RegistrationTemplate, rockContext );
            ShowEditDetails( RegistrationTemplate, rockContext );
        }
Ejemplo n.º 35
0
 /// <summary>
 /// Sets the values on select.
 /// </summary>
 protected override void SetValuesOnSelect()
 {
     var registrationTemplates = new RegistrationTemplateService( new RockContext() ).Queryable().Where( g => ItemIds.Contains( g.Id.ToString() ) );
     this.SetValues( registrationTemplates );
 }
        /// <summary>
        /// Applies a discount code to a registration entity
        /// </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>();

            if (entity is Dictionary <string, object> entityDictionary)
            {
                RegistrationInstance registrationInstanceState = ( RegistrationInstance)entityDictionary["RegistrationInstance"];
                RegistrationInfo     registrationState         = ( RegistrationInfo )entityDictionary["RegistrationInfo"];

                if (registrationState != null)
                {
                    registrationState.Registrants.ForEach(r => r.DiscountApplies = true);

                    RegistrationTemplateDiscount discount = null;
                    bool validDiscount = true;

                    string discountCode = GetAttributeValue(action, "DiscountCode", true).ResolveMergeFields(GetMergeFields(action));
                    if (!string.IsNullOrWhiteSpace(discountCode))
                    {
                        // Reload the discounts to make sure we have all the latest ones (workflow can create new codes)
                        RegistrationTemplateService registrationTemplateService = new RegistrationTemplateService(rockContext);
                        registrationInstanceState.RegistrationTemplate.Discounts = registrationTemplateService.Get(registrationInstanceState.RegistrationTemplate.Guid).Discounts;
                        discount = registrationInstanceState.RegistrationTemplate.Discounts
                                   .Where(d => d.Code.Equals(discountCode, StringComparison.OrdinalIgnoreCase))
                                   .FirstOrDefault();

                        if (discount == null)
                        {
                            validDiscount = false;
                            errorMessages.Add(string.Format("'{0}' is not a valid discount code.", discountCode));
                        }

                        if (validDiscount && discount.MinRegistrants.HasValue && registrationState.RegistrantCount < discount.MinRegistrants.Value)
                        {
                            validDiscount = false;
                            errorMessages.Add(string.Format("The '{0}' discount code requires at least {1} registrants.", discountCode, discount.MinRegistrants.Value));
                        }

                        if (validDiscount && discount.StartDate.HasValue && RockDateTime.Today < discount.StartDate.Value)
                        {
                            validDiscount = false;
                            errorMessages.Add(string.Format("The '{0}' discount code is not available yet.", discountCode));
                        }

                        if (validDiscount && discount.EndDate.HasValue && RockDateTime.Today > discount.EndDate.Value)
                        {
                            validDiscount = false;
                            errorMessages.Add(string.Format("The '{0}' discount code has expired.", discountCode));
                        }

                        if (validDiscount && discount.MaxUsage.HasValue && registrationInstanceState != null)
                        {
                            var instances = new RegistrationService(rockContext)
                                            .Queryable().AsNoTracking()
                                            .Where(r =>
                                                   r.RegistrationInstanceId == registrationInstanceState.Id &&
                                                   (!registrationState.RegistrationId.HasValue || r.Id != registrationState.RegistrationId.Value) &&
                                                   r.DiscountCode == discountCode)
                                            .Count();
                            if (instances >= discount.MaxUsage.Value)
                            {
                                validDiscount = false;
                                errorMessages.Add(string.Format("The '{0}' discount code is no longer available.", discountCode));
                            }
                        }

                        if (validDiscount && discount.MaxRegistrants.HasValue)
                        {
                            for (int i = 0; i < registrationState.Registrants.Count; i++)
                            {
                                registrationState.Registrants[i].DiscountApplies = i < discount.MaxRegistrants.Value;
                            }
                        }
                    }
                    else
                    {
                        validDiscount = false;
                    }

                    registrationState.DiscountCode       = validDiscount ? discountCode : string.Empty;
                    registrationState.DiscountPercentage = validDiscount ? discount.DiscountPercentage : 0.0m;
                    registrationState.DiscountAmount     = validDiscount ? discount.DiscountAmount : 0.0m;
                }
            }

            return(true);
        }
Ejemplo n.º 37
0
        /// <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();

                var template = new RegistrationTemplateService(rockContext).Get(_template.Id);

                var waitListCol = gInstances.ColumnsOfType <RockBoundField>().Where(f => f.DataField == "WaitList").First();
                waitListCol.Visible = template != null && template.WaitListEnabled;

                var 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,
                    Registrants = i.Registrations.Where(r => !r.IsTemporary).SelectMany(r => r.Registrants).Where(r => !r.OnWaitList).Count(),
                    WaitList    = i.Registrations.Where(r => !r.IsTemporary).SelectMany(r => r.Registrants).Where(r => r.OnWaitList).Count()
                });

                gInstances.SetLinqDataSource(instanceQry);
                gInstances.DataBind();
            }
            else
            {
                pnlInstances.Visible = false;
            }
        }
Ejemplo n.º 38
0
        /// <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>
        /// 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 )
        {
            string result = "Registrant";
            string[] selectionValues = selection.Split( '|' );
            if ( selectionValues.Length >= 1 )
            {
                var rockContext = new RockContext();
                var registrationTemplateGuids = selectionValues[0].Split( ',' ).AsGuidList();
                var registrationTemplates = new RegistrationTemplateService( rockContext ).GetByGuids( registrationTemplateGuids );

                SlidingDateRangePicker fakeSlidingDateRangePicker = null;

                bool includeInactiveRegistrationInstances = false;
                if ( selectionValues.Length >= 2 )
                {
                    includeInactiveRegistrationInstances = selectionValues[1].AsBooleanOrNull() ?? false;

                    if ( selectionValues.Length >= 3 )
                    {
                        fakeSlidingDateRangePicker = new SlidingDateRangePicker();

                        // convert comma delimited to pipe
                        fakeSlidingDateRangePicker.DelimitedValues = selectionValues[2].Replace( ',', '|' );
                    }
                }

                if ( registrationTemplates != null )
                {
                    result = string.Format( registrationTemplates.Count() > 0 ? "In Registration Templates: {0}" : "In a Registration", registrationTemplates.Select( a => a.Name ).ToList().AsDelimited( ", ", " or " ) );

                    if ( includeInactiveRegistrationInstances )
                    {
                        result += ", including inactive registration instances";
                    }

                    if ( fakeSlidingDateRangePicker != null )
                    {
                        result += string.Format( ", registered in Date Range: {0}", SlidingDateRangePicker.FormatDelimitedValues( fakeSlidingDateRangePicker.DelimitedValues ) );
                    }
                }
            }

            return result;
        }
Ejemplo n.º 40
0
        private void ShowNewLinkageDialog()
        {
            rieNewLinkage.ShowActive  = false;
            rieNewLinkage.ShowUrlSlug = true;

            ddlNewLinkageTemplate.Items.Clear();

            using (var rockContext = new RockContext())
            {
                // Find most recent mapping with same event, campus and copy some of it's registration instance values
                int EventItemId          = PageParameter("EventItemId").AsInteger();
                int?campusId             = ddlCampus.SelectedValueAsInt();
                var registrationInstance = new EventItemOccurrenceGroupMapService(rockContext)
                                           .Queryable()
                                           .Where(m =>
                                                  m.EventItemOccurrence != null &&
                                                  m.EventItemOccurrence.EventItemId == EventItemId &&
                                                  m.RegistrationInstance != null &&
                                                  (
                                                      (campusId.HasValue && (!m.EventItemOccurrence.CampusId.HasValue || m.EventItemOccurrence.CampusId.Value == campusId.Value)) ||
                                                      (!campusId.HasValue && !m.EventItemOccurrence.CampusId.HasValue)
                                                  )
                                                  )
                                           .ToList()
                                           .OrderByDescending(m => m.EventItemOccurrence.NextStartDateTime)
                                           .Select(m => m.RegistrationInstance)
                                           .FirstOrDefault();

                if (registrationInstance != null)
                {
                    LinkageState.RegistrationInstance           = new RegistrationInstance();
                    LinkageState.RegistrationInstance.AccountId = registrationInstance.AccountId;
                    LinkageState.RegistrationInstance.RegistrationTemplateId        = registrationInstance.RegistrationTemplateId;
                    LinkageState.RegistrationInstance.RegistrationTemplate          = new RegistrationTemplate();
                    LinkageState.RegistrationInstance.ContactPersonAliasId          = registrationInstance.ContactPersonAliasId;
                    LinkageState.RegistrationInstance.ContactPhone                  = registrationInstance.ContactPhone;
                    LinkageState.RegistrationInstance.ContactEmail                  = registrationInstance.ContactEmail;
                    LinkageState.RegistrationInstance.AdditionalReminderDetails     = registrationInstance.AdditionalReminderDetails;
                    LinkageState.RegistrationInstance.AdditionalConfirmationDetails = registrationInstance.AdditionalConfirmationDetails;
                    var registrationTemplate = new RegistrationTemplateService(rockContext).Get(registrationInstance.RegistrationTemplateId);
                    if (registrationTemplate != null)
                    {
                        LinkageState.RegistrationInstance.RegistrationTemplate.CopyPropertiesFrom(registrationTemplate);
                    }
                }

                foreach (var template in new RegistrationTemplateService(rockContext)
                         .Queryable().AsNoTracking().OrderBy(t => t.Name))
                {
                    if (template.IsAuthorized(Authorization.VIEW, CurrentPerson))
                    {
                        ListItem li = new ListItem(template.Name, template.Id.ToString());
                        ddlNewLinkageTemplate.Items.Add(li);
                        li.Selected = LinkageState.RegistrationInstance != null &&
                                      LinkageState.RegistrationInstance.RegistrationTemplateId == template.Id;
                    }
                }

                gpNewLinkageGroup.SetValue(LinkageState.Group);

                rieNewLinkage.SetValue(LinkageState.RegistrationInstance);
                rieNewLinkage.UrlSlug = LinkageState.UrlSlug;

                if (LinkageState.RegistrationInstance == null)
                {
                    var contactPersonAliasId = ppContact.PersonAliasId;
                    if (contactPersonAliasId.HasValue)
                    {
                        var personAlias = new PersonAliasService(rockContext).Get(contactPersonAliasId.Value);
                        if (personAlias != null)
                        {
                            rieNewLinkage.ContactPersonAlias = personAlias;
                        }
                    }

                    if (!string.IsNullOrWhiteSpace(pnPhone.Text))
                    {
                        rieNewLinkage.ContactPhone = pnPhone.Text;
                    }

                    if (!string.IsNullOrWhiteSpace(tbEmail.Text))
                    {
                        rieNewLinkage.ContactEmail = tbEmail.Text;
                    }

                    Guid?accountGuid = GetAttributeValue("DefaultAccount").AsGuidOrNull();
                    if (accountGuid.HasValue)
                    {
                        var account = new FinancialAccountService(rockContext).Get(accountGuid.Value);
                        rieNewLinkage.AccountId = account != null ? account.Id : 0;
                    }
                }
            }

            ShowDialog("EventItemNewLinkage", true);
        }
        private void ShowNewLinkageDialog()
        {
            rieNewLinkage.ShowActive = false;
            rieNewLinkage.ShowUrlSlug = true;

            ddlNewLinkageTemplate.Items.Clear();

            using ( var rockContext = new RockContext() )
            {
                // Find most recent mapping with same event, campus and copy some of it's registration instance values
                int EventItemId = PageParameter( "EventItemId" ).AsInteger();
                int? campusId = ddlCampus.SelectedValueAsInt();
                var registrationInstance = new EventItemOccurrenceGroupMapService( rockContext )
                    .Queryable()
                    .Where( m =>
                        m.EventItemOccurrence != null &&
                        m.EventItemOccurrence.EventItemId == EventItemId &&
                        m.RegistrationInstance != null &&
                        (
                            ( campusId.HasValue && ( !m.EventItemOccurrence.CampusId.HasValue || m.EventItemOccurrence.CampusId.Value == campusId.Value ) ) ||
                            ( !campusId.HasValue && !m.EventItemOccurrence.CampusId.HasValue )
                        )
                    )
                    .ToList()
                    .OrderByDescending( m => m.EventItemOccurrence.NextStartDateTime )
                    .Select( m => m.RegistrationInstance )
                    .FirstOrDefault();

                if ( registrationInstance != null )
                {
                    LinkageState.RegistrationInstance = new RegistrationInstance();
                    LinkageState.RegistrationInstance.AccountId = registrationInstance.AccountId;
                    LinkageState.RegistrationInstance.RegistrationTemplateId = registrationInstance.RegistrationTemplateId;
                    LinkageState.RegistrationInstance.RegistrationTemplate = new RegistrationTemplate();
                    LinkageState.RegistrationInstance.ContactPersonAliasId = registrationInstance.ContactPersonAliasId;
                    LinkageState.RegistrationInstance.ContactPhone = registrationInstance.ContactPhone;
                    LinkageState.RegistrationInstance.ContactEmail = registrationInstance.ContactEmail;
                    LinkageState.RegistrationInstance.AdditionalReminderDetails = registrationInstance.AdditionalReminderDetails;
                    LinkageState.RegistrationInstance.AdditionalConfirmationDetails = registrationInstance.AdditionalConfirmationDetails;
                    var registrationTemplate = new RegistrationTemplateService( rockContext ).Get( registrationInstance.RegistrationTemplateId );
                    if ( registrationTemplate != null )
                    {
                        LinkageState.RegistrationInstance.RegistrationTemplate.CopyPropertiesFrom( registrationTemplate );
                    }
                }

                foreach ( var template in new RegistrationTemplateService( rockContext )
                    .Queryable().AsNoTracking().OrderBy(t => t.Name ))
                {
                    if ( template.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                    {
                        ListItem li = new ListItem( template.Name, template.Id.ToString() );
                        ddlNewLinkageTemplate.Items.Add( li );
                        li.Selected = LinkageState.RegistrationInstance != null &&
                            LinkageState.RegistrationInstance.RegistrationTemplateId == template.Id;
                    }
                }

                gpNewLinkageGroup.SetValue( LinkageState.Group );

                rieNewLinkage.SetValue( LinkageState.RegistrationInstance );
                rieNewLinkage.UrlSlug = LinkageState.UrlSlug;

                if ( LinkageState.RegistrationInstance == null )
                {
                    var contactPersonAliasId = ppContact.PersonAliasId;
                    if ( contactPersonAliasId.HasValue )
                    {
                        var personAlias = new PersonAliasService( rockContext ).Get( contactPersonAliasId.Value );
                        if ( personAlias != null )
                        {
                            rieNewLinkage.ContactPersonAlias = personAlias;
                        }
                    }

                    if ( !string.IsNullOrWhiteSpace( pnPhone.Text))
                    {
                        rieNewLinkage.ContactPhone = pnPhone.Text;
                    }

                    if ( !string.IsNullOrWhiteSpace( tbEmail.Text ) )
                    {
                        rieNewLinkage.ContactEmail = tbEmail.Text;
                    }

                    Guid? accountGuid = GetAttributeValue( "DefaultAccount" ).AsGuidOrNull();
                    if ( accountGuid.HasValue )
                    {
                        var account = new FinancialAccountService( rockContext ).Get( accountGuid.Value );
                        rieNewLinkage.AccountId = account != null ? account.Id : 0;
                    }

                }
            }

            ShowDialog( "EventItemNewLinkage", true );
        }
Ejemplo n.º 42
0
        /// <summary>
        /// Sets the values on select.
        /// </summary>
        protected override void SetValuesOnSelect()
        {
            var registrationTemplates = new RegistrationTemplateService(new RockContext()).Queryable().Where(g => ItemIds.Contains(g.Id.ToString()));

            this.SetValues(registrationTemplates);
        }
        protected void ddlNewLinkageTemplate_SelectedIndexChanged( object sender, EventArgs e )
        {
            int? registrationTemplateId = ddlNewLinkageTemplate.SelectedValueAsInt();
            if ( registrationTemplateId.HasValue )
            {
                var rockContext = new RockContext();

                if ( LinkageState.RegistrationInstance == null )
                {
                    LinkageState.RegistrationInstance = new RegistrationInstance();
                    LinkageState.RegistrationInstance.IsActive = true;
                }

                LinkageState.RegistrationInstance.RegistrationTemplateId = registrationTemplateId.Value;
                if ( LinkageState.RegistrationInstance.RegistrationTemplate == null )
                {
                    LinkageState.RegistrationInstance.RegistrationTemplate = new RegistrationTemplate();
                }

                var registrationTemplate = new RegistrationTemplateService( rockContext ).Get( registrationTemplateId.Value );
                if ( registrationTemplate != null )
                {
                    LinkageState.RegistrationInstance.RegistrationTemplate.CopyPropertiesFrom( registrationTemplate );
                }

                rieNewLinkage.GetValue( LinkageState.RegistrationInstance );
                rieNewLinkage.SetValue( LinkageState.RegistrationInstance );
            }
        }
        /// <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 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 dlgNewLinkage_SaveClick( object sender, EventArgs e )
        {
            int? registrationTemplateId = ddlNewLinkageTemplate.SelectedValueAsInt();
            if ( registrationTemplateId.HasValue )
            {
                var rockContext = new RockContext();

                if ( LinkageState.RegistrationInstance == null )
                {
                    LinkageState.RegistrationInstance = new RegistrationInstance();
                    LinkageState.RegistrationInstance.IsActive = true;
                }

                LinkageState.RegistrationInstance.RegistrationTemplateId = registrationTemplateId.Value;
                if ( LinkageState.RegistrationInstance.RegistrationTemplate == null )
                {
                    LinkageState.RegistrationInstance.RegistrationTemplate = new RegistrationTemplate();
                }

                var registrationTemplate = new RegistrationTemplateService( rockContext ).Get( registrationTemplateId.Value );
                if ( registrationTemplate != null )
                {
                    LinkageState.RegistrationInstance.RegistrationTemplate.CopyPropertiesFrom( registrationTemplate );
                }

                rieNewLinkage.GetValue( LinkageState.RegistrationInstance );

                int? groupId = gpNewLinkageGroup.SelectedValueAsInt();
                if ( groupId.HasValue )
                {
                    var group = new GroupService( rockContext ).Get( groupId.Value );
                    if ( group != null )
                    {
                        LinkageState.GroupId = group.Id;
                        LinkageState.Group = group;
                    }
                }

                LinkageState.PublicName = rieNewLinkage.Name;
                LinkageState.UrlSlug = rieNewLinkage.UrlSlug;

                // 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 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 ( hfRegistrationTemplateId.Value.Equals( "0" ) )
     {
         int? parentCategoryId = PageParameter( "ParentCategoryId" ).AsIntegerOrNull();
         if ( parentCategoryId.HasValue )
         {
             // Cancelling on Add, and we know the parentCategoryId, so we are probably in treeview mode, so navigate to the current page
             var qryParams = new Dictionary<string, string>();
             qryParams["CategoryId"] = parentCategoryId.ToString();
             NavigateToPage( RockPage.Guid, qryParams );
         }
         else
         {
             // Cancelling on Add.  Return to Grid
             NavigateToParentPage();
         }
     }
     else
     {
         // Cancelling on Edit.  Return to Details
         RegistrationTemplateService service = new RegistrationTemplateService( new RockContext() );
         RegistrationTemplate item = service.Get( int.Parse( hfRegistrationTemplateId.Value ) );
         ShowReadonlyDetails( item );
     }
 }
Ejemplo n.º 47
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            ParseControls( true );

            var rockContext = new RockContext();
            var service = new RegistrationTemplateService( rockContext );

            RegistrationTemplate RegistrationTemplate = null;

            int? RegistrationTemplateId = hfRegistrationTemplateId.Value.AsIntegerOrNull();
            if ( RegistrationTemplateId.HasValue )
            {
                RegistrationTemplate = service.Get( RegistrationTemplateId.Value );
            }

            if ( RegistrationTemplate == null )
            {
                RegistrationTemplate = new RegistrationTemplate();
            }

            RegistrationNotify notify = RegistrationNotify.None;
            foreach( ListItem li in cblNotify.Items )
            {
                if ( li.Selected )
                {
                    notify = notify | (RegistrationNotify)li.Value.AsInteger();
                }
            }

            RegistrationTemplate.IsActive = cbIsActive.Checked;
            RegistrationTemplate.Name = tbName.Text;
            RegistrationTemplate.CategoryId = cpCategory.SelectedValueAsInt();
            RegistrationTemplate.GroupTypeId = gtpGroupType.SelectedGroupTypeId;
            RegistrationTemplate.GroupMemberRoleId = rpGroupTypeRole.GroupRoleId;
            RegistrationTemplate.GroupMemberStatus = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>();
            RegistrationTemplate.Notify = notify;
            RegistrationTemplate.LoginRequired = cbLoginRequired.Checked;
            RegistrationTemplate.AllowMultipleRegistrants = cbMultipleRegistrants.Checked;
            RegistrationTemplate.MaxRegistrants = nbMaxRegistrants.Text.AsInteger();
            RegistrationTemplate.RegistrantsSameFamily = rblRegistrantsInSameFamily.SelectedValueAsEnum<RegistrantsSameFamily>();
            RegistrationTemplate.Cost = cbCost.Text.AsDecimal();
            RegistrationTemplate.MinimumInitialPayment = cbMinimumInitialPayment.Text.AsDecimalOrNull();
            RegistrationTemplate.FinancialGatewayId = fgpFinancialGateway.SelectedValueAsInt();

            RegistrationTemplate.ConfirmationFromName = tbConfirmationFromName.Text;
            RegistrationTemplate.ConfirmationFromEmail = tbConfirmationFromEmail.Text;
            RegistrationTemplate.ConfirmationSubject = tbConfirmationSubject.Text;
            RegistrationTemplate.ConfirmationEmailTemplate = ceConfirmationEmailTemplate.Text;

            RegistrationTemplate.ReminderFromName = tbReminderFromName.Text;
            RegistrationTemplate.ReminderFromEmail = tbReminderFromEmail.Text;
            RegistrationTemplate.ReminderSubject = tbReminderSubject.Text;
            RegistrationTemplate.ReminderEmailTemplate = ceReminderEmailTemplate.Text;

            RegistrationTemplate.RegistrationTerm = string.IsNullOrWhiteSpace( tbRegistrationTerm.Text ) ? "Registration" : tbRegistrationTerm.Text;
            RegistrationTemplate.RegistrantTerm = string.IsNullOrWhiteSpace( tbRegistrantTerm.Text ) ? "Registrant" : tbRegistrantTerm.Text;
            RegistrationTemplate.FeeTerm = string.IsNullOrWhiteSpace( tbFeeTerm.Text ) ? "Additional Options" : tbFeeTerm.Text;
            RegistrationTemplate.DiscountCodeTerm = string.IsNullOrWhiteSpace( tbDiscountCodeTerm.Text ) ? "Discount Code" : tbDiscountCodeTerm.Text;
            RegistrationTemplate.SuccessTitle = tbSuccessTitle.Text;
            RegistrationTemplate.SuccessText = ceSuccessText.Text;

            if ( !Page.IsValid || !RegistrationTemplate.IsValid )
            {
                return;
            }

            foreach ( var form in FormState )
            {
                if ( !form.IsValid )
                {
                    return;
                }

                if ( FormFieldsState.ContainsKey( form.Guid ) )
                {
                    foreach( var formField in FormFieldsState[ form.Guid ])
                    {
                        if ( !formField.IsValid )
                        {
                            return;
                        }
                    }
                }
            }

            // Get the valid group member attributes
            var group = new Group();
            group.GroupTypeId = gtpGroupType.SelectedGroupTypeId ?? 0;
            var groupMember = new GroupMember();
            groupMember.Group = group;
            groupMember.LoadAttributes();
            var validGroupMemberAttributeIds = groupMember.Attributes.Select( a => a.Value.Id ).ToList();

            // Remove any group member attributes that are not valid based on selected group type
            foreach( var fieldList in FormFieldsState.Select( s => s.Value ) )
            {
                foreach( var formField in fieldList
                    .Where( a =>
                        a.FieldSource == RegistrationFieldSource.GroupMemberAttribute &&
                        a.AttributeId.HasValue &&
                        !validGroupMemberAttributeIds.Contains( a.AttributeId.Value ) )
                    .ToList() )
                {
                    fieldList.Remove( formField );
                }
            }

            // Perform Validation
            var validationErrors = new List<string>();
            if ( ( RegistrationTemplate.Cost > 0 || FeeState.Any() ) && !RegistrationTemplate.FinancialGatewayId.HasValue )
            {
                validationErrors.Add( "A Financial Gateway is required when the registration has a cost or additional fees." );
            }

            if ( validationErrors.Any() )
            {
                nbValidationError.Visible = true;
                nbValidationError.Text = "<ul class='list-unstyled'><li>" + validationErrors.AsDelimited( "</li><li>" ) + "</li></ul>";
            }
            else
            {
                rockContext.WrapTransaction( () =>
                {
                    // Save the entity field changes to registration template
                    if ( RegistrationTemplate.Id.Equals( 0 ) )
                    {
                        service.Add( RegistrationTemplate );
                    }
                    rockContext.SaveChanges();

                    var attributeService = new AttributeService( rockContext );
                    var registrationTemplateFormService = new RegistrationTemplateFormService( rockContext );
                    var registrationTemplateFormFieldService = new RegistrationTemplateFormFieldService( rockContext );
                    var registrationTemplateDiscountService = new RegistrationTemplateDiscountService( rockContext );
                    var registrationTemplateFeeService = new RegistrationTemplateFeeService( rockContext );

                    // delete forms that aren't assigned in the UI anymore
                    var formUiGuids = FormState.Select( f => f.Guid ).ToList();
                    foreach ( var form in registrationTemplateFormService
                        .Queryable()
                        .Where( f =>
                            f.RegistrationTemplateId == RegistrationTemplate.Id &&
                            !formUiGuids.Contains( f.Guid ) ) )
                    {
                        registrationTemplateFormService.Delete( form );
                    }

                    // delete discounts that aren't assigned in the UI anymore
                    var discountUiGuids = DiscountState.Select( u => u.Guid ).ToList();
                    foreach ( var discount in registrationTemplateDiscountService
                        .Queryable()
                        .Where( d =>
                            d.RegistrationTemplateId == RegistrationTemplate.Id &&
                            !discountUiGuids.Contains( d.Guid ) ) )
                    {
                        registrationTemplateDiscountService.Delete( discount );
                    }

                    // delete fees that aren't assigned in the UI anymore
                    var feeUiGuids = FeeState.Select( u => u.Guid ).ToList();
                    foreach ( var fee in registrationTemplateFeeService
                        .Queryable()
                        .Where( d =>
                            d.RegistrationTemplateId == RegistrationTemplate.Id &&
                            !feeUiGuids.Contains( d.Guid ) ) )
                    {
                        registrationTemplateFeeService.Delete( fee );
                    }

                    var attributesUI = FormFieldsState
                        .SelectMany( s =>
                            s.Value.Where( a =>
                                a.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                                a.Attribute != null ) )
                        .Select( f => f.Attribute );

                    int? entityTypeId = EntityTypeCache.Read( typeof( Rock.Model.RegistrationRegistrant ) ).Id;
                    var qualifierColumn = "RegistrationTemplateId";
                    var qualifierValue = RegistrationTemplate.Id.ToString();

                    // Get the existing registration attributes for this entity type and qualifier value
                    var attributesDB = attributeService.Get( entityTypeId, qualifierColumn, qualifierValue );

                    // Delete any of the registration attributes that were removed in the UI
                    var selectedAttributeGuids = attributesUI.Select( a => a.Guid );
                    foreach ( var attr in attributesDB.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ) )
                    {
                        attributeService.Delete( attr );
                        rockContext.SaveChanges();
                        Rock.Web.Cache.AttributeCache.Flush( attr.Id );
                    }

                    // Update the registration attributes that were assigned in the UI
                    foreach ( var attr in attributesUI )
                    {
                        Helper.SaveAttributeEdits( attr, entityTypeId, qualifierColumn, qualifierValue, rockContext );
                    }

                    // add/updated forms/fields
                    foreach ( var formUI in FormState )
                    {
                        var form = RegistrationTemplate.Forms.FirstOrDefault( f => f.Guid.Equals( formUI.Guid ) );
                        if ( form == null )
                        {
                            form = new RegistrationTemplateForm();
                            form.Guid = formUI.Guid;
                            RegistrationTemplate.Forms.Add( form );
                        }
                        form.Name = formUI.Name;
                        form.Order = formUI.Order;

                        if ( FormFieldsState.ContainsKey( form.Guid ) )
                        {
                            var fieldUiGuids = FormFieldsState[form.Guid].Select( a => a.Guid ).ToList();
                            foreach ( var formField in registrationTemplateFormFieldService
                                .Queryable()
                                .Where( a =>
                                    a.RegistrationTemplateForm.Guid.Equals( form.Guid ) &&
                                    !fieldUiGuids.Contains( a.Guid ) ) )
                            {
                                registrationTemplateFormFieldService.Delete( formField );
                            }

                            foreach ( var formFieldUI in FormFieldsState[form.Guid] )
                            {
                                var formField = form.Fields.FirstOrDefault( a => a.Guid.Equals( formFieldUI.Guid ) );
                                if ( formField == null )
                                {
                                    formField = new RegistrationTemplateFormField();
                                    formField.Guid = formFieldUI.Guid;
                                    form.Fields.Add( formField );
                                }

                                formField.AttributeId = formFieldUI.AttributeId;
                                if ( !formField.AttributeId.HasValue &&
                                    formFieldUI.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                                    formFieldUI.Attribute != null )
                                {
                                    var attr = AttributeCache.Read( formFieldUI.Attribute.Guid, rockContext );
                                    if ( attr != null )
                                    {
                                        formField.AttributeId = attr.Id;
                                    }
                                }

                                formField.FieldSource = formFieldUI.FieldSource;
                                formField.PersonFieldType = formFieldUI.PersonFieldType;
                                formField.IsSharedValue = formFieldUI.IsSharedValue;
                                formField.ShowCurrentValue = formFieldUI.ShowCurrentValue;
                                formField.PreText = formFieldUI.PreText;
                                formField.PostText = formFieldUI.PostText;
                                formField.IsGridField = formFieldUI.IsGridField;
                                formField.IsRequired = formFieldUI.IsRequired;
                                formField.Order = formFieldUI.Order;
                            }
                        }
                    }

                    // add/updated discounts
                    foreach ( var discountUI in DiscountState )
                    {
                        var discount = RegistrationTemplate.Discounts.FirstOrDefault( a => a.Guid.Equals( discountUI.Guid ) );
                        if ( discount == null )
                        {
                            discount = new RegistrationTemplateDiscount();
                            discount.Guid = discountUI.Guid;
                            RegistrationTemplate.Discounts.Add( discount );
                        }
                        discount.Code = discountUI.Code;
                        discount.DiscountPercentage = discountUI.DiscountPercentage;
                        discount.DiscountAmount = discountUI.DiscountAmount;
                        discount.Order = discountUI.Order;
                    }

                    // add/updated fees
                    foreach ( var feeUI in FeeState )
                    {
                        var fee = RegistrationTemplate.Fees.FirstOrDefault( a => a.Guid.Equals( feeUI.Guid ) );
                        if ( fee == null )
                        {
                            fee = new RegistrationTemplateFee();
                            fee.Guid = feeUI.Guid;
                            RegistrationTemplate.Fees.Add( fee );
                        }
                        fee.Name = feeUI.Name;
                        fee.FeeType = feeUI.FeeType;
                        fee.CostValue = feeUI.CostValue;
                        fee.DiscountApplies = feeUI.DiscountApplies;
                        fee.AllowMultiple = feeUI.AllowMultiple;
                        fee.Order = feeUI.Order;
                    }

                    rockContext.SaveChanges();

                } );

                var qryParams = new Dictionary<string, string>();
                qryParams["RegistrationTemplateId"] = RegistrationTemplate.Id.ToString();
                NavigateToPage( RockPage.Guid, qryParams );
            }
        }
        /// <summary>
        /// Handles the Click event of the 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 )
        {
            var rockContext = new RockContext();

            var service = new RegistrationTemplateService( rockContext );
            var registrationTemplate = service.Get( hfRegistrationTemplateId.Value.AsInteger() );

            if ( registrationTemplate != null )
            {
                if ( !UserCanEdit && !registrationTemplate.IsAuthorized( Authorization.ADMINISTRATE, this.CurrentPerson ) )
                {
                    mdDeleteWarning.Show( "You are not authorized to delete this registration template.", ModalAlertType.Information );
                    return;
                }

                rockContext.WrapTransaction( () =>
                {
                    new RegistrationService( rockContext ).DeleteRange( registrationTemplate.Instances.SelectMany( i => i.Registrations ) );
                    new RegistrationInstanceService( rockContext ).DeleteRange( registrationTemplate.Instances );
                    service.Delete( registrationTemplate );
                    rockContext.SaveChanges();
                } );
            }

            // reload page
            var qryParams = new Dictionary<string, string>();
            NavigateToPage( RockPage.Guid, qryParams );
        }
Ejemplo n.º 49
0
        /// <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();

                var template = new RegistrationTemplateService( rockContext ).Get( _template.Id );

                var waitListCol = gInstances.ColumnsOfType<RockBoundField>().Where( f => f.DataField == "WaitList" ).First();
                waitListCol.Visible = template != null && template.WaitListEnabled;

                var 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.Where( r => !r.IsTemporary ).SelectMany( r => r.Registrants ).Where( r => !r.OnWaitList ).Count(),
                    WaitList = i.Registrations.Where( r => !r.IsTemporary ).SelectMany( r => r.Registrants ).Where( r => r.OnWaitList ).Count()
                } );

                gInstances.SetLinqDataSource( instanceQry );
                gInstances.DataBind();
            }
            else
            {
                pnlInstances.Visible = false;
            }
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click( object sender, EventArgs e )
        {
            ParseControls( true );

            var rockContext = new RockContext();
            var service = new RegistrationTemplateService( rockContext );

            RegistrationTemplate RegistrationTemplate = null;

            int? RegistrationTemplateId = hfRegistrationTemplateId.Value.AsIntegerOrNull();
            if ( RegistrationTemplateId.HasValue )
            {
                RegistrationTemplate = service.Get( RegistrationTemplateId.Value );
            }

            bool newTemplate = false;
            if ( RegistrationTemplate == null )
            {
                newTemplate = true;
                RegistrationTemplate = new RegistrationTemplate();
            }

            RegistrationNotify notify = RegistrationNotify.None;
            foreach( ListItem li in cblNotify.Items )
            {
                if ( li.Selected )
                {
                    notify = notify | (RegistrationNotify)li.Value.AsInteger();
                }
            }

            RegistrationTemplate.IsActive = cbIsActive.Checked;
            RegistrationTemplate.Name = tbName.Text;
            RegistrationTemplate.CategoryId = cpCategory.SelectedValueAsInt();
            RegistrationTemplate.GroupTypeId = gtpGroupType.SelectedGroupTypeId;
            RegistrationTemplate.GroupMemberRoleId = rpGroupTypeRole.GroupRoleId;
            RegistrationTemplate.GroupMemberStatus = ddlGroupMemberStatus.SelectedValueAsEnum<GroupMemberStatus>();
            RegistrationTemplate.RequiredSignatureDocumentTemplateId = ddlSignatureDocumentTemplate.SelectedValueAsInt();
            RegistrationTemplate.SignatureDocumentAction = cbDisplayInLine.Checked ? SignatureDocumentAction.Embed : SignatureDocumentAction.Email;

            RegistrationTemplate.RegistrationWorkflowTypeId = wtpRegistrationWorkflow.SelectedValueAsInt();
            RegistrationTemplate.Notify = notify;
            RegistrationTemplate.AddPersonNote = cbAddPersonNote.Checked;
            RegistrationTemplate.LoginRequired = cbLoginRequired.Checked;
            RegistrationTemplate.AllowExternalRegistrationUpdates = cbAllowExternalUpdates.Checked;
            RegistrationTemplate.AllowGroupPlacement = cbAllowGroupPlacement.Checked;
            RegistrationTemplate.AllowMultipleRegistrants = cbMultipleRegistrants.Checked;
            RegistrationTemplate.MaxRegistrants = nbMaxRegistrants.Text.AsInteger();
            RegistrationTemplate.RegistrantsSameFamily = rblRegistrantsInSameFamily.SelectedValueAsEnum<RegistrantsSameFamily>();
            RegistrationTemplate.ShowCurrentFamilyMembers = cbShowCurrentFamilyMembers.Checked;
            RegistrationTemplate.SetCostOnInstance = !tglSetCostOnTemplate.Checked;
            RegistrationTemplate.Cost = cbCost.Text.AsDecimal();
            RegistrationTemplate.MinimumInitialPayment = cbMinimumInitialPayment.Text.AsDecimalOrNull();
            RegistrationTemplate.FinancialGatewayId = fgpFinancialGateway.SelectedValueAsInt();
            RegistrationTemplate.BatchNamePrefix = txtBatchNamePrefix.Text;

            RegistrationTemplate.ConfirmationFromName = tbConfirmationFromName.Text;
            RegistrationTemplate.ConfirmationFromEmail = tbConfirmationFromEmail.Text;
            RegistrationTemplate.ConfirmationSubject = tbConfirmationSubject.Text;
            RegistrationTemplate.ConfirmationEmailTemplate = ceConfirmationEmailTemplate.Text;

            RegistrationTemplate.ReminderFromName = tbReminderFromName.Text;
            RegistrationTemplate.ReminderFromEmail = tbReminderFromEmail.Text;
            RegistrationTemplate.ReminderSubject = tbReminderSubject.Text;
            RegistrationTemplate.ReminderEmailTemplate = ceReminderEmailTemplate.Text;

            RegistrationTemplate.PaymentReminderFromName = tbPaymentReminderFromName.Text;
            RegistrationTemplate.PaymentReminderFromEmail = tbPaymentReminderFromEmail.Text;
            RegistrationTemplate.PaymentReminderSubject = tbPaymentReminderSubject.Text;
            RegistrationTemplate.PaymentReminderEmailTemplate = cePaymentReminderEmailTemplate.Text;
            RegistrationTemplate.PaymentReminderTimeSpan = nbPaymentReminderTimeSpan.Text.AsInteger();

            RegistrationTemplate.RegistrationTerm = string.IsNullOrWhiteSpace( tbRegistrationTerm.Text ) ? "Registration" : tbRegistrationTerm.Text;
            RegistrationTemplate.RegistrantTerm = string.IsNullOrWhiteSpace( tbRegistrantTerm.Text ) ? "Registrant" : tbRegistrantTerm.Text;
            RegistrationTemplate.FeeTerm = string.IsNullOrWhiteSpace( tbFeeTerm.Text ) ? "Additional Options" : tbFeeTerm.Text;
            RegistrationTemplate.DiscountCodeTerm = string.IsNullOrWhiteSpace( tbDiscountCodeTerm.Text ) ? "Discount Code" : tbDiscountCodeTerm.Text;
            RegistrationTemplate.SuccessTitle = tbSuccessTitle.Text;
            RegistrationTemplate.SuccessText = ceSuccessText.Text;

            if ( !Page.IsValid || !RegistrationTemplate.IsValid )
            {
                return;
            }

            foreach ( var form in FormState )
            {
                if ( !form.IsValid )
                {
                    return;
                }

                if ( FormFieldsState.ContainsKey( form.Guid ) )
                {
                    foreach( var formField in FormFieldsState[ form.Guid ])
                    {
                        if ( !formField.IsValid )
                        {
                            return;
                        }
                    }
                }
            }

            // Get the valid group member attributes
            var group = new Group();
            group.GroupTypeId = gtpGroupType.SelectedGroupTypeId ?? 0;
            var groupMember = new GroupMember();
            groupMember.Group = group;
            groupMember.LoadAttributes();
            var validGroupMemberAttributeIds = groupMember.Attributes.Select( a => a.Value.Id ).ToList();

            // Remove any group member attributes that are not valid based on selected group type
            foreach( var fieldList in FormFieldsState.Select( s => s.Value ) )
            {
                foreach( var formField in fieldList
                    .Where( a =>
                        a.FieldSource == RegistrationFieldSource.GroupMemberAttribute &&
                        a.AttributeId.HasValue &&
                        !validGroupMemberAttributeIds.Contains( a.AttributeId.Value ) )
                    .ToList() )
                {
                    fieldList.Remove( formField );
                }
            }

            // Perform Validation
            var validationErrors = new List<string>();
            if ( ( ( RegistrationTemplate.SetCostOnInstance ?? false ) || RegistrationTemplate.Cost > 0 || FeeState.Any() ) && !RegistrationTemplate.FinancialGatewayId.HasValue )
            {
                validationErrors.Add( "A Financial Gateway is required when the registration has a cost or additional fees or is configured to allow instances to set a cost." );
            }

            if ( validationErrors.Any() )
            {
                nbValidationError.Visible = true;
                nbValidationError.Text = "<ul class='list-unstyled'><li>" + validationErrors.AsDelimited( "</li><li>" ) + "</li></ul>";
            }
            else
            {
                // Save the entity field changes to registration template
                if ( RegistrationTemplate.Id.Equals( 0 ) )
                {
                    service.Add( RegistrationTemplate );
                }
                rockContext.SaveChanges();

                var attributeService = new AttributeService( rockContext );
                var registrationTemplateFormService = new RegistrationTemplateFormService( rockContext );
                var registrationTemplateFormFieldService = new RegistrationTemplateFormFieldService( rockContext );
                var registrationTemplateDiscountService = new RegistrationTemplateDiscountService( rockContext );
                var registrationTemplateFeeService = new RegistrationTemplateFeeService( rockContext );
                var registrationRegistrantFeeService = new RegistrationRegistrantFeeService( rockContext );

                var groupService = new GroupService( rockContext );

                // delete forms that aren't assigned in the UI anymore
                var formUiGuids = FormState.Select( f => f.Guid ).ToList();
                foreach ( var form in registrationTemplateFormService
                    .Queryable()
                    .Where( f =>
                        f.RegistrationTemplateId == RegistrationTemplate.Id &&
                        !formUiGuids.Contains( f.Guid ) ) )
                {
                    foreach( var formField in form.Fields.ToList() )
                    {
                        form.Fields.Remove( formField );
                        registrationTemplateFormFieldService.Delete( formField );
                    }
                    registrationTemplateFormService.Delete( form );
                }

                // delete fields that aren't assigned in the UI anymore
                var fieldUiGuids = FormFieldsState.SelectMany( a => a.Value).Select( f => f.Guid ).ToList();
                foreach ( var formField in registrationTemplateFormFieldService
                    .Queryable()
                    .Where( a =>
                        formUiGuids.Contains( a.RegistrationTemplateForm.Guid ) &&
                        !fieldUiGuids.Contains( a.Guid ) ) )
                {
                    registrationTemplateFormFieldService.Delete( formField );
                }

                // delete discounts that aren't assigned in the UI anymore
                var discountUiGuids = DiscountState.Select( u => u.Guid ).ToList();
                foreach ( var discount in registrationTemplateDiscountService
                    .Queryable()
                    .Where( d =>
                        d.RegistrationTemplateId == RegistrationTemplate.Id &&
                        !discountUiGuids.Contains( d.Guid ) ) )
                {
                    registrationTemplateDiscountService.Delete( discount );
                }

                // delete fees that aren't assigned in the UI anymore
                var feeUiGuids = FeeState.Select( u => u.Guid ).ToList();
                var deletedfees = registrationTemplateFeeService
                    .Queryable()
                    .Where( d =>
                        d.RegistrationTemplateId == RegistrationTemplate.Id &&
                        !feeUiGuids.Contains( d.Guid ) )
                    .ToList();

                var deletedFeeIds = deletedfees.Select( f => f.Id ).ToList();
                foreach ( var registrantFee in registrationRegistrantFeeService
                    .Queryable()
                    .Where( f => deletedFeeIds.Contains( f.RegistrationTemplateFeeId ) )
                    .ToList() )
                {
                    registrationRegistrantFeeService.Delete( registrantFee );
                }

                foreach ( var fee in deletedfees )
                {
                    registrationTemplateFeeService.Delete( fee );
                }

                int? entityTypeId = EntityTypeCache.Read( typeof( Rock.Model.RegistrationRegistrant ) ).Id;
                var qualifierColumn = "RegistrationTemplateId";
                var qualifierValue = RegistrationTemplate.Id.ToString();

                // Get the registration attributes still in the UI
                var attributesUI = FormFieldsState
                    .SelectMany( s =>
                        s.Value.Where( a =>
                            a.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                            a.Attribute != null ) )
                    .Select( f => f.Attribute )
                    .ToList();
                var selectedAttributeGuids = attributesUI.Select( a => a.Guid );

                // Delete the registration attributes that were removed from the UI
                var attributesDB = attributeService.Get( entityTypeId, qualifierColumn, qualifierValue );
                foreach ( var attr in attributesDB.Where( a => !selectedAttributeGuids.Contains( a.Guid ) ).ToList() )
                {
                    attributeService.Delete( attr );
                    Rock.Web.Cache.AttributeCache.Flush( attr.Id );
                }

                rockContext.SaveChanges();

                // Save all of the registration attributes still in the UI
                foreach ( var attr in attributesUI )
                {
                    Helper.SaveAttributeEdits( attr, entityTypeId, qualifierColumn, qualifierValue, rockContext );
                }

                // add/updated forms/fields
                foreach ( var formUI in FormState )
                {
                    var form = RegistrationTemplate.Forms.FirstOrDefault( f => f.Guid.Equals( formUI.Guid ) );
                    if ( form == null )
                    {
                        form = new RegistrationTemplateForm();
                        form.Guid = formUI.Guid;
                        RegistrationTemplate.Forms.Add( form );
                    }
                    form.Name = formUI.Name;
                    form.Order = formUI.Order;

                    if ( FormFieldsState.ContainsKey( form.Guid ) )
                    {
                        foreach ( var formFieldUI in FormFieldsState[form.Guid] )
                        {
                            var formField = form.Fields.FirstOrDefault( a => a.Guid.Equals( formFieldUI.Guid ) );
                            if ( formField == null )
                            {
                                formField = new RegistrationTemplateFormField();
                                formField.Guid = formFieldUI.Guid;
                                form.Fields.Add( formField );
                            }

                            formField.AttributeId = formFieldUI.AttributeId;
                            if ( !formField.AttributeId.HasValue &&
                                formFieldUI.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                                formFieldUI.Attribute != null )
                            {
                                var attr = AttributeCache.Read( formFieldUI.Attribute.Guid, rockContext );
                                if ( attr != null )
                                {
                                    formField.AttributeId = attr.Id;
                                }
                            }

                            formField.FieldSource = formFieldUI.FieldSource;
                            formField.PersonFieldType = formFieldUI.PersonFieldType;
                            formField.IsInternal = formFieldUI.IsInternal;
                            formField.IsSharedValue = formFieldUI.IsSharedValue;
                            formField.ShowCurrentValue = formFieldUI.ShowCurrentValue;
                            formField.PreText = formFieldUI.PreText;
                            formField.PostText = formFieldUI.PostText;
                            formField.IsGridField = formFieldUI.IsGridField;
                            formField.IsRequired = formFieldUI.IsRequired;
                            formField.Order = formFieldUI.Order;
                        }
                    }
                }

                // add/updated discounts
                foreach ( var discountUI in DiscountState )
                {
                    var discount = RegistrationTemplate.Discounts.FirstOrDefault( a => a.Guid.Equals( discountUI.Guid ) );
                    if ( discount == null )
                    {
                        discount = new RegistrationTemplateDiscount();
                        discount.Guid = discountUI.Guid;
                        RegistrationTemplate.Discounts.Add( discount );
                    }
                    discount.Code = discountUI.Code;
                    discount.DiscountPercentage = discountUI.DiscountPercentage;
                    discount.DiscountAmount = discountUI.DiscountAmount;
                    discount.Order = discountUI.Order;
                }

                // add/updated fees
                foreach ( var feeUI in FeeState )
                {
                    var fee = RegistrationTemplate.Fees.FirstOrDefault( a => a.Guid.Equals( feeUI.Guid ) );
                    if ( fee == null )
                    {
                        fee = new RegistrationTemplateFee();
                        fee.Guid = feeUI.Guid;
                        RegistrationTemplate.Fees.Add( fee );
                    }
                    fee.Name = feeUI.Name;
                    fee.FeeType = feeUI.FeeType;
                    fee.CostValue = feeUI.CostValue;
                    fee.DiscountApplies = feeUI.DiscountApplies;
                    fee.AllowMultiple = feeUI.AllowMultiple;
                    fee.Order = feeUI.Order;
                }

                rockContext.SaveChanges();

                AttributeCache.FlushEntityAttributes();

                // If this is a new template, give the current user and the Registration Administrators role administrative
                // rights to this template, and staff, and staff like roles edit rights
                if ( newTemplate )
                {
                    RegistrationTemplate.AllowPerson( Authorization.ADMINISTRATE, CurrentPerson, rockContext );

                    var registrationAdmins = groupService.Get( Rock.SystemGuid.Group.GROUP_EVENT_REGISTRATION_ADMINISTRATORS.AsGuid() );
                    RegistrationTemplate.AllowSecurityRole( Authorization.ADMINISTRATE, registrationAdmins, rockContext );

                    var staffLikeUsers = groupService.Get( Rock.SystemGuid.Group.GROUP_STAFF_LIKE_MEMBERS.AsGuid() );
                    RegistrationTemplate.AllowSecurityRole( Authorization.EDIT, staffLikeUsers, rockContext );

                    var staffUsers = groupService.Get( Rock.SystemGuid.Group.GROUP_STAFF_MEMBERS.AsGuid() );
                    RegistrationTemplate.AllowSecurityRole( Authorization.EDIT, staffUsers, rockContext );
                }

                var qryParams = new Dictionary<string, string>();
                qryParams["RegistrationTemplateId"] = RegistrationTemplate.Id.ToString();
                NavigateToPage( RockPage.Guid, qryParams );
            }
        }
Ejemplo n.º 51
0
 /// <summary>
 /// Sets the value on select.
 /// </summary>
 protected override void SetValueOnSelect()
 {
     var registrationTemplate = new RegistrationTemplateService( new RockContext() ).Get( int.Parse( ItemId ) );
     SetValue( registrationTemplate );
 }