Ejemplo n.º 1
0
        /// <summary>
        /// Handles the Click event of the btnSaveType 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)
        {
            bool inviteCancelled = false;

            var rockContext = new RockContext();

            int?documentTemplateId = ddlDocumentType.SelectedValueAsInt();

            if (!documentTemplateId.HasValue)
            {
                nbErrorMessage.Title = string.Empty;
                nbErrorMessage.Text  = "Document Template is Required!";
                nbErrorMessage.NotificationBoxType = NotificationBoxType.Danger;
                nbErrorMessage.Visible             = true;
                return;
            }

            SignatureDocument        signatureDocument = null;
            SignatureDocumentService service           = new SignatureDocumentService(rockContext);

            int signatureDocumentId = hfSignatureDocumentId.ValueAsInt();

            int?origBinaryFileId = null;

            if (signatureDocumentId != 0)
            {
                signatureDocument = service.Get(signatureDocumentId);
            }

            if (signatureDocument == null)
            {
                signatureDocument = new SignatureDocument();
                service.Add(signatureDocument);
            }

            signatureDocument.Name = tbName.Text;

            var newStatus = rbStatus.SelectedValueAsEnum <SignatureDocumentStatus>(SignatureDocumentStatus.None);

            if (signatureDocument.Status != newStatus)
            {
                signatureDocument.Status         = newStatus;
                signatureDocument.LastStatusDate = RockDateTime.Now;
                inviteCancelled = newStatus == SignatureDocumentStatus.Cancelled;
            }

            signatureDocument.AppliesToPersonAliasId  = ppAppliesTo.PersonAliasId;
            signatureDocument.AssignedToPersonAliasId = ppAssignedTo.PersonAliasId;
            signatureDocument.SignedByPersonAliasId   = ppSignedBy.PersonAliasId;

            signatureDocument.SignatureDocumentTemplateId = documentTemplateId.Value;

            origBinaryFileId = signatureDocument.BinaryFileId;
            signatureDocument.BinaryFileId = fuDocument.BinaryFileId;

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

            BinaryFileService binaryFileService = new BinaryFileService(rockContext);

            if (origBinaryFileId.HasValue && origBinaryFileId.Value != signatureDocument.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 (signatureDocument.BinaryFileId.HasValue)
            {
                var binaryFile = binaryFileService.Get(signatureDocument.BinaryFileId.Value);
                if (binaryFile != null && binaryFile.IsTemporary)
                {
                    binaryFile.IsTemporary = false;
                }
            }

            rockContext.SaveChanges();

            if (inviteCancelled && !string.IsNullOrWhiteSpace(signatureDocument.DocumentKey))
            {
                var errorMessages = new List <string>();
                if (new SignatureDocumentTemplateService(rockContext).CancelDocument(signatureDocument, out errorMessages))
                {
                    rockContext.SaveChanges();
                }
            }

            ReturnToParent();
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Shows the detail.
        /// </summary>
        /// <param name="groupMemberId">The group member identifier.</param>
        /// <param name="groupId">The group id.</param>
        public void ShowDetail(int groupMemberId, int?groupId)
        {
            // autoexpand the person picker if this is an add
            var personPickerStartupScript = @"Sys.Application.add_load(function () {

                // if the person picker is empty then open it for quick entry
                var personPicker = $('.js-authorizedperson');
                var currentPerson = personPicker.find('.picker-selectedperson').html();
                if (currentPerson != null && currentPerson.length == 0) {
                    $(personPicker).find('a.picker-label').trigger('click');
                }

            });";

            this.Page.ClientScript.RegisterStartupScript(this.GetType(), "StartupScript", personPickerStartupScript, true);

            var         rockContext = new RockContext();
            GroupMember groupMember = null;

            if (!groupMemberId.Equals(0))
            {
                groupMember = new GroupMemberService(rockContext).Get(groupMemberId);
                pdAuditDetails.SetEntity(groupMember, ResolveRockUrl("~"));
            }
            else
            {
                // only create a new one if parent was specified
                if (groupId.HasValue)
                {
                    groupMember = new GroupMember {
                        Id = 0
                    };
                    groupMember.GroupId           = groupId.Value;
                    groupMember.Group             = new GroupService(rockContext).Get(groupMember.GroupId);
                    groupMember.GroupRoleId       = groupMember.Group.GroupType.DefaultGroupRoleId ?? 0;
                    groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                    groupMember.DateTimeAdded     = RockDateTime.Now;
                    // hide the panel drawer that show created and last modified dates
                    pdAuditDetails.Visible = false;
                }
            }

            if (groupMember == null)
            {
                if (groupMemberId > 0)
                {
                    nbErrorMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Warning;
                    nbErrorMessage.Title = "Warning";
                    nbErrorMessage.Text  = "Group Member not found. Group Member may have been moved to another group or deleted.";
                }
                else
                {
                    nbErrorMessage.NotificationBoxType = Rock.Web.UI.Controls.NotificationBoxType.Danger;
                    nbErrorMessage.Title = "Invalid Request";
                    nbErrorMessage.Text  = "An incorrect querystring parameter was used.  A valid GroupMemberId or GroupId parameter is required.";
                }

                pnlEditDetails.Visible = false;
                return;
            }

            pnlEditDetails.Visible = true;

            hfGroupId.Value       = groupMember.GroupId.ToString();
            hfGroupMemberId.Value = groupMember.Id.ToString();

            if (IsUserAuthorized(Authorization.ADMINISTRATE))
            {
                cbIsNotified.Checked = groupMember.IsNotified;
                cbIsNotified.Visible = true;
                cbIsNotified.Help    = "If this box is unchecked and a <a href=\"http://www.rockrms.com/Rock/BookContent/7/#servicejobsrelatingtogroups\">group leader notification job</a> is enabled then a notification will be sent to the group's leaders when this group member is saved.";
            }
            else
            {
                cbIsNotified.Visible = false;
            }

            // render UI based on Authorized and IsSystem
            bool readOnly = false;

            var group = groupMember.Group;

            if (!string.IsNullOrWhiteSpace(group.GroupType.IconCssClass))
            {
                lGroupIconHtml.Text = string.Format("<i class='{0}' ></i>", group.GroupType.IconCssClass);
            }
            else
            {
                lGroupIconHtml.Text = "<i class='fa fa-user' ></i>";
            }

            if (groupMember.Id.Equals(0))
            {
                lReadOnlyTitle.Text    = ActionTitle.Add(groupMember.Group.GroupType.GroupTerm + " " + groupMember.Group.GroupType.GroupMemberTerm).FormatAsHtmlTitle();
                btnSaveThenAdd.Visible = true;
            }
            else
            {
                lReadOnlyTitle.Text    = groupMember.Person.FullName.FormatAsHtmlTitle();
                btnSaveThenAdd.Visible = false;
            }

            if (groupMember.DateTimeAdded.HasValue)
            {
                hfDateAdded.Text    = string.Format("Added: {0}", groupMember.DateTimeAdded.Value.ToShortDateString());
                hfDateAdded.Visible = true;
            }
            else
            {
                hfDateAdded.Text    = string.Empty;
                hfDateAdded.Visible = false;
            }

            // user has to have EDIT Auth to the Block OR the group
            nbEditModeMessage.Text = string.Empty;
            if (!IsUserAuthorized(Authorization.EDIT) && !group.IsAuthorized(Authorization.EDIT, this.CurrentPerson))
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(Group.FriendlyTypeName);
            }

            if (groupMember.IsSystem)
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlySystem(Group.FriendlyTypeName);
            }

            btnSave.Visible = !readOnly;

            if (readOnly || groupMember.Id == 0)
            {
                // hide the ShowMoveDialog if this is readOnly or if this is a new group member (can't move a group member that doesn't exist yet)
                btnShowMoveDialog.Visible = false;
            }

            LoadDropDowns();

            ShowRequiredDocumentStatus(rockContext, groupMember, group);

            ppGroupMemberPerson.SetValue(groupMember.Person);
            ppGroupMemberPerson.Enabled = !readOnly;

            if (groupMember.Id != 0)
            {
                // once a group member record is saved, don't let them change the person
                ppGroupMemberPerson.Enabled = false;
            }

            ddlGroupRole.SetValue(groupMember.GroupRoleId);
            ddlGroupRole.Enabled = !readOnly;

            tbNote.Text     = groupMember.Note;
            tbNote.ReadOnly = readOnly;

            rblStatus.SetValue((int)groupMember.GroupMemberStatus);
            rblStatus.Enabled = !readOnly;
            rblStatus.Label   = string.Format("{0} Status", group.GroupType.GroupMemberTerm);

            var registrations = new RegistrationRegistrantService(rockContext)
                                .Queryable().AsNoTracking()
                                .Where(r =>
                                       r.Registration != null &&
                                       r.Registration.RegistrationInstance != null &&
                                       r.GroupMemberId.HasValue &&
                                       r.GroupMemberId.Value == groupMember.Id)
                                .Select(r => new
            {
                Id   = r.Registration.Id,
                Name = r.Registration.RegistrationInstance.Name
            })
                                .ToList();

            if (registrations.Any())
            {
                rcwLinkedRegistrations.Visible    = true;
                rptLinkedRegistrations.DataSource = registrations;
                rptLinkedRegistrations.DataBind();
            }
            else
            {
                rcwLinkedRegistrations.Visible = false;
            }

            if (groupMember.Group.RequiredSignatureDocumentTemplate != null)
            {
                fuSignedDocument.Label = groupMember.Group.RequiredSignatureDocumentTemplate.Name;
                if (groupMember.Group.RequiredSignatureDocumentTemplate.BinaryFileType != null)
                {
                    fuSignedDocument.BinaryFileTypeGuid = groupMember.Group.RequiredSignatureDocumentTemplate.BinaryFileType.Guid;
                }

                var signatureDocument = new SignatureDocumentService(rockContext)
                                        .Queryable().AsNoTracking()
                                        .Where(d =>
                                               d.SignatureDocumentTemplateId == groupMember.Group.RequiredSignatureDocumentTemplateId.Value &&
                                               d.AppliesToPersonAlias != null &&
                                               d.AppliesToPersonAlias.PersonId == groupMember.PersonId &&
                                               d.LastStatusDate.HasValue &&
                                               d.Status == SignatureDocumentStatus.Signed &&
                                               d.BinaryFile != null)
                                        .OrderByDescending(d => d.LastStatusDate.Value)
                                        .FirstOrDefault();

                if (signatureDocument != null)
                {
                    hfSignedDocumentId.Value      = signatureDocument.Id.ToString();
                    fuSignedDocument.BinaryFileId = signatureDocument.BinaryFileId;
                }

                fuSignedDocument.Visible = true;
            }
            else
            {
                fuSignedDocument.Visible = false;
            }

            groupMember.LoadAttributes();
            phAttributes.Controls.Clear();

            Rock.Attribute.Helper.AddEditControls(groupMember, phAttributes, true, string.Empty, true);
            if (readOnly)
            {
                Rock.Attribute.Helper.AddDisplayControls(groupMember, phAttributesReadOnly);
                phAttributesReadOnly.Visible = true;
                phAttributes.Visible         = false;
            }
            else
            {
                phAttributesReadOnly.Visible = false;
                phAttributes.Visible         = true;
            }

            var groupHasRequirements = group.GroupRequirements.Any();

            pnlRequirements.Visible        = groupHasRequirements;
            btnReCheckRequirements.Visible = groupHasRequirements;

            ShowGroupRequirementsStatuses();
        }
Ejemplo n.º 3
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();
        }
Ejemplo n.º 4
0
        private void SaveGroupMember()
        {
            if (Page.IsValid)
            {
                var rockContext = new RockContext();

                // Verify valid group
                var groupService = new GroupService(rockContext);
                var group        = groupService.Get(hfGroupId.ValueAsInt());
                if (group == null)
                {
                    nbErrorMessage.Title = "Please select a Role";
                    return;
                }

                // Check to see if a person was selected
                int?personId      = ppGroupMemberPerson.PersonId;
                int?personAliasId = ppGroupMemberPerson.PersonAliasId;
                if (!personId.HasValue || !personAliasId.HasValue)
                {
                    nbErrorMessage.Title = "Please select a Person";
                    return;
                }

                // check to see if the user selected a role
                var role = new GroupTypeRoleService(rockContext).Get(ddlGroupRole.SelectedValueAsInt() ?? 0);
                if (role == null)
                {
                    nbErrorMessage.Title = "Please select a Role";
                    return;
                }

                var         groupMemberService            = new GroupMemberService(rockContext);
                var         groupMemberRequirementService = new GroupMemberRequirementService(rockContext);
                GroupMember groupMember;

                int groupMemberId = int.Parse(hfGroupMemberId.Value);

                // if adding a new group member
                if (groupMemberId.Equals(0))
                {
                    groupMember = new GroupMember {
                        Id = 0
                    };
                    groupMember.GroupId = group.Id;
                }
                else
                {
                    // load existing group member
                    groupMember = groupMemberService.Get(groupMemberId);
                }

                groupMember.PersonId          = personId.Value;
                groupMember.GroupRoleId       = role.Id;
                groupMember.Note              = tbNote.Text;
                groupMember.GroupMemberStatus = rblStatus.SelectedValueAsEnum <GroupMemberStatus>();

                if (cbIsNotified.Visible)
                {
                    groupMember.IsNotified = cbIsNotified.Checked;
                }

                if (pnlRequirements.Visible)
                {
                    foreach (var checkboxItem in cblManualRequirements.Items.OfType <ListItem>())
                    {
                        int  groupRequirementId     = checkboxItem.Value.AsInteger();
                        var  groupMemberRequirement = groupMember.GroupMemberRequirements.FirstOrDefault(a => a.GroupRequirementId == groupRequirementId);
                        bool metRequirement         = checkboxItem.Selected;
                        if (metRequirement)
                        {
                            if (groupMemberRequirement == null)
                            {
                                groupMemberRequirement = new GroupMemberRequirement();
                                groupMemberRequirement.GroupRequirementId = groupRequirementId;

                                groupMember.GroupMemberRequirements.Add(groupMemberRequirement);
                            }

                            // set the RequirementMetDateTime if it hasn't been set already
                            groupMemberRequirement.RequirementMetDateTime = groupMemberRequirement.RequirementMetDateTime ?? RockDateTime.Now;

                            groupMemberRequirement.LastRequirementCheckDateTime = RockDateTime.Now;
                        }
                        else
                        {
                            if (groupMemberRequirement != null)
                            {
                                // doesn't meets the requirement
                                groupMemberRequirement.RequirementMetDateTime       = null;
                                groupMemberRequirement.LastRequirementCheckDateTime = RockDateTime.Now;
                            }
                        }
                    }
                }

                if (group.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)
                    {
                        document = new SignatureDocument();
                        document.SignatureDocumentTemplateId = group.RequiredSignatureDocumentTemplate.Id;
                        document.AppliesToPersonAliasId      = personAliasId.Value;
                        document.AssignedToPersonAliasId     = personAliasId.Value;
                        document.Name = string.Format("{0}_{1}",
                                                      group.Name.RemoveSpecialCharacters(),
                                                      (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;
                            }
                        }
                    }
                }

                groupMember.LoadAttributes();

                Rock.Attribute.Helper.GetEditValues(phAttributes, groupMember);

                if (!Page.IsValid)
                {
                    return;
                }

                // if the groupMember IsValid is false, and the UI controls didn't report any errors, it is probably because the custom rules of GroupMember didn't pass.
                // So, make sure a message is displayed in the validation summary
                cvGroupMember.IsValid = groupMember.IsValid;

                if (!cvGroupMember.IsValid)
                {
                    cvGroupMember.ErrorMessage = groupMember.ValidationResults.Select(a => a.ErrorMessage).ToList().AsDelimited("<br />");
                    return;
                }

                // using WrapTransaction because there are three Saves
                rockContext.WrapTransaction(() =>
                {
                    if (groupMember.Id.Equals(0))
                    {
                        groupMemberService.Add(groupMember);
                    }

                    rockContext.SaveChanges();
                    groupMember.SaveAttributeValues(rockContext);
                });

                groupMember.CalculateRequirements(rockContext, true);

                if (group.IsSecurityRole || group.GroupType.Guid.Equals(Rock.SystemGuid.GroupType.GROUPTYPE_SECURITY_ROLE.AsGuid()))
                {
                    Rock.Security.Role.Flush(group.Id);
                }
            }
        }