/// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression(Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection)
        {
            string[] selectionValues = selection.Split('|');
            if (selectionValues.Length >= 1)
            {
                List <Guid> registrationTemplateGuids   = selectionValues[0].Split(',').AsGuidList();
                var         registrationInstanceService = new RegistrationInstanceService((RockContext)serviceInstance.Context);
                var         registrationInstanceIds     = registrationInstanceService.Queryable().Where(ri => registrationTemplateGuids.Contains(ri.RegistrationTemplate.Guid)).Select(ri => ri.Id).Distinct().ToList();

                RegistrationRegistrantService registrationRegistrantService = new RegistrationRegistrantService((RockContext)serviceInstance.Context);


                bool includeInactiveRegistrationInstances = false;

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

                var registrationRegistrantServiceQry = registrationRegistrantService.Queryable();

                if (registrationTemplateGuids.Count > 0)
                {
                    registrationRegistrantServiceQry = registrationRegistrantServiceQry.Where(xx => registrationInstanceIds.Contains(xx.Registration.RegistrationInstanceId));
                }

                if (selectionValues.Length >= 3)
                {
                    string    slidingDelimitedValues = selectionValues[2].Replace(',', '|');
                    DateRange dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues(slidingDelimitedValues);
                    if (dateRange.Start.HasValue)
                    {
                        registrationRegistrantServiceQry = registrationRegistrantServiceQry.Where(xx => xx.CreatedDateTime >= dateRange.Start.Value);
                    }

                    if (dateRange.End.HasValue)
                    {
                        registrationRegistrantServiceQry = registrationRegistrantServiceQry.Where(xx => xx.CreatedDateTime < dateRange.End.Value);
                    }
                }

                var qry = new PersonService((RockContext)serviceInstance.Context).Queryable()
                          .Where(p => registrationRegistrantServiceQry.Any(xx => xx.PersonAlias.PersonId == p.Id));

                Expression extractedFilterExpression = FilterExpressionExtractor.Extract <Rock.Model.Person>(qry, parameterExpression, "p");

                return(extractedFilterExpression);
            }

            return(null);
        }
        protected void BindGrid()
        {
            RockContext                   rockContext                   = new RockContext();
            PersonAliasService            personAliasService            = new PersonAliasService(rockContext);
            WorkflowService               workflowTypeService           = new WorkflowService(rockContext);
            WorkflowService               workflowService               = new WorkflowService(rockContext);
            AttributeService              attributeService              = new AttributeService(rockContext);
            AttributeValueService         attributeValueService         = new AttributeValueService(rockContext);
            RegistrationRegistrantService registrationRegistrantService = new RegistrationRegistrantService(rockContext);

            List <string> workflowTypes   = GetAttributeValues("WorkflowTypes");
            List <string> workflowTypeIds = new List <string>();

            foreach (string workflowTypeGuid in workflowTypes)
            {
                workflowTypeIds.Add(WorkflowTypeCache.Get(workflowTypeGuid.AsGuid()).Id.ToString());
            }

            var attributes   = attributeService.Queryable().Where(a => workflowTypeIds.Contains(a.EntityTypeQualifierValue) && a.EntityTypeQualifierColumn == "WorkflowTypeId");
            var attributeIds = attributes.Select(a => a.Id);

            // Get all the family members
            var familyMembers = personAliasService.Get(PageParameter("PersonAliasId").AsInteger()).Person.GetFamilyMembers(true);

            var familyAliasIds = familyMembers.SelectMany(fm => fm.Person.Aliases.Select(pa => pa.Id)).ToList();

            var discountCodes = registrationRegistrantService.Queryable().Where(rr => rr.PersonAliasId.HasValue && familyAliasIds.Contains(rr.PersonAliasId.Value))
                                .Where(rr => rr.Registration.DiscountCode != null && rr.Registration.DiscountCode != "")
                                .ToDictionary(x => x.Registration.DiscountCode.ToUpper(), x => x.Registration.DiscountAmount);

            var qry = workflowService.Queryable().Where(w => workflowTypeIds.Contains(w.WorkflowTypeId.ToString()))
                      .GroupJoin(attributeValueService.Queryable().Where(av => attributeIds.Contains(av.AttributeId)),
                                 w => w.Id,
                                 av => av.EntityId,
                                 (w, av) => new { Workflow = w, AttributeValues = av })
                      .Where(obj => obj.AttributeValues.Any(av => av.Attribute.Key == "DiscountCode" && discountCodes.Keys.Contains(av.Value)))
                      .ToList()
                      .Select(obj => new {
                Id              = obj.Workflow.Id,
                FirstName       = obj.AttributeValues.Where(av => av.Attribute.Key == "StudentFirstName").Select(av => av.Value).DefaultIfEmpty(obj.AttributeValues.Where(av => av.Attribute.Key == "ParentFirstName").Select(av => av.Value).FirstOrDefault()).FirstOrDefault(),
                LastName        = obj.AttributeValues.Where(av => av.Attribute.Key == "StudentLastName").Select(av => av.Value).DefaultIfEmpty(obj.AttributeValues.Where(av => av.Attribute.Key == "ParentLastName").Select(av => av.Value).FirstOrDefault()).FirstOrDefault(),
                Campus          = obj.AttributeValues.Where(av => av.Attribute.Key == "Campus").Select(av => CampusCache.Get(av.Value.AsGuid())).FirstOrDefault(),
                ApplicationYear = obj.AttributeValues.Where(av => av.Attribute.Key == "ApplicationYear").Select(av => av.Value).DefaultIfEmpty(attributes.Where(a => a.Key == "ApplicationYear").Select(a => a.DefaultValue).FirstOrDefault()).FirstOrDefault(),
                DiscountCode    = obj.AttributeValues.Where(av => av.Attribute.Key == "DiscountCode").Select(av => av.Value).FirstOrDefault(),
                DiscountAmount  = discountCodes.ContainsKey(obj.AttributeValues.Where(av => av.Attribute.Key == "DiscountCode").Select(av => av.Value.ToUpper()).FirstOrDefault()) ?discountCodes[obj.AttributeValues.Where(av => av.Attribute.Key == "DiscountCode").Select(av => av.Value.ToUpper()).FirstOrDefault()]:0,
                Event           = obj.AttributeValues.Where(av => av.Attribute.Key == "EventStudentisAttending").Select(av => av.Value).DefaultIfEmpty(obj.AttributeValues.Where(av => av.Attribute.Key == "EventLeaderisAttending").Select(av => av.Value).FirstOrDefault()).FirstOrDefault(),
                Status          = obj.Workflow.Status
            });

            gFamilyProfile.DataSource = qry.ToList();
            gFamilyProfile.DataBind();
        }
Beispiel #3
0
        /// <summary>
        /// Handles the Click event of the DeleteGroupMember control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs" /> instance containing the event data.</param>
        protected void DeleteGroupMember_Click(object sender, Rock.Web.UI.Controls.RowEventArgs e)
        {
            RockContext                   rockContext        = new RockContext();
            GroupMemberService            groupMemberService = new GroupMemberService(rockContext);
            RegistrationRegistrantService registrantService  = new RegistrationRegistrantService(rockContext);
            GroupMember                   groupMember        = groupMemberService.Get(e.RowKeyId);

            if (groupMember != null)
            {
                string errorMessage;
                if (!groupMemberService.CanDelete(groupMember, out errorMessage))
                {
                    mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                    return;
                }

                int groupId = groupMember.GroupId;

                foreach (var registrant in registrantService.Queryable().Where(r => r.GroupMemberId == groupMember.Id))
                {
                    registrant.GroupMemberId = null;
                }

                groupMemberService.Delete(groupMember);

                rockContext.SaveChanges();

                Group group = new GroupService(rockContext).Get(groupId);
                if (group.IsSecurityRole || group.GroupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()))
                {
                    // person removed from SecurityRole, Flush
                    Rock.Security.Role.Flush(group.Id);
                }
            }

            BindGroupMembersGrid();
        }
Beispiel #4
0
        /// <summary>
        /// Handles the Delete event of the gGroups control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gGroups_Delete(object sender, RowEventArgs e)
        {
            var          rockContext  = new RockContext();
            GroupService groupService = new GroupService(rockContext);
            AuthService  authService  = new AuthService(rockContext);
            Group        group        = groupService.Get(e.RowKeyId);

            if (group != null)
            {
                string errorMessage;
                bool   isSecurityRoleGroup = group.IsSecurityRole || group.GroupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid());
                int    personEntityTypeId  = EntityTypeCache.Read("Rock.Model.Person").Id;

                if (ContextTypesRequired.Any(a => a.Id == personEntityTypeId))
                {
                    var personContext = ContextEntity <Person>();
                    GroupMemberService            groupMemberService = new GroupMemberService(rockContext);
                    RegistrationRegistrantService registrantService  = new RegistrationRegistrantService(rockContext);
                    GroupMember groupMember = group.Members.SingleOrDefault(a => a.PersonId == personContext.Id);

                    if (!(group.IsAuthorized(Authorization.EDIT, this.CurrentPerson) || group.IsAuthorized(Authorization.MANAGE_MEMBERS, this.CurrentPerson)))
                    {
                        mdGridWarning.Show("You are not authorized to delete members from this group", ModalAlertType.Information);
                        return;
                    }

                    if (!groupMemberService.CanDelete(groupMember, out errorMessage))
                    {
                        mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                        return;
                    }

                    foreach (var registrant in registrantService.Queryable().Where(r => r.GroupMemberId == groupMember.Id))
                    {
                        registrant.GroupMemberId = null;
                    }

                    if (group.IsSecurityRole || group.GroupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()))
                    {
                        // person removed from SecurityRole, Flush
                        Rock.Security.Role.Flush(group.Id);
                    }

                    groupMemberService.Delete(groupMember);
                }
                else
                {
                    if (!group.IsAuthorized(Authorization.EDIT, this.CurrentPerson))
                    {
                        mdGridWarning.Show("You are not authorized to delete this group", ModalAlertType.Information);
                        return;
                    }


                    if (!groupService.CanDelete(group, out errorMessage))
                    {
                        mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                        return;
                    }


                    if (isSecurityRoleGroup)
                    {
                        Rock.Security.Role.Flush(group.Id);
                        foreach (var auth in authService.Queryable().Where(a => a.GroupId == group.Id).ToList())
                        {
                            authService.Delete(auth);
                        }
                    }

                    groupService.Delete(group);
                }

                rockContext.SaveChanges();

                if (isSecurityRoleGroup)
                {
                    Rock.Security.Authorization.Flush();
                }
            }

            BindGrid();
        }
Beispiel #5
0
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var rockContext = new RockContext();

            var groupMemberService            = new GroupMemberService(rockContext);
            var groupService                  = new GroupService(rockContext);
            var groupTypeService              = new GroupTypeService(rockContext);
            var attributeService              = new AttributeService(rockContext);
            var attributeValueService         = new AttributeValueService(rockContext);
            var personService                 = new PersonService(rockContext);
            var personAliasService            = new PersonAliasService(rockContext);
            var entityTypeService             = new EntityTypeService(rockContext);
            var registrationRegistrantService = new RegistrationRegistrantService(rockContext);
            var eiogmService                  = new EventItemOccurrenceGroupMapService(rockContext);
            var groupLocationService          = new GroupLocationService(rockContext);
            var locationService               = new LocationService(rockContext);
            var signatureDocumentServce       = new SignatureDocumentService(rockContext);
            var phoneNumberService            = new PhoneNumberService(rockContext);

            int[] signatureDocumentIds = { };
            if (!string.IsNullOrWhiteSpace(GetAttributeValue("SignatureDocumentTemplates")))
            {
                signatureDocumentIds = Array.ConvertAll(GetAttributeValue("SignatureDocumentTemplates").Split(','), int.Parse);
            }
            Guid bbGroup = GetAttributeValue("Group").AsGuid();
            var  group   = new GroupService(rockContext).Get(bbGroup);

            if (group.Name.Contains("Week 2"))
            {
                cmpCampus.Visible = true;
            }

            Guid hsmGroupTypeGuid = GetAttributeValue("MSMGroupType").AsGuid();
            int? hsmGroupTypeId   = groupTypeService.Queryable().Where(gt => gt.Guid == hsmGroupTypeGuid).Select(gt => gt.Id).FirstOrDefault();

            int entityTypeId = entityTypeService.Queryable().Where(et => et.Name == typeof(Rock.Model.Group).FullName).FirstOrDefault().Id;

            var registrationTemplateIds = eiogmService.Queryable().Where(r => r.GroupId == group.Id).Select(m => m.RegistrationInstance.RegistrationTemplateId.ToString()).ToList();

            hlGroup.NavigateUrl = "/group/" + group.Id;

            var attributeIds = attributeService.Queryable()
                               .Where(a => (a.EntityTypeQualifierColumn == "GroupId" && a.EntityTypeQualifierValue == group.Id.ToString()) ||
                                      (a.EntityTypeQualifierColumn == "GroupTypeId" && a.EntityTypeQualifierValue == group.GroupTypeId.ToString()) ||
                                      (a.EntityTypeQualifierColumn == "RegistrationTemplateId" && registrationTemplateIds.Contains(a.EntityTypeQualifierValue)))
                               .Select(a => a.Id).ToList();

            var gmTmpqry = groupMemberService.Queryable()
                           .Where(gm => (gm.GroupId == group.Id));

            var qry = gmTmpqry
                      .GroupJoin(registrationRegistrantService.Queryable(),
                                 obj => obj.Id,
                                 rr => rr.GroupMemberId,
                                 (obj, rr) => new { GroupMember = obj, Person = obj.Person, RegistrationRegistrant = rr })
                      .GroupJoin(attributeValueService.Queryable(),
                                 obj => new { PersonId = (int?)obj.Person.Id, AttributeId = 739 },
                                 av => new { PersonId = av.EntityId, av.AttributeId },
                                 (obj, av) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, School = av.Select(s => s.Value).FirstOrDefault() })
                      .GroupJoin(attributeValueService.Queryable(),
                                 obj => obj.GroupMember.Id,
                                 av => av.EntityId.Value,
                                 (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)), School = obj.School /*, Location = obj.Location */ })
                      .GroupJoin(attributeValueService.Queryable(),
                                 obj => obj.RegistrationRegistrant.FirstOrDefault().Id,
                                 av => av.EntityId.Value,
                                 (obj, avs) => new { GroupMember = obj.GroupMember, Person = obj.Person, RegistrationRegistrant = obj.RegistrationRegistrant, GroupMemberAttributeValues = obj.GroupMemberAttributeValues, RegistrationAttributeValues = avs.Where(av => attributeIds.Contains(av.AttributeId)), School = obj.School /*, Location = obj.Location */ });

            var qry2 = gmTmpqry
                       .GroupJoin(
                groupMemberService.Queryable()
                .Join(groupService.Queryable(),
                      gm => new { Id = gm.GroupId, GroupTypeId = 10 },
                      g => new { g.Id, g.GroupTypeId },
                      (gm, g) => new { GroupMember = gm, Group = g })
                .Join(groupLocationService.Queryable(),
                      obj => new { GroupId = obj.Group.Id, GroupLocationTypeValueId = (int?)19 },
                      gl => new { gl.GroupId, gl.GroupLocationTypeValueId },
                      (g, gl) => new { GroupMember = g.GroupMember, GroupLocation = gl })
                .Join(locationService.Queryable(),
                      obj => obj.GroupLocation.LocationId,
                      l => l.Id,
                      (obj, l) => new { GroupMember = obj.GroupMember, Location = l }),
                gm => gm.PersonId,
                glgm => glgm.GroupMember.PersonId,
                (obj, l) => new { GroupMember = obj, Location = l.Select(loc => loc.Location).FirstOrDefault() }
                )
                       .GroupJoin(signatureDocumentServce.Queryable()
                                  .Join(personAliasService.Queryable(),
                                        sd => sd.AppliesToPersonAliasId,
                                        pa => pa.Id,
                                        (sd, pa) => new { SignatureDocument = sd, Alias = pa }),
                                  obj => obj.GroupMember.PersonId,
                                  sd => sd.Alias.PersonId,
                                  (obj, sds) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = sds })
                       .GroupJoin(phoneNumberService.Queryable(),
                                  obj => obj.GroupMember.PersonId,
                                  p => p.PersonId,
                                  (obj, pn) => new { GroupMember = obj.GroupMember, Location = obj.Location, SignatureDocuments = obj.SignatureDocuments, PhoneNumbers = pn });


            if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}PersonName", keyPrefix))))
            {
                string personName = GetUserPreference(string.Format("{0}PersonName", keyPrefix)).ToLower();
                qry = qry.ToList().Where(q => q.GroupMember.Person.FullName.ToLower().Contains(personName)).AsQueryable();
            }
            decimal?lowerVal = GetUserPreference(string.Format("{0}BalanceOwedLower", keyPrefix)).AsDecimalOrNull();
            decimal?upperVal = GetUserPreference(string.Format("{0}BalanceOwedUpper", keyPrefix)).AsDecimalOrNull();

            if (lowerVal != null && upperVal != null)
            {
                qry = qry.ToList().Where(q => q.RegistrationRegistrant.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() >= lowerVal && q.RegistrationRegistrant.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() <= upperVal).AsQueryable();
            }
            else if (lowerVal != null)
            {
                qry = qry.ToList().Where(q => q.RegistrationRegistrant.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() >= lowerVal).AsQueryable();
            }
            else if (upperVal != null)
            {
                qry = qry.ToList().Where(q => q.RegistrationRegistrant.Select(rr => rr.Registration.BalanceDue).FirstOrDefault() <= upperVal).AsQueryable();
            }
            else if (!string.IsNullOrEmpty(cmpCampus.SelectedValue))
            {
                if (group.Name.Contains("Week 2"))
                {
                    qry = qry.ToList().Where(q => q.RegistrationAttributeValues.Where(ra => ra.AttributeKey == "Whichcampusdoyouwanttodepartforcampfromandroomwith" && ra.Value == cmpCampus.SelectedValue).Any()).AsQueryable();
                }
            }

            var stopwatch = new Stopwatch();

            stopwatch.Start();
            var tmp  = qry.ToList();
            var tmp2 = qry2.ToList();

            lStats.Text = "Query Runtime: " + stopwatch.Elapsed;
            stopwatch.Reset();

            stopwatch.Start();

            var newQry = tmp.Select(g => new
            {
                Id                    = g.GroupMember.Id,
                RegisteredBy          = new ModelValue <Person>(g.RegistrationRegistrant.Select(rr => rr.Registration.PersonAlias.Person).FirstOrDefault()),
                Registrant            = new ModelValue <Person>(g.Person),
                Age                   = g.Person.Age,
                GraduationYear        = g.Person.GraduationYear,
                RegistrationId        = g.RegistrationRegistrant.Select(rr => rr.RegistrationId).FirstOrDefault(),
                Group                 = new ModelValue <Rock.Model.Group>((Rock.Model.Group)g.GroupMember.Group),
                DOB                   = g.Person.BirthDate.HasValue ? g.Person.BirthDate.Value.ToShortDateString() : "",
                Address               = new ModelValue <Rock.Model.Location>((Rock.Model.Location)tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location).FirstOrDefault()),
                Email                 = g.Person.Email,
                Gender                = g.Person.Gender,         // (B & B Registration)
                GraduationYearProfile = g.Person.GraduationYear, // (Person Profile)
                HomePhone             = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(),
                CellPhone             = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.PhoneNumbers).Where(pn => pn.NumberTypeValue.Guid == Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()).Select(pn => pn.NumberFormatted).FirstOrDefault(),
                GroupMemberData       = new Func <GroupMemberAttributes>(() =>
                {
                    GroupMemberAttributes gma = new GroupMemberAttributes(g.GroupMember, g.Person, g.GroupMemberAttributeValues);
                    return(gma);
                })(),
                RegistrantData = new Func <RegistrantAttributes>(() =>
                {
                    RegistrantAttributes row = new RegistrantAttributes(g.RegistrationRegistrant.FirstOrDefault(), g.RegistrationAttributeValues);
                    return(row);
                })(),
                School              = string.IsNullOrEmpty(g.School)?"":DefinedValueCache.Read(g.School.AsGuid()) != null?DefinedValueCache.Read(g.School.AsGuid()).Value:"",
                LegalRelease        = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).SelectMany(gm => gm.SignatureDocuments).OrderByDescending(sd => sd.SignatureDocument.CreatedDateTime).Where(sd => signatureDocumentIds.Contains(sd.SignatureDocument.SignatureDocumentTemplateId)).Select(sd => sd.SignatureDocument.SignatureDocumentTemplate.Name + " (" + sd.SignatureDocument.Status.ToString() + ")").FirstOrDefault(),
                Departure           = g.GroupMemberAttributeValues.Where(av => av.AttributeKey == "Departure").Select(av => av.Value).FirstOrDefault(),
                Campus              = group.Campus,                                                                                                        //
                Role                = group.ParentGroup.GroupType.Name.Contains("Serving") || group.Name.ToLower().Contains("leader")? "Leader":"Student", //
                MSMGroup            = String.Join(", ", groupMemberService.Queryable().Where(gm => gm.PersonId == g.GroupMember.PersonId && gm.Group.GroupTypeId == hsmGroupTypeId && gm.GroupMemberStatus == GroupMemberStatus.Active).Select(gm => gm.Group.Name).ToList()),
                Person              = g.Person,
                AddressStreet       = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location != null?gm.Location.Street1:"").FirstOrDefault(),
                AddressCityStateZip = tmp2.Where(gm => gm.GroupMember.Id == g.GroupMember.Id).Select(gm => gm.Location != null ? gm.Location.City + ", " + gm.Location.State + " " + gm.Location.PostalCode : "").FirstOrDefault(),

                RegistrantName = g.Person.FullName,
            }).OrderBy(w => w.Registrant.Model.LastName).ToList().AsQueryable();

            lStats.Text += "<br />Object Build Runtime: " + stopwatch.Elapsed;

            stopwatch.Stop();
            gReport.GetRecipientMergeFields += GReport_GetRecipientMergeFields;
            var mergeFields = new List <String>();

            mergeFields.Add("Id");
            mergeFields.Add("RegisteredBy");
            mergeFields.Add("Group");
            mergeFields.Add("Registrant");
            mergeFields.Add("Age");
            mergeFields.Add("GraduationYear");
            mergeFields.Add("DOB");
            mergeFields.Add("Address");
            mergeFields.Add("Email");
            mergeFields.Add("Gender");
            mergeFields.Add("GraduationYearProfile");
            mergeFields.Add("HomePhone");
            mergeFields.Add("CellPhone");
            mergeFields.Add("GroupMemberData");
            mergeFields.Add("RegistrantData");
            mergeFields.Add("LegalRelease");
            mergeFields.Add("Departure");
            mergeFields.Add("Campus");
            mergeFields.Add("Role");
            mergeFields.Add("MSMGroup");
            gReport.CommunicateMergeFields = mergeFields;

            /*
             * if (!String.IsNullOrWhiteSpace(GetUserPreference(string.Format("{0}POA", keyPrefix))))
             * {
             *  string poa = GetUserPreference(string.Format("{0}POA", keyPrefix));
             *  if (poa == "[Blank]")
             *  {
             *      poa = "";
             *  }
             *  newQry = newQry.Where(q => q.GroupMemberData.POA == poa);
             * }
             */

            SortProperty sortProperty = gReport.SortProperty;

            if (sortProperty != null)
            {
                gReport.SetLinqDataSource(newQry.Sort(sortProperty));
            }
            else
            {
                gReport.SetLinqDataSource(newQry.OrderBy(p => p.Registrant.Model.LastName));
            }
            gReport.DataBind();
        }
Beispiel #6
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)
        {
            if (RegistrantState != null)
            {
                RockContext            rockContext                        = new RockContext();
                var                    personService                      = new PersonService(rockContext);
                var                    registrantService                  = new RegistrationRegistrantService(rockContext);
                var                    registrantFeeService               = new RegistrationRegistrantFeeService(rockContext);
                var                    registrationTemplateFeeService     = new RegistrationTemplateFeeService(rockContext);
                var                    registrationTemplateFeeItemService = new RegistrationTemplateFeeItemService(rockContext);
                RegistrationRegistrant registrant = null;
                if (RegistrantState.Id > 0)
                {
                    registrant = registrantService.Get(RegistrantState.Id);
                }

                var previousRegistrantPersonIds = registrantService.Queryable().Where(a => a.RegistrationId == RegistrantState.RegistrationId)
                                                  .Where(r => r.PersonAlias != null)
                                                  .Select(r => r.PersonAlias.PersonId)
                                                  .ToList();

                bool newRegistrant     = false;
                var  registrantChanges = new History.HistoryChangeList();

                if (registrant == null)
                {
                    newRegistrant             = true;
                    registrant                = new RegistrationRegistrant();
                    registrant.RegistrationId = RegistrantState.RegistrationId;
                    registrantService.Add(registrant);
                    registrantChanges.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, "Registrant");
                }

                if (!registrant.PersonAliasId.Equals(ppPerson.PersonAliasId))
                {
                    string prevPerson = (registrant.PersonAlias != null && registrant.PersonAlias.Person != null) ?
                                        registrant.PersonAlias.Person.FullName : string.Empty;
                    string newPerson = ppPerson.PersonName;
                    newRegistrant = true;
                    History.EvaluateChange(registrantChanges, "Person", prevPerson, newPerson);
                }

                int?personId = ppPerson.PersonId.Value;
                registrant.PersonAliasId = ppPerson.PersonAliasId.Value;

                // Get the name of registrant for history
                string registrantName = "Unknown";
                if (ppPerson.PersonId.HasValue)
                {
                    var person = personService.Get(ppPerson.PersonId.Value);
                    if (person != null)
                    {
                        registrantName = person.FullName;
                    }
                }

                // set their status (wait list / registrant)
                registrant.OnWaitList = !tglWaitList.Checked;

                History.EvaluateChange(registrantChanges, "Cost", registrant.Cost, cbCost.Text.AsDecimal());
                registrant.Cost = cbCost.Text.AsDecimal();

                History.EvaluateChange(registrantChanges, "Discount Applies", registrant.DiscountApplies, cbDiscountApplies.Checked);
                registrant.DiscountApplies = cbDiscountApplies.Checked;

                if (!Page.IsValid)
                {
                    return;
                }

                // Remove/delete any registrant fees that are no longer in UI with quantity
                foreach (var dbFee in registrant.Fees.ToList())
                {
                    if (!RegistrantState.FeeValues.Keys.Contains(dbFee.RegistrationTemplateFeeId) ||
                        RegistrantState.FeeValues[dbFee.RegistrationTemplateFeeId] == null ||
                        !RegistrantState.FeeValues[dbFee.RegistrationTemplateFeeId]
                        .Any(f =>
                             f.RegistrationTemplateFeeItemId == dbFee.RegistrationTemplateFeeItemId &&
                             f.Quantity > 0))
                    {
                        var feeOldValue = string.Format("'{0}' Fee (Quantity:{1:N0}, Cost:{2:C2}, Option:{3}",
                                                        dbFee.RegistrationTemplateFee.Name, dbFee.Quantity, dbFee.Cost, dbFee.Option);

                        registrantChanges.AddChange(History.HistoryVerb.Delete, History.HistoryChangeType.Record, "Fee").SetOldValue(feeOldValue);
                        registrant.Fees.Remove(dbFee);
                        registrantFeeService.Delete(dbFee);
                    }
                }

                // Add/Update any of the fees from UI
                foreach (var uiFee in RegistrantState.FeeValues.Where(f => f.Value != null))
                {
                    foreach (var uiFeeOption in uiFee.Value)
                    {
                        var dbFee = registrant.Fees
                                    .Where(f =>
                                           f.RegistrationTemplateFeeId == uiFee.Key &&
                                           f.RegistrationTemplateFeeItemId == uiFeeOption.RegistrationTemplateFeeItemId)
                                    .FirstOrDefault();

                        if (dbFee == null)
                        {
                            dbFee = new RegistrationRegistrantFee();
                            dbFee.RegistrationTemplateFeeId = uiFee.Key;
                            var registrationTemplateFeeItem = uiFeeOption.RegistrationTemplateFeeItemId != null?registrationTemplateFeeItemService.GetNoTracking(uiFeeOption.RegistrationTemplateFeeItemId.Value) : null;

                            if (registrationTemplateFeeItem != null)
                            {
                                dbFee.Option = registrationTemplateFeeItem.Name;
                            }

                            dbFee.RegistrationTemplateFeeItemId = uiFeeOption.RegistrationTemplateFeeItemId;
                            registrant.Fees.Add(dbFee);
                        }

                        var templateFee = dbFee.RegistrationTemplateFee;
                        if (templateFee == null)
                        {
                            templateFee = registrationTemplateFeeService.Get(uiFee.Key);
                        }

                        string feeName = templateFee != null ? templateFee.Name : "Fee";
                        if (!string.IsNullOrWhiteSpace(uiFeeOption.FeeLabel))
                        {
                            feeName = string.Format("{0} ({1})", feeName, uiFeeOption.FeeLabel);
                        }

                        if (dbFee.Id <= 0)
                        {
                            registrantChanges.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, "Fee").SetNewValue(feeName);
                        }

                        History.EvaluateChange(registrantChanges, feeName + " Quantity", dbFee.Quantity, uiFeeOption.Quantity);
                        dbFee.Quantity = uiFeeOption.Quantity;

                        History.EvaluateChange(registrantChanges, feeName + " Cost", dbFee.Cost, uiFeeOption.Cost);
                        dbFee.Cost = uiFeeOption.Cost;
                    }
                }

                if (this.RegistrationTemplate.RequiredSignatureDocumentTemplate != null)
                {
                    var person = new PersonService(rockContext).Get(personId.Value);

                    var documentService        = new SignatureDocumentService(rockContext);
                    var binaryFileService      = new BinaryFileService(rockContext);
                    SignatureDocument document = null;

                    int?signatureDocumentId = hfSignedDocumentId.Value.AsIntegerOrNull();
                    int?binaryFileId        = fuSignedDocument.BinaryFileId;
                    if (signatureDocumentId.HasValue)
                    {
                        document = documentService.Get(signatureDocumentId.Value);
                    }

                    if (document == null && binaryFileId.HasValue)
                    {
                        var instance = new RegistrationInstanceService(rockContext).Get(RegistrationInstanceId);

                        document = new SignatureDocument();
                        document.SignatureDocumentTemplateId = this.RegistrationTemplate.RequiredSignatureDocumentTemplate.Id;
                        document.AppliesToPersonAliasId      = registrant.PersonAliasId.Value;
                        document.AssignedToPersonAliasId     = registrant.PersonAliasId.Value;
                        document.Name = string.Format(
                            "{0}_{1}",
                            instance != null ? instance.Name : this.RegistrationTemplate.Name,
                            person != null ? person.FullName.RemoveSpecialCharacters() : string.Empty);
                        document.Status         = SignatureDocumentStatus.Signed;
                        document.LastStatusDate = RockDateTime.Now;
                        documentService.Add(document);
                    }

                    if (document != null)
                    {
                        int?origBinaryFileId = document.BinaryFileId;
                        document.BinaryFileId = binaryFileId;

                        if (origBinaryFileId.HasValue && origBinaryFileId.Value != document.BinaryFileId)
                        {
                            // if a new the binaryFile was uploaded, mark the old one as Temporary so that it gets cleaned up
                            var oldBinaryFile = binaryFileService.Get(origBinaryFileId.Value);
                            if (oldBinaryFile != null && !oldBinaryFile.IsTemporary)
                            {
                                oldBinaryFile.IsTemporary = true;
                            }
                        }

                        // ensure the IsTemporary is set to false on binaryFile associated with this document
                        if (document.BinaryFileId.HasValue)
                        {
                            var binaryFile = binaryFileService.Get(document.BinaryFileId.Value);
                            if (binaryFile != null && binaryFile.IsTemporary)
                            {
                                binaryFile.IsTemporary = false;
                            }
                        }
                    }
                }

                if (!registrant.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                // use WrapTransaction since SaveAttributeValues does it's own RockContext.SaveChanges()
                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();

                    registrant.LoadAttributes();
                    // NOTE: We will only have Registration Attributes displayed and editable on Registrant Detail.
                    // To Edit Person or GroupMember Attributes, they will have to go the PersonDetail or GroupMemberDetail blocks
                    foreach (var field in this.RegistrationTemplate.Forms
                             .SelectMany(f => f.Fields
                                         .Where(t =>
                                                t.FieldSource == RegistrationFieldSource.RegistrantAttribute &&
                                                t.AttributeId.HasValue)))
                    {
                        var attribute = AttributeCache.Get(field.AttributeId.Value);
                        if (attribute != null)
                        {
                            string originalValue = registrant.GetAttributeValue(attribute.Key);
                            var fieldValue       = RegistrantState.FieldValues
                                                   .Where(f => f.Key == field.Id)
                                                   .Select(f => f.Value.FieldValue)
                                                   .FirstOrDefault();
                            string newValue = fieldValue != null ? fieldValue.ToString() : string.Empty;

                            if ((originalValue ?? string.Empty).Trim() != (newValue ?? string.Empty).Trim())
                            {
                                string formattedOriginalValue = string.Empty;
                                if (!string.IsNullOrWhiteSpace(originalValue))
                                {
                                    formattedOriginalValue = attribute.FieldType.Field.FormatValue(null, originalValue, attribute.QualifierValues, false);
                                }

                                string formattedNewValue = string.Empty;
                                if (!string.IsNullOrWhiteSpace(newValue))
                                {
                                    formattedNewValue = attribute.FieldType.Field.FormatValue(null, newValue, attribute.QualifierValues, false);
                                }

                                History.EvaluateChange(registrantChanges, attribute.Name, formattedOriginalValue, formattedNewValue);
                            }

                            if (fieldValue != null)
                            {
                                registrant.SetAttributeValue(attribute.Key, fieldValue.ToString());
                            }
                        }
                    }

                    registrant.SaveAttributeValues(rockContext);
                });

                if (newRegistrant && this.RegistrationTemplate.GroupTypeId.HasValue && ppPerson.PersonId.HasValue)
                {
                    using (var newRockContext = new RockContext())
                    {
                        var reloadedRegistrant = new RegistrationRegistrantService(newRockContext).Get(registrant.Id);
                        if (reloadedRegistrant != null &&
                            reloadedRegistrant.Registration != null &&
                            reloadedRegistrant.Registration.Group != null &&
                            reloadedRegistrant.Registration.Group.GroupTypeId == this.RegistrationTemplate.GroupTypeId.Value)
                        {
                            int?groupRoleId = this.RegistrationTemplate.GroupMemberRoleId.HasValue ?
                                              this.RegistrationTemplate.GroupMemberRoleId.Value :
                                              reloadedRegistrant.Registration.Group.GroupType.DefaultGroupRoleId;
                            if (groupRoleId.HasValue)
                            {
                                var groupMemberService = new GroupMemberService(newRockContext);
                                var groupMember        = groupMemberService
                                                         .Queryable().AsNoTracking()
                                                         .Where(m =>
                                                                m.GroupId == reloadedRegistrant.Registration.Group.Id &&
                                                                m.PersonId == reloadedRegistrant.PersonId &&
                                                                m.GroupRoleId == groupRoleId.Value)
                                                         .FirstOrDefault();
                                if (groupMember == null)
                                {
                                    groupMember                   = new GroupMember();
                                    groupMember.GroupId           = reloadedRegistrant.Registration.Group.Id;
                                    groupMember.PersonId          = ppPerson.PersonId.Value;
                                    groupMember.GroupRoleId       = groupRoleId.Value;
                                    groupMember.GroupMemberStatus = this.RegistrationTemplate.GroupMemberStatus;
                                    groupMemberService.Add(groupMember);

                                    newRockContext.SaveChanges();

                                    registrantChanges.AddChange(History.HistoryVerb.Add, History.HistoryChangeType.Record, string.Format("Registrant to {0} group", reloadedRegistrant.Registration.Group.Name));
                                }
                                else
                                {
                                    registrantChanges.AddChange(History.HistoryVerb.Modify, History.HistoryChangeType.Record, string.Format("Registrant to existing person in {0} group", reloadedRegistrant.Registration.Group.Name));
                                }

                                if (reloadedRegistrant.GroupMemberId.HasValue && reloadedRegistrant.GroupMemberId.Value != groupMember.Id)
                                {
                                    groupMemberService.Delete(reloadedRegistrant.GroupMember);
                                    newRockContext.SaveChanges();
                                    registrantChanges.AddChange(History.HistoryVerb.Delete, History.HistoryChangeType.Record, string.Format("Registrant to previous person in {0} group", reloadedRegistrant.Registration.Group.Name));
                                }

                                // Record this to the Person's and Registrants Notes and History...

                                reloadedRegistrant.GroupMemberId = groupMember.Id;
                            }
                        }
                        if (reloadedRegistrant.Registration.FirstName.IsNotNullOrWhiteSpace() && reloadedRegistrant.Registration.LastName.IsNotNullOrWhiteSpace())
                        {
                            reloadedRegistrant.Registration.SavePersonNotesAndHistory(reloadedRegistrant.Registration.FirstName, reloadedRegistrant.Registration.LastName, this.CurrentPersonAliasId, previousRegistrantPersonIds);
                        }
                        newRockContext.SaveChanges();
                    }
                }

                HistoryService.SaveChanges(
                    rockContext,
                    typeof(Registration),
                    Rock.SystemGuid.Category.HISTORY_EVENT_REGISTRATION.AsGuid(),
                    registrant.RegistrationId,
                    registrantChanges,
                    "Registrant: " + registrantName,
                    null,
                    null);
            }

            NavigateToRegistration();
        }
        /// <summary>
        /// Gets the expression.
        /// </summary>
        /// <param name="entityType">Type of the entity.</param>
        /// <param name="serviceInstance">The service instance.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <param name="selection">The selection.</param>
        /// <returns></returns>
        public override Expression GetExpression( Type entityType, IService serviceInstance, ParameterExpression parameterExpression, string selection )
        {
            string[] selectionValues = selection.Split( '|' );
            if ( selectionValues.Length >= 1 )
            {
                List<Guid> registrationTemplateGuids = selectionValues[0].Split( ',' ).AsGuidList();
                var registrationInstanceService = new RegistrationInstanceService( (RockContext)serviceInstance.Context );
                var registrationInstanceIds = registrationInstanceService.Queryable().Where( ri => registrationTemplateGuids.Contains( ri.RegistrationTemplate.Guid ) ).Select( ri => ri.Id ).Distinct().ToList();

                RegistrationRegistrantService registrationRegistrantService = new RegistrationRegistrantService( (RockContext)serviceInstance.Context );

                bool includeInactiveRegistrationInstances = false;

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

                var registrationRegistrantServiceQry = registrationRegistrantService.Queryable();

                if ( registrationTemplateGuids.Count > 0 )
                {
                    registrationRegistrantServiceQry = registrationRegistrantServiceQry.Where( xx => registrationInstanceIds.Contains( xx.Registration.RegistrationInstanceId ) );
                }

                if ( selectionValues.Length >= 3 )
                {
                    string slidingDelimitedValues = selectionValues[2].Replace( ',', '|' );
                    DateRange dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( slidingDelimitedValues );
                    if ( dateRange.Start.HasValue )
                    {
                        registrationRegistrantServiceQry = registrationRegistrantServiceQry.Where( xx => xx.CreatedDateTime >= dateRange.Start.Value );
                    }

                    if ( dateRange.End.HasValue )
                    {
                        registrationRegistrantServiceQry = registrationRegistrantServiceQry.Where( xx => xx.CreatedDateTime < dateRange.End.Value );
                    }
                }

                var qry = new PersonService( (RockContext)serviceInstance.Context ).Queryable()
                    .Where( p => registrationRegistrantServiceQry.Any( xx => xx.PersonAlias.PersonId == p.Id ) );

                Expression extractedFilterExpression = FilterExpressionExtractor.Extract<Rock.Model.Person>( qry, parameterExpression, "p" );

                return extractedFilterExpression;
            }

            return null;
        }
        /// <summary>
        /// Handles the Click event of the DeleteGroupMember control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Rock.Web.UI.Controls.RowEventArgs" /> instance containing the event data.</param>
        protected void DeleteGroupMember_Click( object sender, Rock.Web.UI.Controls.RowEventArgs e )
        {
            RockContext rockContext = new RockContext();
            GroupMemberService groupMemberService = new GroupMemberService( rockContext );
            RegistrationRegistrantService registrantService = new RegistrationRegistrantService( rockContext );
            GroupMember groupMember = groupMemberService.Get( e.RowKeyId );
            if ( groupMember != null )
            {
                string errorMessage;
                if ( !groupMemberService.CanDelete( groupMember, out errorMessage ) )
                {
                    mdGridWarning.Show( errorMessage, ModalAlertType.Information );
                    return;
                }

                int groupId = groupMember.GroupId;

                foreach ( var registrant in registrantService.Queryable().Where( r => r.GroupMemberId == groupMember.Id ) )
                {
                    registrant.GroupMemberId = null;
                }

                groupMemberService.Delete( groupMember );

                rockContext.SaveChanges();

                Group group = new GroupService( rockContext ).Get( groupId );
                if ( group.IsSecurityRole || group.GroupType.Guid.Equals( Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid() ) )
                {
                    // person removed from SecurityRole, Flush
                    Rock.Security.Role.Flush( group.Id );
                }
            }

            BindGroupMembersGrid();
        }