示例#1
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            if ( !Page.IsPostBack )
            {
                string groupId = PageParameter( "GroupId" );
                string groupMemberId = PageParameter( "GroupMemberId" );
                if ( !string.IsNullOrWhiteSpace( groupMemberId ) )
                {
                    if ( string.IsNullOrWhiteSpace( groupId ) )
                    {
                        ShowDetail( "GroupMemberId", int.Parse( groupMemberId ) );
                    }
                    else
                    {
                        ShowDetail( "GroupMemberId", int.Parse( groupMemberId ), int.Parse( groupId ) );
                    }
                }
                else
                {
                    upDetail.Visible = false;
                }
            }
            else
            {
                var groupMember = new GroupMember { GroupId = hfGroupId.ValueAsInt() };
                if ( groupMember != null )
                {
                    groupMember.LoadAttributes();
                    phAttributes.Controls.Clear();
                    Rock.Attribute.Helper.AddEditControls( groupMember, phAttributes, false );
                }
            }
        }
示例#2
0
 public void Register(GroupMember member)
 {
     if (! members.Contains(member)) {
         count++;
         members.Add(member);
     }
 }
 /// <summary>
 /// Builds and returns the GroupMember object.
 /// </summary>
 /// <returns>the GroupMember object</returns>
 public GroupMember Build()
 {
     GroupMember groupMember = new GroupMember
     {
         Email = this.email
     };
     return groupMember;
 }
示例#4
0
 public void DeleteGroupMember(GroupMember groupMember)
 {
     using (SPKTDataContext dc = conn.GetContext())
     {
         dc.GroupMembers.Attach(groupMember, true);
         dc.GroupMembers.DeleteOnSubmit(groupMember);
         dc.SubmitChanges();
     }
 }
示例#5
0
 public static void UpdateCharacterGroup(GroupMember pMember)
 {
     using (var client = Program.DatabaseManager.GetClient())
     {
         string q = string.Format(UpdateCharacterGroupQuery,
                     pMember.Group.Id,
                     pMember.Role == GroupRole.Master,
                     pMember.Character.ID);
         client.ExecuteQuery(q);
     }
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="GroupMemberPlacedElsewhereTransaction" /> class.
 /// </summary>
 /// <param name="groupMember">The group member of the current group they are in (before being deleted and processed) </param>
 /// <param name="note">The note.</param>
 /// <param name="trigger">The GroupMemberWorkflowTrigger.</param>
 public GroupMemberPlacedElsewhereTransaction( GroupMember groupMember, string note, GroupMemberWorkflowTrigger trigger )
 {
     this.Trigger = trigger;
     this.GroupId = groupMember.GroupId;
     this.PersonId = groupMember.PersonId;
     this.GroupMemberStatusName = groupMember.GroupMemberStatus.ConvertToString();
     this.GroupMemberRoleName = groupMember.GroupRole.ToString();
     groupMember.LoadAttributes();
     this.GroupMemberAttributeValues = groupMember.AttributeValues.ToDictionary( k => k.Key, v => v.Value.Value );
     this.Note = note;
 }
示例#7
0
 /*
 This needs to be static because if the Group is destroyed before
 all of its members, then it might be inadvertently recreated.
   */
 public static void Deregister(GroupMember member)
 {
     var o = GameObject.Find(member.groupName);
     if (o != null) {
         Group group = Group.GetGroup(member.groupName);
         if (group.members.Contains(member)) {
             group.count--;
             group.members.Remove(member);
         }
     }
 }
示例#8
0
        internal static GroupMember GroupMember(GroupMemberEntity data)
        {
            GroupMember ent = new GroupMember();

            ent.Id = data.groupMemberId;
            ent.GroupFK = data.groupFK;
            ent.MemberFK = data.memberFK;
            ent.IsAdmin = data.isAdmin;
            ent.UpdateTimestamp = data.updateTimestamp;
            ent.UpdatePersonFK = data.updatePersonFK;

            return ent;
        }
示例#9
0
        internal static GroupMemberEntity GroupMember(GroupMember ent)
        {
            GroupMemberEntity data = new GroupMemberEntity();

            data.groupMemberId = ent.Id;
            data.groupFK = ent.GroupFK;
            data.memberFK = ent.MemberFK;
            data.isAdmin = ent.IsAdmin;
            data.updateTimestamp = ent.UpdateTimestamp;
            data.updatePersonFK = ent.UpdatePersonFK;

            return data;
        }
示例#10
0
 public void RequestMembership()
 {
     if (_webContext.CurrentUser != null)
     {
         GroupMember gm = new GroupMember();
         gm.AccountID = _webContext.CurrentUser.AccountID;
         gm.GroupID = _webContext.GroupID;
         gm.CreateDate = DateTime.Now;
         gm.IsAdmin = false;
         gm.IsApproved = false;
         _groupMemberRepository.SaveGroupMember(gm);
         ShowMessage("Membership requested successfully!");
     }
 }
示例#11
0
 public void RequestMembership()
 {
     if (_webContext.CurrentUser != null)
     {
         GroupMember gm = new GroupMember();
         gm.AccountID = _webContext.CurrentUser.AccountID;
         gm.GroupID = _webContext.GroupID;
         gm.CreateDate = DateTime.Now;
         gm.IsAdmin = false;
         gm.IsApproved = false;
         _groupMemberRepository.SaveGroupMember(gm);
         ShowMessage("Yêu cầu thành công!Cảm ơn bạn đã quan tâm đến nhóm! Chờ Admin Group chấp nhận yêu cầu của bạn");
     }
 }
示例#12
0
        public GroupMember InviteMember( GroupId groupId, GroupMember groupMember ) {
            string path = template.UrlFor (UrlTemplate.GROUPS_MEMBER_PATH)
				.Replace("{groupId}", groupId.Id )
                .Build ();
			Silanis.ESL.API.GroupMember apiGroupMember = new GroupMemberConverter(groupMember).ToAPIGroupMember();
            try {
				string json = JsonConvert.SerializeObject (apiGroupMember, settings);
                string response = restClient.Post(path, json);              
				Silanis.ESL.API.GroupMember apiResponse = JsonConvert.DeserializeObject<Silanis.ESL.API.GroupMember> (response);
				return new GroupMemberConverter( apiResponse ).ToSDKGroupMember();
            } catch (Exception e) {
                throw new EslException ("Could not create a new package." + " Exception: " + e.Message);
            }
        }
示例#13
0
        public Contracts.GenericListResult<Contracts.SmallGroupMember> GetSmallGroupMembers(int groupID, int start, int max)
        {
            Contracts.GenericListResult<Contracts.SmallGroupMember> list = new Contracts.GenericListResult<Contracts.SmallGroupMember>();
            Contracts.SmallGroupMemberMapper mapper = new Contracts.SmallGroupMemberMapper();
            Group group = new Group(groupID);
            GroupMember leader = new GroupMember(groupID, group.Leader);
            leader.Role = new Lookup(new Guid("029B270C-7B7A-499F-8006-CC3211C91E95"));
            group.Members.Add(leader);

            Boolean accessDenied = false;
            // If this person isn't the outright leader and they don't have view access
            if (group.Leader.PersonID != ArenaContext.Current.Person.PersonID &&
                RestApi.GroupClusterOperationAllowed(ArenaContext.Current.Person.PersonID, group.GroupClusterID, OperationType.View) == false) {

                accessDenied = true;

                // Do a deeper dive into each member of the group
                foreach(GroupMember gm in group.Members) {
                    if (gm.Active && gm.Role.Value == "Leader")
                    {
                        accessDenied = false;
                        break;
                    }
                }
            }
            if (accessDenied) {
                throw new Exception("Access denied.");
            }

            list.Start = start;
            list.Max = max;
            list.Total = group.Members.Count;
            list.Items = new List<Contracts.SmallGroupMember>();

            int i;
            for (i = start; i < group.Members.Count && (max <= 0 || i < (start + max)); i++)
            {
                list.Items.Add(mapper.FromArena(group.Members[i]));
            }

            return list;
        }
            public override void Init(StoC_0x16_VariousUpdate pak)
            {
                groupMembers = new GroupMember[pak.SubCount];

                m_oids = new ushort[pak.SubCount];
                for (int i = 0; i < pak.SubCount; i++)
                {
                    GroupMember member = new GroupMember();

                    member.level = pak.ReadByte();
                    member.health = pak.ReadByte();
                    member.mana = pak.ReadByte();
                    member.endurance = pak.ReadByte(); // new in 1.69
                    member.status = pak.ReadByte();
                    member.oid = pak.ReadShort();
                    member.name = pak.ReadPascalString();
                    member.classname = pak.ReadPascalString();
                    m_oids[i] = member.oid;

                    groupMembers[i] = member;
                }
            }
示例#15
0
        private void ReceiveBadgeList(GroupMember member)
        {
            uint count = 0;
            if (!currentUsers.TryGetValue(member.Group, out count))
            {
                currentUsers.Add(member.Group, 1);

                ServerMessage message = PacketHandelingManager.GetRecycledItem(OutputCode.SendGroup);
                message.AddInt32(1);
                message.AddUInt32(member.Group.ID);
                message.AddString(member.Group.image);
                broadcaster.SendMessage(message);
            }
            else
            {
                currentUsers[member.Group] = ++count;
            }

            GameClient client = ButterflyEnvironment.GetGame().GetClientManager().GetClient(member.data.Id);
            if (client != null)
                client.SendMessage(SerializeList());
        }
示例#16
0
        private void UserLeaving(GroupMember member)
        {
            // unload fix

            uint count = 0;

            if (currentUsers != null)
            {
                if (member != null)
                {
                    if (member.Group != null)
                    {
                        if (currentUsers.TryGetValue(member.Group, out count))
                        {
                            if (count > 1)
                                currentUsers[member.Group] = --count;
                            else
                                currentUsers.Remove(member.Group);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Adds the group member.
        /// </summary>
        /// <param name="familyGroup">The family group.</param>
        /// <param name="person">The person.</param>
        /// <returns></returns>
        protected GroupMember AddGroupMember( int familyGroupId, Person person )
        {
            var rockContext = new RockContext();

            GroupMember groupMember = new GroupMember();
            groupMember.IsSystem = false;
            groupMember.GroupId = familyGroupId;
            groupMember.PersonId = person.Id;
            if ( person.Age >= 18 )
            {
                groupMember.GroupRoleId = new GroupTypeRoleService( rockContext ).Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ).Id;
            }
            else
            {
                groupMember.GroupRoleId = new GroupTypeRoleService( rockContext ).Get( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) ).Id;
            }

            GroupMemberService groupMemberService = new GroupMemberService( rockContext );
            groupMemberService.Add( groupMember );
            rockContext.SaveChanges();

            return groupMember;
        }
        /// <summary>
        /// Writes to package.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model">The model.</param>
        public static void WriteToPackage <T>(T model)
        {
            var typeName = model.GetType().Name;

            if (model is IImportModel)
            {
                var importModel = (IImportModel)model;
                // check if a textwriter is needed for this model type
                if (!textWriters.ContainsKey(typeName))
                {
                    if (!Directory.Exists(_packageDirectory))
                    {
                        InitalizePackageFolder();
                    }

                    textWriters.Add(typeName, (TextWriter)File.CreateText($@"{_packageDirectory}\{importModel.GetFileName()}"));

                    // if model is for person create related writers
                    if (importModel is Person)
                    {
                        // person attributes
                        var personAttributeValue = new PersonAttributeValue();
                        textWriters.Add(personAttributeValue.GetType().Name, (TextWriter)File.CreateText($@"{_packageDirectory}\{personAttributeValue.GetFileName()}"));

                        // person phones
                        var personPhone = new PersonPhone();
                        textWriters.Add(personPhone.GetType().Name, (TextWriter)File.CreateText($@"{_packageDirectory}\{personPhone.GetFileName()}"));

                        // person addresses
                        var personAddress = new PersonAddress();
                        textWriters.Add(personAddress.GetType().Name, (TextWriter)File.CreateText($@"{_packageDirectory}\{personAddress.GetFileName()}"));
                    }

                    // if model is for financial batch create related writers
                    if (importModel is FinancialBatch)
                    {
                        // financial transactions
                        var financialTransaction = new FinancialTransaction();
                        textWriters.Add(financialTransaction.GetType().Name, (TextWriter)File.CreateText($@"{_packageDirectory}\{financialTransaction.GetFileName()}"));

                        // financial transation details
                        var financialTransactionDetail = new FinancialTransactionDetail();
                        textWriters.Add(financialTransactionDetail.GetType().Name, (TextWriter)File.CreateText($@"{_packageDirectory}\{financialTransactionDetail.GetFileName()}"));
                    }

                    // if model is for group create related writers
                    if (importModel is Group)
                    {
                        // group member
                        var groupMember = new GroupMember();
                        textWriters.Add(groupMember.GetType().Name, ( TextWriter )File.CreateText($@"{_packageDirectory}\{groupMember.GetFileName()}"));
                    }
                }

                var txtWriter = textWriters[typeName];

                // check if a csvwriter is needed for this model type
                if (!csvWriters.ContainsKey(typeName))
                {
                    var newCsvWriter = new CsvWriter(txtWriter);
                    csvWriters.Add(typeName, newCsvWriter);
                    newCsvWriter.WriteHeader <T>();
                    //newCsvWriter.Configuration.QuoteAllFields = true;

                    // if model is for person create related writers
                    if (importModel is Person)
                    {
                        // person attributes
                        var personAttributeValue             = new PersonAttributeValue();
                        var newPersonAttributeValueCsvWriter = new CsvWriter(textWriters[personAttributeValue.GetType().Name]);
                        csvWriters.Add(personAttributeValue.GetType().Name, newPersonAttributeValueCsvWriter);
                        newPersonAttributeValueCsvWriter.WriteHeader <PersonAttributeValue>();

                        // person phones
                        var personPhone             = new PersonPhone();
                        var newPersonPhoneCsvWriter = new CsvWriter(textWriters[personPhone.GetType().Name]);
                        csvWriters.Add(personPhone.GetType().Name, newPersonPhoneCsvWriter);
                        newPersonPhoneCsvWriter.WriteHeader <PersonPhone>();

                        // person addresses
                        var personAddress             = new PersonAddress();
                        var newPersonAddressCsvWriter = new CsvWriter(textWriters[personAddress.GetType().Name]);
                        csvWriters.Add(personAddress.GetType().Name, newPersonAddressCsvWriter);
                        newPersonAddressCsvWriter.WriteHeader <PersonAddress>();
                    }

                    // if model is for financial batch create related writers
                    if (importModel is FinancialBatch)
                    {
                        // financial transaction
                        var financialTransaction             = new FinancialTransaction();
                        var newFinancialTransactionCsvWriter = new CsvWriter(textWriters[financialTransaction.GetType().Name]);
                        csvWriters.Add(financialTransaction.GetType().Name, newFinancialTransactionCsvWriter);
                        newFinancialTransactionCsvWriter.WriteHeader <FinancialTransaction>();

                        // financial transaction detail
                        var financialTransactionDetail             = new FinancialTransactionDetail();
                        var newFinancialTransactionDetailCsvWriter = new CsvWriter(textWriters[financialTransactionDetail.GetType().Name]);
                        csvWriters.Add(financialTransactionDetail.GetType().Name, newFinancialTransactionDetailCsvWriter);
                        newFinancialTransactionDetailCsvWriter.WriteHeader <FinancialTransactionDetail>();
                    }

                    // if model is for group create related writers
                    if (importModel is Group)
                    {
                        // group member
                        var groupMember             = new GroupMember();
                        var newGroupMemberCsvWriter = new CsvWriter(textWriters[groupMember.GetType().Name]);
                        csvWriters.Add(groupMember.GetType().Name, newGroupMemberCsvWriter);
                        newGroupMemberCsvWriter.WriteHeader <GroupMember>();
                    }
                }

                var csvWriter = csvWriters[typeName];

                csvWriter.WriteRecord <T>(model);

                // if person model write out any related models
                if (importModel is Person)
                {
                    // person attributes
                    var personAttributeValue          = new PersonAttributeValue();
                    var csvPersonAttributeValueWriter = csvWriters[personAttributeValue.GetType().Name];

                    if (csvPersonAttributeValueWriter != null)
                    {
                        foreach (var attribute in ((Person)importModel).Attributes)
                        {
                            csvPersonAttributeValueWriter.WriteRecord <PersonAttributeValue>(attribute);
                        }
                    }

                    // person phones
                    var personPhone          = new PersonPhone();
                    var csvPersonPhoneWriter = csvWriters[personPhone.GetType().Name];

                    if (csvPersonPhoneWriter != null)
                    {
                        foreach (var phone in ((Person)importModel).PhoneNumbers)
                        {
                            csvPersonPhoneWriter.WriteRecord <PersonPhone>(phone);
                        }
                    }

                    // person addresses
                    var personAddress          = new PersonAddress();
                    var csvPersonAddressWriter = csvWriters[personAddress.GetType().Name];

                    if (csvPersonAddressWriter != null)
                    {
                        foreach (var address in ((Person)importModel).Addresses)
                        {
                            csvPersonAddressWriter.WriteRecord <PersonAddress>(address);
                        }
                    }
                }

                // if financial model write out any related models
                if (importModel is FinancialBatch)
                {
                    // write out financial transactions and transaction details
                    var financialTransaction          = new FinancialTransaction();
                    var csvFinancialTransactionWriter = csvWriters[financialTransaction.GetType().Name];

                    var financialTransactionDetail          = new FinancialTransactionDetail();
                    var csvFinancialTransactionDetailWriter = csvWriters[financialTransactionDetail.GetType().Name];

                    if (csvFinancialTransactionWriter != null && csvFinancialTransactionDetailWriter != null)
                    {
                        foreach (var transaction in ((FinancialBatch)importModel).FinancialTransactions)
                        {
                            csvFinancialTransactionWriter.WriteRecord <FinancialTransaction>(transaction);

                            foreach (var transactionDetail in transaction.FinancialTransactionDetails)
                            {
                                csvFinancialTransactionDetailWriter.WriteRecord <FinancialTransactionDetail>(transactionDetail);
                            }
                        }
                    }
                }

                // if group model write out any related models
                if (importModel is Group)
                {
                    // group members
                    var groupMember          = new GroupMember();
                    var csvGroupMemberWriter = csvWriters[groupMember.GetType().Name];

                    if (csvGroupMemberWriter != null)
                    {
                        foreach (var groupMemberItem in (( Group )importModel).GroupMembers)
                        {
                            csvGroupMemberWriter.WriteRecord <GroupMember>(groupMemberItem);
                        }
                    }
                }
            }
        }
示例#19
0
        private Group SaveNewPerson(Rock.Model.Person person, Group existingFamily, int?defaultCampus, RockContext rockContext)
        {
            if (existingFamily == null)
            {
                return(PersonService.SaveNewPerson(person, rockContext, (defaultCampus != null ? defaultCampus : ( int? )null), false));
            }
            else
            {
                person.FirstName  = person.FirstName.FixCase();
                person.NickName   = person.NickName.FixCase();
                person.MiddleName = person.MiddleName.FixCase();
                person.LastName   = person.LastName.FixCase();

                // Create/Save Known Relationship Group
                var knownRelationshipGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS);
                if (knownRelationshipGroupType != null)
                {
                    var ownerRole = knownRelationshipGroupType.Roles
                                    .FirstOrDefault(r =>
                                                    r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid()));
                    if (ownerRole != null)
                    {
                        var groupMember = new GroupMember();
                        groupMember.Person      = person;
                        groupMember.GroupRoleId = ownerRole.Id;

                        var group = new Group();
                        group.Name        = knownRelationshipGroupType.Name;
                        group.GroupTypeId = knownRelationshipGroupType.Id;
                        group.Members.Add(groupMember);

                        var groupService = new GroupService(rockContext);
                        groupService.Add(group);
                    }
                }

                // Create/Save Implied Relationship Group
                var impliedRelationshipGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_PEER_NETWORK);
                if (impliedRelationshipGroupType != null)
                {
                    var ownerRole = impliedRelationshipGroupType.Roles
                                    .FirstOrDefault(r =>
                                                    r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_PEER_NETWORK_OWNER.AsGuid()));
                    if (ownerRole != null)
                    {
                        var groupMember = new GroupMember();
                        groupMember.Person      = person;
                        groupMember.GroupRoleId = ownerRole.Id;

                        var group = new Group();
                        group.Name        = impliedRelationshipGroupType.Name;
                        group.GroupTypeId = impliedRelationshipGroupType.Id;
                        group.Members.Add(groupMember);

                        var groupService = new GroupService(rockContext);
                        groupService.Add(group);
                    }
                }
                var familyGroupType = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY);

                var adultRole = familyGroupType?.Roles
                                .FirstOrDefault(r =>
                                                r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()));

                var childRole = familyGroupType?.Roles
                                .FirstOrDefault(r =>
                                                r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()));

                var age = person.Age;

                var familyRole = age.HasValue && age < 18 ? childRole : adultRole;

                // Add to the existing family
                PersonService.AddPersonToFamily(person, true, existingFamily.Id, familyRole.Id, rockContext);
                return(existingFamily);
            }
        }
示例#20
0
        /// <summary>
        /// Saves the individuals.
        /// </summary>
        /// <param name="newFamilyList">The family list.</param>
        /// <param name="visitorList">The optional visitor list.</param>
        private void SaveIndividuals(List <Group> newFamilyList, List <Group> visitorList = null, List <Note> newNoteList = null)
        {
            if (newFamilyList.Any())
            {
                var rockContext = new RockContext();
                rockContext.WrapTransaction(() =>
                {
                    rockContext.Groups.AddRange(newFamilyList);
                    rockContext.SaveChanges(true);

                    ImportedPeople.AddRange(newFamilyList);

                    foreach (var familyGroups in newFamilyList.GroupBy <Group, string>(g => g.ForeignId))
                    {
                        bool visitorsExist = visitorList.Any() && familyGroups.Any();
                        foreach (var newFamilyGroup in familyGroups)
                        {
                            foreach (var person in newFamilyGroup.Members.Select(m => m.Person))
                            {
                                // Set notes on this person
                                if (newNoteList.Any(n => n.ForeignId == person.ForeignId))
                                {
                                    newNoteList.Where(n => n.ForeignId == person.ForeignId).ToList()
                                    .ForEach(n => n.EntityId = person.Id);
                                }

                                // Set attributes on this person
                                foreach (var attributeCache in person.Attributes.Select(a => a.Value))
                                {
                                    var newAttributeValue = person.AttributeValues[attributeCache.Key];

                                    if (newAttributeValue != null)
                                    {
                                        newAttributeValue.EntityId = person.Id;
                                        rockContext.AttributeValues.Add(newAttributeValue);
                                    }
                                }

                                // Set aliases on this person
                                if (!person.Aliases.Any(a => a.AliasPersonId == person.Id))
                                {
                                    person.Aliases.Add(new PersonAlias
                                    {
                                        AliasPersonId   = person.Id,
                                        AliasPersonGuid = person.Guid,
                                        ForeignId       = person.ForeignId
                                    });
                                }

                                person.GivingGroupId = newFamilyGroup.Id;

                                if (visitorsExist)
                                {
                                    var groupTypeRoleService = new GroupTypeRoleService(rockContext);
                                    var ownerRole            = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER));
                                    int inviteeRoleId        = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_INVITED)).Id;
                                    int invitedByRoleId      = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_INVITED_BY)).Id;
                                    int canCheckInRoleId     = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_CAN_CHECK_IN)).Id;
                                    int allowCheckInByRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_ALLOW_CHECK_IN_BY)).Id;

                                    // Retrieve or create the group this person is an owner of
                                    var ownerGroup = new GroupMemberService(rockContext).Queryable()
                                                     .Where(m => m.PersonId == person.Id && m.GroupRoleId == ownerRole.Id)
                                                     .Select(m => m.Group).FirstOrDefault();
                                    if (ownerGroup == null)
                                    {
                                        var ownerGroupMember         = new GroupMember();
                                        ownerGroupMember.PersonId    = person.Id;
                                        ownerGroupMember.GroupRoleId = ownerRole.Id;

                                        ownerGroup             = new Group();
                                        ownerGroup.Name        = ownerRole.GroupType.Name;
                                        ownerGroup.GroupTypeId = ownerRole.GroupTypeId.Value;
                                        ownerGroup.Members.Add(ownerGroupMember);
                                        rockContext.Groups.Add(ownerGroup);
                                    }

                                    // Visitor, add relationships to the family members
                                    if (visitorList.Where(v => v.ForeignId == newFamilyGroup.ForeignId)
                                        .Any(v => v.Members.Any(m => m.Person.ForeignId.Equals(person.ForeignId))))
                                    {
                                        var familyMembers = familyGroups.Except(visitorList).SelectMany(g => g.Members);
                                        foreach (var familyMember in familyMembers)
                                        {
                                            // Add visitor invitedBy relationship
                                            var invitedByMember         = new GroupMember();
                                            invitedByMember.PersonId    = familyMember.Person.Id;
                                            invitedByMember.GroupRoleId = invitedByRoleId;
                                            ownerGroup.Members.Add(invitedByMember);

                                            if (person.Age < 18 && familyMember.Person.Age > 15)
                                            {
                                                // Add visitor allowCheckInBy relationship
                                                var allowCheckinMember         = new GroupMember();
                                                allowCheckinMember.PersonId    = familyMember.Person.Id;
                                                allowCheckinMember.GroupRoleId = allowCheckInByRoleId;
                                                ownerGroup.Members.Add(allowCheckinMember);
                                            }
                                        }
                                    }
                                    else
                                    {   // Family member, add relationships to the visitor(s)
                                        var familyVisitors = visitorList.Where(v => v.ForeignId == newFamilyGroup.ForeignId).SelectMany(g => g.Members).ToList();
                                        foreach (var visitor in familyVisitors)
                                        {
                                            // Add invited visitor relationship
                                            var inviteeMember         = new GroupMember();
                                            inviteeMember.PersonId    = visitor.Person.Id;
                                            inviteeMember.GroupRoleId = inviteeRoleId;
                                            ownerGroup.Members.Add(inviteeMember);

                                            if (visitor.Person.Age < 18 && person.Age > 15)
                                            {
                                                // Add canCheckIn visitor relationship
                                                var canCheckInMember         = new GroupMember();
                                                canCheckInMember.PersonId    = visitor.Person.Id;
                                                canCheckInMember.GroupRoleId = canCheckInRoleId;
                                                ownerGroup.Members.Add(canCheckInMember);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // Save notes and all changes
                    rockContext.Notes.AddRange(newNoteList);
                    rockContext.SaveChanges(true);
                });
            }
        }
示例#21
0
        /// <summary>
        /// Maps the company.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="totalRows">The total rows.</param>
        private void MapCompany(IQueryable <Row> tableData, long totalRows = 0)
        {
            var lookupContext = new RockContext();
            var businessList  = new List <Group>();

            var importedCompanyCount = new PersonService(lookupContext).Queryable().Count(p => p.ForeignId != null && p.RecordTypeValueId == BusinessRecordTypeId);

            if (totalRows == 0)
            {
                totalRows = tableData.Count();
            }

            var completedItems = importedCompanyCount;
            var percentage     = (totalRows - 1) / 100 + 1;

            ReportProgress(0, $"Verifying company import ({totalRows:N0} found, {importedCompanyCount:N0} already exist).");

            foreach (var row in tableData.Where(r => r != null))
            {
                var householdId = row["Household_ID"] as int?;
                if (GetPersonKeys(null, householdId) == null)
                {
                    var businessGroup  = new Group();
                    var businessPerson = new Person
                    {
                        CreatedByPersonAliasId = ImportPersonAliasId,
                        CreatedDateTime        = row["Created_Date"] as DateTime?,
                        ModifiedDateTime       = row["Last_Updated_Date"] as DateTime?,
                        RecordTypeValueId      = BusinessRecordTypeId,
                        RecordStatusValueId    = ActivePersonRecordStatusId
                    };

                    var businessName = row["Household_Name"] as string;
                    if (!string.IsNullOrWhiteSpace(businessName))
                    {
                        businessName            = businessName.Replace("&#39;", "'");
                        businessName            = businessName.Replace("&amp;", "&");
                        businessPerson.LastName = businessName.Left(50);
                        businessGroup.Name      = businessName.Left(50);
                    }

                    businessPerson.Attributes      = new Dictionary <string, AttributeCache>();
                    businessPerson.AttributeValues = new Dictionary <string, AttributeValueCache>();
                    AddEntityAttributeValue(lookupContext, HouseholdIdAttribute, businessPerson, householdId.ToString());

                    var groupMember = new GroupMember
                    {
                        Person            = businessPerson,
                        GroupRoleId       = FamilyAdultRoleId,
                        GroupMemberStatus = GroupMemberStatus.Active
                    };
                    businessGroup.Members.Add(groupMember);
                    businessGroup.GroupTypeId = FamilyGroupTypeId;
                    businessGroup.ForeignKey  = householdId.ToString();
                    businessGroup.ForeignId   = householdId;
                    businessList.Add(businessGroup);

                    completedItems++;
                    if (completedItems % percentage < 1)
                    {
                        var percentComplete = completedItems / percentage;
                        ReportProgress(percentComplete, $"{completedItems - importedCompanyCount:N0} companies imported ({percentComplete}% complete).");
                    }

                    if (completedItems % ReportingNumber < 1)
                    {
                        SaveCompanies(businessList);
                        ReportPartialProgress();
                        businessList.Clear();
                    }
                }
            }

            if (businessList.Any())
            {
                SaveCompanies(businessList);
            }

            ReportProgress(100, $"Finished company import: {completedItems - importedCompanyCount:N0} companies imported.");
        }
示例#22
0
        protected void CreateUser()
        {
            var rockContext      = new RockContext();
            var userLoginService = new UserLoginService(rockContext);

            if (!IsUserAuthorized(Authorization.ADMINISTRATE))
            {
                return;
            }
            rockContext.WrapTransaction(() =>
            {
                var personService = new PersonService(rockContext);
                var restUser      = new Person();

                personService.Add(restUser);
                rockContext.SaveChanges();

                // the rest user name gets saved as the last name on a person
                restUser.LastName            = "apollos";
                restUser.RecordTypeValueId   = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_RESTUSER.AsGuid()).Id;
                restUser.RecordStatusValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid()).Id;


                if (restUser.IsValid)
                {
                    rockContext.SaveChanges();
                }

                // the description gets saved as a system note for the person
                var noteType = NoteTypeCache.Get(Rock.SystemGuid.NoteType.PERSON_TIMELINE_NOTE.AsGuid());
                if (noteType != null)
                {
                    var noteService = new NoteService(rockContext);
                    var note        = noteService.Get(noteType.Id, restUser.Id).FirstOrDefault();
                    if (note == null)
                    {
                        note = new Note();
                        noteService.Add(note);
                    }
                    note.NoteTypeId = noteType.Id;
                    note.EntityId   = restUser.Id;
                    note.Text       = "Apollos API User - used for authenticating Apollos Server with Rock";
                }
                rockContext.SaveChanges();

                // the key gets saved in the api key field of a user login (which you have to create if needed)
                var entityType = new EntityTypeService(rockContext)
                                 .Get("Rock.Security.Authentication.Database");

                var userLogin = new UserLogin();
                userLoginService.Add(userLogin);

                userLogin.UserName = Guid.NewGuid().ToString();

                userLogin.IsConfirmed  = true;
                userLogin.ApiKey       = GenerateKey();
                userLogin.PersonId     = restUser.Id;
                userLogin.EntityTypeId = entityType.Id;
                rockContext.SaveChanges();

                var groupMemberService        = new GroupMemberService(rockContext);
                var groupMember               = new GroupMember();
                groupMember.PersonId          = restUser.Id;
                var adminGroup                = new GroupService(rockContext).Get(Rock.SystemGuid.Group.GROUP_ADMINISTRATORS.AsGuid());
                groupMember.GroupId           = adminGroup.Id;
                var securityGroupMember       = adminGroup.GroupType.Roles.Where(r => r.Guid.Equals(Rock.SystemGuid.GroupRole.GROUPROLE_SECURITY_GROUP_MEMBER.AsGuid())).First();
                groupMember.GroupRoleId       = securityGroupMember.Id;
                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                if (groupMember.IsValid)
                {
                    groupMemberService.Add(groupMember);
                    rockContext.SaveChanges();
                }
            });
        }
        /// <summary>
        /// Handles the Click event of the btnRegister 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 btnRegister_Click(object sender, EventArgs e)
        {
            // Check _isValidSettings in case the form was showing and they clicked the visible register button.
            if (Page.IsValid && _isValidSettings)
            {
                var rockContext   = new RockContext();
                var personService = new PersonService(rockContext);

                Person        person       = null;
                Person        spouse       = null;
                Group         family       = null;
                GroupLocation homeLocation = null;
                bool          isMatch      = false;

                // Only use current person if the name entered matches the current person's name and autofill mode is true
                if (_autoFill)
                {
                    if (CurrentPerson != null && CurrentPerson.NickName.IsNotNullOrWhiteSpace() && CurrentPerson.LastName.IsNotNullOrWhiteSpace() &&
                        tbFirstName.Text.Trim().Equals(CurrentPerson.NickName.Trim(), StringComparison.OrdinalIgnoreCase) &&
                        tbLastName.Text.Trim().Equals(CurrentPerson.LastName.Trim(), StringComparison.OrdinalIgnoreCase))
                    {
                        person  = personService.Get(CurrentPerson.Id);
                        isMatch = true;
                    }
                }

                // Try to find person by name/email
                if (person == null)
                {
                    var personQuery = new PersonService.PersonMatchQuery(tbFirstName.Text.Trim(), tbLastName.Text.Trim(), tbEmail.Text.Trim(), pnCell.Text.Trim());
                    person = personService.FindPerson(personQuery, true);
                    if (person != null)
                    {
                        isMatch = true;
                    }
                }

                // Check to see if this is a new person
                if (person == null)
                {
                    var people = personService.GetByMatch(
                        tbFirstName.Text.Trim(),
                        tbLastName.Text.Trim(),
                        dppDOB.SelectedDate,
                        tbEmail.Text.Trim(),
                        pnCell.Text.Trim(),
                        acAddress.Street1,
                        acAddress.PostalCode);
                    if (people.Count() == 1 &&
                        // Make sure their email matches.  If it doesn't, we need to go ahead and create a new person to be matched later.
                        (string.IsNullOrWhiteSpace(tbEmail.Text.Trim()) ||
                         (people.First().Email != null &&
                          tbEmail.Text.ToLower().Trim() == people.First().Email.ToLower().Trim())) &&

                        // Make sure their DOB matches.  If it doesn't, we need to go ahead and create a new person to be matched later.
                        (!dppDOB.SelectedDate.HasValue ||
                         (people.First().BirthDate != null &&
                          dppDOB.SelectedDate.Value == people.First().BirthDate))
                        )
                    {
                        person = people.First();
                    }
                    else
                    {
                        // If so, create the person and family record for the new person
                        person           = new Person();
                        person.FirstName = tbFirstName.Text.Trim();
                        person.LastName  = tbLastName.Text.Trim();
                        person.Email     = tbEmail.Text.Trim();
                        if (dppDOB.SelectedDate.HasValue)
                        {
                            person.BirthDay   = dppDOB.SelectedDate.Value.Day;
                            person.BirthMonth = dppDOB.SelectedDate.Value.Month;
                            person.BirthYear  = dppDOB.SelectedDate.Value.Year;
                        }
                        person.IsEmailActive           = true;
                        person.EmailPreference         = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                        person.ConnectionStatusValueId = _dvcConnectionStatus.Id;
                        person.RecordStatusValueId     = _dvcRecordStatus.Id;
                        person.Gender = Gender.Unknown;

                        family = PersonService.SaveNewPerson(person, rockContext, _publishGroup.Group.CampusId, false);
                    }
                }
                else
                {
                    // updating current existing person
                    person.Email = tbEmail.Text;

                    // Get the current person's families
                    var families = person.GetFamilies(rockContext);

                    // If address can being entered, look for first family with a home location

                    foreach (var aFamily in families)
                    {
                        homeLocation = aFamily.GroupLocations
                                       .Where(l =>
                                              l.GroupLocationTypeValueId == _homeAddressType.Id)
                                       .FirstOrDefault();
                        if (homeLocation != null)
                        {
                            family = aFamily;
                            break;
                        }
                    }


                    // If a family wasn't found with a home location, use the person's first family
                    if (family == null)
                    {
                        family = families.FirstOrDefault();
                    }
                }


                if (!isMatch || !string.IsNullOrWhiteSpace(pnHome.Number))
                {
                    SetPhoneNumber(rockContext, person, pnHome, null, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid());
                }
                if (!isMatch || !string.IsNullOrWhiteSpace(pnCell.Number))
                {
                    SetPhoneNumber(rockContext, person, pnCell, cbSms, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid());
                }

                if (!isMatch || !string.IsNullOrWhiteSpace(acAddress.Street1))
                {
                    string oldLocation = homeLocation != null?homeLocation.Location.ToString() : string.Empty;

                    string newLocation = string.Empty;

                    var location = new LocationService(rockContext).Get(acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country);
                    if (location != null)
                    {
                        if (homeLocation == null)
                        {
                            homeLocation = new GroupLocation();
                            homeLocation.GroupLocationTypeValueId = _homeAddressType.Id;
                            homeLocation.IsMappedLocation         = true;
                            family.GroupLocations.Add(homeLocation);
                        }
                        else
                        {
                            oldLocation = homeLocation.Location.ToString();
                        }

                        homeLocation.Location = location;
                        newLocation           = location.ToString();
                    }
                    else
                    {
                        if (homeLocation != null)
                        {
                            homeLocation.Location = null;
                            family.GroupLocations.Remove(homeLocation);
                            new GroupLocationService(rockContext).Delete(homeLocation);
                        }
                    }
                }

                // Check for the spouse
                if (cbRegisterSpouse.Checked && _showSpouse && tbSpouseFirstName.Text.IsNotNullOrWhiteSpace() && tbSpouseLastName.Text.IsNotNullOrWhiteSpace())
                {
                    spouse = person.GetSpouse(rockContext);
                    bool isSpouseMatch = true;

                    if (spouse == null ||
                        !tbSpouseFirstName.Text.Trim().Equals(spouse.FirstName.Trim(), StringComparison.OrdinalIgnoreCase) ||
                        !tbSpouseLastName.Text.Trim().Equals(spouse.LastName.Trim(), StringComparison.OrdinalIgnoreCase) ||
                        // Make sure their email matches.  If it doesn't, we need to go ahead and create a new person to be matched later.
                        (string.IsNullOrWhiteSpace(tbSpouseEmail.Text.Trim()) ||
                         (spouse.Email != null &&
                          tbSpouseEmail.Text.ToLower().Trim() != spouse.Email.ToLower().Trim())) &&

                        // Make sure their DOB matches.  If it doesn't, we need to go ahead and create a new person to be matched later.
                        (!dppSpouseDOB.SelectedDate.HasValue ||
                         (spouse.BirthDate != null &&
                          dppSpouseDOB.SelectedDate.Value != spouse.BirthDate))
                        )
                    {
                        spouse        = new Person();
                        isSpouseMatch = false;

                        spouse.FirstName = tbSpouseFirstName.Text.FixCase();
                        spouse.LastName  = tbSpouseLastName.Text.FixCase();

                        if (dppSpouseDOB.SelectedDate.HasValue)
                        {
                            spouse.BirthDay   = dppSpouseDOB.SelectedDate.Value.Day;
                            spouse.BirthMonth = dppSpouseDOB.SelectedDate.Value.Month;
                            spouse.BirthYear  = dppSpouseDOB.SelectedDate.Value.Year;
                        }

                        spouse.ConnectionStatusValueId = _dvcConnectionStatus.Id;
                        spouse.RecordStatusValueId     = _dvcRecordStatus.Id;
                        spouse.Gender = Gender.Unknown;

                        spouse.IsEmailActive   = true;
                        spouse.EmailPreference = EmailPreference.EmailAllowed;

                        var groupMember = new GroupMember();
                        groupMember.GroupRoleId = _adultRole.Id;
                        groupMember.Person      = spouse;

                        family.Members.Add(groupMember);

                        spouse.MaritalStatusValueId = _married.Id;
                        person.MaritalStatusValueId = _married.Id;
                    }

                    spouse.Email = tbSpouseEmail.Text;

                    if (!isSpouseMatch || !string.IsNullOrWhiteSpace(pnHome.Number))
                    {
                        SetPhoneNumber(rockContext, spouse, pnHome, null, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid());
                    }

                    if (!isSpouseMatch || !string.IsNullOrWhiteSpace(pnSpouseCell.Number))
                    {
                        SetPhoneNumber(rockContext, spouse, pnSpouseCell, cbSpouseSms, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid());
                    }
                }


                // Save the person/spouse and change history
                rockContext.SaveChanges();

                // Check to see if a workflow should be launched for each person
                WorkflowTypeCache workflowType = null;
                Guid?workflowTypeGuid          = GetAttributeValue("Workflow").AsGuidOrNull();
                if (workflowTypeGuid.HasValue)
                {
                    workflowType = WorkflowTypeCache.Get(workflowTypeGuid.Value);
                }

                // Save the registrations ( and launch workflows )
                var newGroupMembers = new List <GroupMember>();
                AddPersonToGroup(rockContext, person, workflowType, newGroupMembers);
                AddPersonToGroup(rockContext, spouse, workflowType, newGroupMembers);

                // Show the results
                pnlView.Visible   = false;
                pnlResult.Visible = true;

                // Show lava content
                var mergeFields = new Dictionary <string, object>();
                mergeFields.Add("PublishGroup", _publishGroup);
                mergeFields.Add("Group", _publishGroup.Group);
                mergeFields.Add("GroupMembers", newGroupMembers);

                string template = GetAttributeValue("ResultLavaTemplate");
                lResult.Text = template.ResolveMergeFields(mergeFields);

                SendConfirmation(person);
                SendConfirmation(spouse);

                // Will only redirect if a value is specifed
                NavigateToLinkedPage("ResultPage");
            }
        }
示例#24
0
        /// <summary>
        /// Saves the family and persons to the database
        /// </summary>
        /// <param name="kioskCampusId">The kiosk campus identifier.</param>
        /// <param name="rockContext">The rock context.</param>
        /// <returns></returns>
        public SaveResult SaveFamilyAndPersonsToDatabase(int?kioskCampusId, RockContext rockContext)
        {
            SaveResult saveResult = new SaveResult();

            FamilyRegistrationState editFamilyState = this;
            var personService             = new PersonService(rockContext);
            var groupService              = new GroupService(rockContext);
            var recordTypePersonId        = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
            var maritalStatusMarried      = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_MARRIED.AsGuid());
            var maritalStatusSingle       = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_MARITAL_STATUS_SINGLE.AsGuid());
            var numberTypeValueMobile     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid());
            int groupTypeRoleAdultId      = GroupTypeCache.GetFamilyGroupType().Roles.FirstOrDefault(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id;
            int groupTypeRoleChildId      = GroupTypeCache.GetFamilyGroupType().Roles.FirstOrDefault(a => a.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()).Id;
            int?groupTypeRoleCanCheckInId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid())
                                            ?.Roles.FirstOrDefault(r => r.Guid == Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_CAN_CHECK_IN.AsGuid())?.Id;

            bool?groupTypeDefaultSmsEnabled = GroupTypeCache.GetFamilyGroupType().GetAttributeValue(Rock.SystemKey.GroupTypeAttributeKey.CHECKIN_REGISTRATION_DEFAULTSMSENABLED).AsBooleanOrNull();

            Group primaryFamily = null;

            if (editFamilyState.GroupId.HasValue)
            {
                primaryFamily = groupService.Get(editFamilyState.GroupId.Value);
            }

            // see if we can find matches for new people that were added, and also set the primary family if this is a new family, but a matching family was found
            foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.PersonId.HasValue && !a.IsDeleted))
            {
                var personQuery    = new PersonService.PersonMatchQuery(familyPersonState.FirstName, familyPersonState.LastName, familyPersonState.Email, familyPersonState.MobilePhoneNumber, familyPersonState.Gender, familyPersonState.BirthDate, familyPersonState.SuffixValueId);
                var matchingPerson = personService.FindPerson(personQuery, true);
                if (matchingPerson != null)
                {
                    // newly added person, but a match was found, so set the PersonId, GroupId, and ConnectionStatusValueID to the matching person instead of creating a new person
                    familyPersonState.PersonId                 = matchingPerson.Id;
                    familyPersonState.GroupId                  = matchingPerson.GetFamily(rockContext)?.Id;
                    familyPersonState.RecordStatusValueId      = matchingPerson.RecordStatusValueId;
                    familyPersonState.ConnectionStatusValueId  = matchingPerson.ConnectionStatusValueId;
                    familyPersonState.ConvertedToMatchedPerson = true;
                    if (primaryFamily == null && familyPersonState.IsAdult)
                    {
                        // if this is a new family, but we found a matching adult person, use that person's family as the family
                        primaryFamily = matchingPerson.GetFamily(rockContext);
                    }
                }
            }

            // loop thru all people and add/update as needed
            foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.IsDeleted))
            {
                Person person;
                if (!familyPersonState.PersonId.HasValue)
                {
                    person = new Person();
                    personService.Add(person);
                    saveResult.NewPersonList.Add(person);
                    person.RecordTypeValueId = recordTypePersonId;
                    person.FirstName         = familyPersonState.FirstName;
                }
                else
                {
                    person = personService.Get(familyPersonState.PersonId.Value);
                }

                // NOTE, Gender, MaritalStatusValueId, NickName, LastName are required fields so, always updated them to match the UI (even if a matched person was found)
                person.Gender = familyPersonState.Gender;
                person.MaritalStatusValueId = familyPersonState.IsMarried ? maritalStatusMarried.Id : maritalStatusSingle.Id;
                person.NickName             = familyPersonState.FirstName;
                person.LastName             = familyPersonState.LastName;

                // if the familyPersonState was converted to a Matched Person, don't overwrite existing values with blank values
                var saveEmptyValues = !familyPersonState.ConvertedToMatchedPerson;

                if (familyPersonState.SuffixValueId.HasValue || saveEmptyValues)
                {
                    person.SuffixValueId = familyPersonState.SuffixValueId;
                }

                if (familyPersonState.BirthDate.HasValue || saveEmptyValues)
                {
                    person.SetBirthDate(familyPersonState.BirthDate);
                }

                if (familyPersonState.Email.IsNotNullOrWhiteSpace() || saveEmptyValues)
                {
                    person.Email = familyPersonState.Email;
                }

                if (familyPersonState.GradeOffset.HasValue || saveEmptyValues)
                {
                    person.GradeOffset = familyPersonState.GradeOffset;
                }

                // if a matching person was found, the familyPersonState's RecordStatusValueId and ConnectinoStatusValueId was already updated to match the matched person
                person.RecordStatusValueId     = familyPersonState.RecordStatusValueId;
                person.ConnectionStatusValueId = familyPersonState.ConnectionStatusValueId;

                rockContext.SaveChanges();

                bool isNewPerson = !familyPersonState.PersonId.HasValue;
                if (!familyPersonState.PersonId.HasValue)
                {
                    // if we added a new person, we know now the personId after SaveChanges, so set it
                    familyPersonState.PersonId = person.Id;
                }

                if (familyPersonState.AlternateID.IsNotNullOrWhiteSpace())
                {
                    PersonSearchKey        personAlternateValueIdSearchKey;
                    PersonSearchKeyService personSearchKeyService = new PersonSearchKeyService(rockContext);
                    if (isNewPerson)
                    {
                        // if we added a new person, a default AlternateId was probably added in the service layer. If a specific Alternate ID was specified, make sure that their SearchKey is updated
                        personAlternateValueIdSearchKey = person.GetPersonSearchKeys(rockContext).Where(a => a.SearchTypeValueId == _personSearchAlternateValueId).FirstOrDefault();
                    }
                    else
                    {
                        // see if the key already exists. If if it doesn't already exist, let a new one get created
                        personAlternateValueIdSearchKey = person.GetPersonSearchKeys(rockContext).Where(a => a.SearchTypeValueId == _personSearchAlternateValueId && a.SearchValue == familyPersonState.AlternateID).FirstOrDefault();
                    }

                    if (personAlternateValueIdSearchKey == null)
                    {
                        personAlternateValueIdSearchKey = new PersonSearchKey();
                        personAlternateValueIdSearchKey.PersonAliasId     = person.PrimaryAliasId;
                        personAlternateValueIdSearchKey.SearchTypeValueId = _personSearchAlternateValueId;
                        personSearchKeyService.Add(personAlternateValueIdSearchKey);
                    }

                    if (personAlternateValueIdSearchKey.SearchValue != familyPersonState.AlternateID)
                    {
                        personAlternateValueIdSearchKey.SearchValue = familyPersonState.AlternateID;
                        rockContext.SaveChanges();
                    }
                }

                person.LoadAttributes();
                foreach (var attributeValue in familyPersonState.PersonAttributeValuesState)
                {
                    // only set attribute values that are editable so we don't accidently delete any attribute values
                    if (familyPersonState.EditableAttributes.Contains(attributeValue.Value.AttributeId))
                    {
                        if (attributeValue.Value.Value.IsNotNullOrWhiteSpace() || saveEmptyValues)
                        {
                            person.SetAttributeValue(attributeValue.Key, attributeValue.Value.Value);
                        }
                    }
                }

                person.SaveAttributeValues(rockContext);

                if (familyPersonState.MobilePhoneNumber.IsNotNullOrWhiteSpace() || saveEmptyValues)
                {
                    person.UpdatePhoneNumber(numberTypeValueMobile.Id, familyPersonState.MobilePhoneCountryCode, familyPersonState.MobilePhoneNumber, familyPersonState.MobilePhoneSmsEnabled ?? groupTypeDefaultSmsEnabled, false, rockContext);
                }

                rockContext.SaveChanges();
            }

            if (primaryFamily == null)
            {
                // new family and no family found by looking up matching adults, so create a new family
                primaryFamily = new Group();
                var familyLastName = editFamilyState.FamilyPersonListState.OrderBy(a => a.IsAdult).Where(a => !a.IsDeleted).Select(a => a.LastName).FirstOrDefault();
                primaryFamily.Name        = familyLastName + " Family";
                primaryFamily.GroupTypeId = GroupTypeCache.GetFamilyGroupType().Id;

                // Set the Campus to the Campus of this Kiosk
                primaryFamily.CampusId = kioskCampusId;

                groupService.Add(primaryFamily);
                saveResult.NewFamilyList.Add(primaryFamily);
                rockContext.SaveChanges();
            }

            if (!editFamilyState.GroupId.HasValue)
            {
                editFamilyState.GroupId = primaryFamily.Id;
            }

            primaryFamily.LoadAttributes();
            foreach (var familyAttribute in editFamilyState.FamilyAttributeValuesState)
            {
                // only set attribute values that are editable so we don't accidently delete any attribute values
                if (editFamilyState.EditableFamilyAttributes.Contains(familyAttribute.Value.AttributeId))
                {
                    primaryFamily.SetAttributeValue(familyAttribute.Key, familyAttribute.Value.Value);
                }
            }

            primaryFamily.SaveAttributeValues(rockContext);

            var groupMemberService = new GroupMemberService(rockContext);

            // loop thru all people that are part of the same family (in the UI) and ensure they are all in the same primary family (in the database)
            foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.IsDeleted && a.InPrimaryFamily))
            {
                var currentFamilyMember = primaryFamily.Members.FirstOrDefault(m => m.PersonId == familyPersonState.PersonId.Value);

                if (currentFamilyMember == null)
                {
                    currentFamilyMember = new GroupMember
                    {
                        GroupId           = primaryFamily.Id,
                        PersonId          = familyPersonState.PersonId.Value,
                        GroupMemberStatus = GroupMemberStatus.Active
                    };

                    if (familyPersonState.IsAdult)
                    {
                        currentFamilyMember.GroupRoleId = groupTypeRoleAdultId;
                    }
                    else
                    {
                        currentFamilyMember.GroupRoleId = groupTypeRoleChildId;
                    }

                    groupMemberService.Add(currentFamilyMember);

                    rockContext.SaveChanges();
                }
            }

            // make a dictionary of new related families (by lastname) so we can combine any new related children into a family with the same last name
            Dictionary <string, Group> newRelatedFamilies = new Dictionary <string, Group>(StringComparer.OrdinalIgnoreCase);

            // loop thru all people that are NOT part of the same family
            foreach (var familyPersonState in editFamilyState.FamilyPersonListState.Where(a => !a.IsDeleted && a.InPrimaryFamily == false))
            {
                if (!familyPersonState.GroupId.HasValue)
                {
                    // related person not in a family yet
                    Group relatedFamily = newRelatedFamilies.GetValueOrNull(familyPersonState.LastName);
                    if (relatedFamily == null)
                    {
                        relatedFamily             = new Group();
                        relatedFamily.Name        = familyPersonState.LastName + " Family";
                        relatedFamily.GroupTypeId = GroupTypeCache.GetFamilyGroupType().Id;

                        // Set the Campus to the Campus of this Kiosk
                        relatedFamily.CampusId = kioskCampusId;

                        newRelatedFamilies.Add(familyPersonState.LastName, relatedFamily);
                        groupService.Add(relatedFamily);
                        saveResult.NewFamilyList.Add(relatedFamily);
                    }

                    rockContext.SaveChanges();

                    familyPersonState.GroupId = relatedFamily.Id;

                    var familyMember = new GroupMember
                    {
                        GroupId           = relatedFamily.Id,
                        PersonId          = familyPersonState.PersonId.Value,
                        GroupMemberStatus = GroupMemberStatus.Active
                    };

                    if (familyPersonState.IsAdult)
                    {
                        familyMember.GroupRoleId = groupTypeRoleAdultId;
                    }
                    else
                    {
                        familyMember.GroupRoleId = groupTypeRoleChildId;
                    }

                    groupMemberService.Add(familyMember);
                }

                // ensure there are known relationships between each adult in the primary family to this person that isn't in the primary family
                foreach (var primaryFamilyAdult in editFamilyState.FamilyPersonListState.Where(a => a.IsAdult && a.InPrimaryFamily))
                {
                    groupMemberService.CreateKnownRelationship(primaryFamilyAdult.PersonId.Value, familyPersonState.PersonId.Value, familyPersonState.ChildRelationshipToAdult);

                    // if this is something other than the CanCheckIn relationship, but is a relationship that should ensure a CanCheckIn relationship, create a CanCheckinRelationship
                    if (groupTypeRoleCanCheckInId.HasValue && familyPersonState.CanCheckIn && groupTypeRoleCanCheckInId != familyPersonState.ChildRelationshipToAdult)
                    {
                        groupMemberService.CreateKnownRelationship(primaryFamilyAdult.PersonId.Value, familyPersonState.PersonId.Value, groupTypeRoleCanCheckInId.Value);
                    }
                }
            }

            return(saveResult);
        }
        /// <summary>
        /// Handles the Click event of the lbConnect 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 lbConnect_Click( object sender, EventArgs e )
        {
            using ( var rockContext = new RockContext() )
            {
                var connectionRequestService = new ConnectionRequestService( rockContext );
                var groupMemberService = new GroupMemberService( rockContext );
                var connectionActivityTypeService = new ConnectionActivityTypeService( rockContext );
                var connectionRequestActivityService = new ConnectionRequestActivityService( rockContext );
                var connectionRequest = connectionRequestService.Get( hfConnectionRequestId.ValueAsInt() );

                if ( connectionRequest != null &&
                    connectionRequest.PersonAlias != null &&
                    connectionRequest.ConnectionOpportunity != null )
                {
                    bool okToConnect = true;

                    GroupMember groupMember = null;

                    // Only do group member placement if the request has an assigned placement group, role, and status
                    if ( connectionRequest.AssignedGroupId.HasValue &&
                        connectionRequest.AssignedGroupMemberRoleId.HasValue &&
                        connectionRequest.AssignedGroupMemberStatus.HasValue )
                    {
                        var group = new GroupService( rockContext ).Get( connectionRequest.AssignedGroupId.Value );
                        if ( group != null )
                        {
                            // Only attempt the add if person does not already exist in group with same role
                            groupMember = groupMemberService.GetByGroupIdAndPersonIdAndGroupRoleId( connectionRequest.AssignedGroupId.Value,
                                connectionRequest.PersonAlias.PersonId, connectionRequest.AssignedGroupMemberRoleId.Value );
                            if ( groupMember == null )
                            {
                                groupMember = new GroupMember();
                                groupMember.PersonId = connectionRequest.PersonAlias.PersonId;
                                groupMember.GroupId = connectionRequest.AssignedGroupId.Value;
                                groupMember.GroupRoleId = connectionRequest.AssignedGroupMemberRoleId.Value;
                                groupMember.GroupMemberStatus = connectionRequest.AssignedGroupMemberStatus.Value;

                                foreach ( ListItem item in cblManualRequirements.Items )
                                {
                                    if ( !item.Selected && group.MustMeetRequirementsToAddMember.HasValue && group.MustMeetRequirementsToAddMember.Value )
                                    {
                                        okToConnect = false;
                                        nbRequirementsErrors.Text = "Group Requirements have not been met. Please verify all of the requirements.";
                                        nbRequirementsErrors.Visible = true;
                                        break;
                                    }
                                    else
                                    {
                                        groupMember.GroupMemberRequirements.Add( new GroupMemberRequirement
                                        {
                                            GroupRequirementId = item.Value.AsInteger(),
                                            RequirementMetDateTime = RockDateTime.Now,
                                            LastRequirementCheckDateTime = RockDateTime.Now
                                        } );
                                    }
                                }

                                if ( okToConnect )
                                {
                                    groupMemberService.Add( groupMember );
                                    if ( !string.IsNullOrWhiteSpace( connectionRequest.AssignedGroupMemberAttributeValues ) )
                                    {
                                        var savedValues = JsonConvert.DeserializeObject<Dictionary<string, string>>( connectionRequest.AssignedGroupMemberAttributeValues );
                                        if ( savedValues != null )
                                        {
                                            groupMember.LoadAttributes();
                                            foreach ( var item in savedValues )
                                            {
                                                groupMember.SetAttributeValue( item.Key, item.Value );
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if ( okToConnect )
                    {
                        // ... but always record the connection activity and change the state to connected.
                        var guid = Rock.SystemGuid.ConnectionActivityType.CONNECTED.AsGuid();
                        var connectedActivityId = connectionActivityTypeService.Queryable()
                            .Where( t => t.Guid == guid )
                            .Select( t => t.Id )
                            .FirstOrDefault();
                        if ( connectedActivityId > 0 )
                        {
                            var connectionRequestActivity = new ConnectionRequestActivity();
                            connectionRequestActivity.ConnectionRequestId = connectionRequest.Id;
                            connectionRequestActivity.ConnectionOpportunityId = connectionRequest.ConnectionOpportunityId;
                            connectionRequestActivity.ConnectionActivityTypeId = connectedActivityId;
                            connectionRequestActivity.ConnectorPersonAliasId = CurrentPersonAliasId;
                            connectionRequestActivityService.Add( connectionRequestActivity );
                        }

                        connectionRequest.ConnectionState = ConnectionState.Connected;

                        rockContext.SaveChanges();
                        if ( groupMember != null && !string.IsNullOrWhiteSpace( connectionRequest.AssignedGroupMemberAttributeValues ) )
                        {
                            groupMember.SaveAttributeValues( rockContext );
                        }

                        ShowDetail( connectionRequest.Id, connectionRequest.ConnectionOpportunityId );
                    }
                }
            }
        }
示例#26
0
 public Group InviteMember(GroupId groupId, GroupMember groupMember)
 {
     Silanis.ESL.API.GroupMember apiGroupMember = new GroupMemberConverter(groupMember).ToAPIGroupMember();
     Silanis.ESL.API.Group       apiResponse    = apiClient.InviteMember(groupId.Id, apiGroupMember);
     return(new GroupConverter(apiResponse).ToSDKGroup());
 }
示例#27
0
        public async Task <(int Count, string Message, GroupMember?Entity)> SaveMemberAsync(ClaimsPrincipal?principal, GroupMember entity)
        {
            using var dbContext = Factory.CreateDbContext();
            var countryId = (await dbContext.Groups.AsNoTracking().SingleOrDefaultAsync(g => g.Id == entity.GroupId))?.CountryId;

            if (await IsGroupDataAdministratorAsync(principal, entity.GroupId, countryId))
            {
                dbContext.GroupMembers.Attach(entity);
                dbContext.Entry(entity).State = entity.Id.GetState();
                var count = await dbContext.SaveChangesAsync();

                return(count.SaveResult(entity));
            }
            return(principal.SaveNotAuthorised <GroupMember>());
        }
示例#28
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 (string.IsNullOrWhiteSpace(txtFirstName.Text) ||
                string.IsNullOrWhiteSpace(txtLastName.Text) ||
                string.IsNullOrWhiteSpace(txtEmail.Text))
            {
                ShowError("Missing Information", "Please enter a value for First Name, Last Name, and Email");
            }
            else
            {
                var rockContext = new RockContext();
                var person      = GetPerson(rockContext);
                if (person != null)
                {
                    Guid?groupGuid = GetAttributeValue("Group").AsGuidOrNull();

                    if (groupGuid.HasValue)
                    {
                        var groupService       = new GroupService(rockContext);
                        var groupMemberService = new GroupMemberService(rockContext);

                        var group = groupService.Get(groupGuid.Value);
                        if (group != null && group.GroupType.DefaultGroupRoleId.HasValue)
                        {
                            string linkedPage = GetAttributeValue("ConfirmationPage");
                            if (!string.IsNullOrWhiteSpace(linkedPage))
                            {
                                var member = group.Members.Where(m => m.PersonId == person.Id).FirstOrDefault();

                                // If person has not registered or confirmed their registration
                                if (member == null || member.GroupMemberStatus != GroupMemberStatus.Active)
                                {
                                    Guid confirmationEmailTemplateGuid = Guid.Empty;
                                    if (!Guid.TryParse(GetAttributeValue("ConfirmationEmail"), out confirmationEmailTemplateGuid))
                                    {
                                        confirmationEmailTemplateGuid = Guid.Empty;
                                    }

                                    if (member == null)
                                    {
                                        member             = new GroupMember();
                                        member.GroupId     = group.Id;
                                        member.PersonId    = person.Id;
                                        member.GroupRoleId = group.GroupType.DefaultGroupRoleId.Value;

                                        // If a confirmation email is configured, set status to Pending otherwise set it to active
                                        member.GroupMemberStatus = confirmationEmailTemplateGuid != Guid.Empty ? GroupMemberStatus.Pending : GroupMemberStatus.Active;

                                        groupMemberService.Add(member);
                                        rockContext.SaveChanges();

                                        member = groupMemberService.Get(member.Id);
                                    }

                                    // Send the confirmation
                                    if (confirmationEmailTemplateGuid != Guid.Empty)
                                    {
                                        var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, this.CurrentPerson);
                                        mergeFields.Add("Member", member);

                                        var pageParams = new Dictionary <string, string>();
                                        pageParams.Add("gm", member.UrlEncodedKey);
                                        var pageReference = new Rock.Web.PageReference(linkedPage, pageParams);
                                        mergeFields.Add("ConfirmationPage", pageReference.BuildUrl());

                                        var recipients = new List <RecipientData>();
                                        recipients.Add(new RecipientData(person.Email, mergeFields));
                                        Email.Send(confirmationEmailTemplateGuid, recipients, ResolveRockUrl("~/"), ResolveRockUrl("~~/"));
                                    }

                                    ShowSuccess(GetAttributeValue("SuccessMessage"));
                                }
                                else
                                {
                                    var pageParams = new Dictionary <string, string>();
                                    pageParams.Add("gm", member.UrlEncodedKey);
                                    var pageReference = new Rock.Web.PageReference(linkedPage, pageParams);
                                    Response.Redirect(pageReference.BuildUrl(), false);
                                }
                            }
                            else
                            {
                                ShowError("Configuration Error", "Invalid Confirmation Page setting");
                            }
                        }
                        else
                        {
                            ShowError("Configuration Error", "The configured group does not exist, or it's group type does not have a default role configured.");
                        }
                    }
                    else
                    {
                        ShowError("Configuration Error", "Invalid Group setting");
                    }
                }
            }
        }
示例#29
0
        public override async System.Threading.Tasks.Task ExecuteAsync(List <string> command, List <BaseMessage> originMessage, MessageSourceType sourceType, UserInfo qq, Group group, GroupMember member)
        {
            var fromQQ  = 0L;
            var toGroup = 0L;

            //var message = "";
            if (sourceType != MessageSourceType.Group)
            {
                return;
            }

            var sourceMessageId = (originMessage?.FirstOrDefault() as SourceMessage)?.Id ?? default;
            var messages        = new List <BaseMessage>();

            messages.Add(new QuoteMessage(toGroup, fromQQ, sourceMessageId));

            fromQQ  = member.QQ;
            toGroup = member.GroupNumber;
            var permit = member.PermitType;

            if (originMessage.Count <= 2)
            {
                if (command[0].Equals("on", StringComparison.CurrentCultureIgnoreCase))
                {
                    if (permit == PermitType.None)
                    {
                        MessageManager.SendTextMessage(MessageSourceType.Group, "只有群主或管理员才有权限开启色图鉴定功能", fromQQ, toGroup);
                        return;
                    }

                    UpdateGroupHentaiCheckConfig(toGroup, true);
                    MessageManager.SendTextMessage(MessageSourceType.Group, "色图鉴定已开启", fromQQ, toGroup);
                    return;
                }
                else if (command[0].Equals("off", StringComparison.CurrentCultureIgnoreCase))
                {
                    if (permit == PermitType.None)
                    {
                        MessageManager.SendTextMessage(MessageSourceType.Group, "只有群主或管理员才有权限关闭色图鉴定功能", fromQQ, toGroup);
                        return;
                    }

                    UpdateGroupHentaiCheckConfig(toGroup, false);
                    MessageManager.SendTextMessage(MessageSourceType.Group, "色图鉴定已关闭", fromQQ, toGroup);
                    return;
                }
                else if (!GroupHentaiCheckConfig.TryGetValue(toGroup, out var config))
                {
                    MessageManager.SendTextMessage(MessageSourceType.Group, "当前群尚未色图鉴定功能", fromQQ, toGroup);
                    return;
                }
                else
                {
                    messages.Add(new TextMessage("图呢?"));
                    MessageManager.SendMessage(sourceType, messages, fromQQ, toGroup);
                    return;
                }
            }
            else
            {
                if (!(originMessage?.ElementAt(2) is ImageMessage im))
                {
                    messages.Add(new TextMessage("图呢?"));
                    MessageManager.SendMessage(sourceType, messages, fromQQ, toGroup);
                    return;
                }

                var imageUrl = im.Url;
                if (string.IsNullOrWhiteSpace(imageUrl))
                {
                    MessageManager.SendTextMessage(MessageSourceType.Group, "图片上传失败惹", fromQQ, toGroup);
                    return;
                }

                var client = new RestClient();
                client.Timeout = -1;
                var imageDownloadRequest = new RestRequest(imageUrl, Method.GET);
                var imgRes = await client.ExecuteAsync(imageDownloadRequest);

                if (!imgRes.IsSuccessful)
                {
                    MessageManager.SendTextMessage(sourceType, "请求失败了QAQ", fromQQ, toGroup);
                    return;
                }

                var savedPath = Path.Combine(Config.TempPath, Guid.NewGuid() + ".png");

                var uploadRequest = new RestRequest("https://checkimage.querydata.org/api", Method.POST)
                {
                    AlwaysMultipartFormData = true
                };
                uploadRequest.AddFileBytes("image", imgRes.RawBytes, savedPath, contentType: imgRes.ContentType);
                var res = await client.ExecuteAsync(uploadRequest);

                if (!res.IsSuccessful)
                {
                    MessageManager.SendTextMessage(sourceType, "请求失败了QAQ", fromQQ, toGroup);
                    return;
                }

                var strContent = res.Content;
                var jsonRes    =
                    Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(strContent, new List <HentaiCheckModel>());

                if (jsonRes == null || !jsonRes.Any())
                {
                    MessageManager.SendTextMessage(sourceType, "请求失败了QAQ", fromQQ, toGroup);
                    return;
                }

                var messageText = "没鉴定出来><";
                var result      = jsonRes.OrderByDescending(p => p.Probability).FirstOrDefault();
                switch (result?.ClassName)
                {
                case "Drawing":
                case "Neutral":
                    messageText = "这不是挺健全的嘛";
                    break;

                case "Hentai":
                    messageText = "色疯辣!";
                    break;

                case "Sexy":
                    messageText = "我超,太烧啦!";
                    break;

                case "P**n":
                    messageText = "你完了,我这就叫狗管理来抓你";
                    break;
                }

                messages.Add(new TextMessage(messageText));
                MessageManager.SendMessage(sourceType, messages, fromQQ, toGroup);
            }
        }
示例#30
0
        public override async Task ExecuteAsync(List <string> command, List <BaseMessage> originMessage, MessageSourceType sourceType, UserInfo qq, Group group, GroupMember member)
        {
            await Task.Yield();

            var name = "";

            if (sourceType == MessageSourceType.Group)
            {
                if (member == null)
                {
                    return;
                }

                name = string.IsNullOrWhiteSpace(member.GroupName) ? qq.Name : member.GroupName;
            }
            else if (sourceType == MessageSourceType.Private)
            {
                if (qq == null)
                {
                    return;
                }
                name = qq.Name;
            }

            var str         = $"{name}的疯狂发作 - 总结症状:\n";
            var insaneIndex = DiceManager.RollDice(_longInsaneList.Count - 1);

            str += $"1d{_longInsaneList.Count - 1}={insaneIndex}\n";
            var duration = DiceManager.RollDice(10);

            if (insaneIndex == 9)
            {
                var fearIndex = DiceManager.RollDice(_fearList.Count - 1);
                str += string.Format($"症状=>{_longInsaneList[insaneIndex]}", "1d10=" + duration, $"1d{_fearList.Count - 1}={fearIndex}",
                                     _fearList[fearIndex]);
            }
            else if (insaneIndex == 10)
            {
                var panicIndex = DiceManager.RollDice(_panicList.Count - 1);
                str += string.Format($"症状=>{_longInsaneList[insaneIndex]}", "1d10=" + duration, $"1d{_panicList.Count - 1}={panicIndex}",
                                     _panicList[panicIndex]);
            }
            else
            {
                str += string.Format($"症状=>{_longInsaneList[insaneIndex]}", "1d10=" + duration);
            }

            MessageManager.SendTextMessage(sourceType, str, qq?.QQ, member?.GroupNumber);
        }
示例#31
0
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            // Determine which group to add the person to
            Group group       = null;
            int?  groupRoleId = null;

            var groupAndRoleValues = (GetAttributeValue(action, "GroupAndRole") ?? string.Empty).Split('|');

            if (groupAndRoleValues.Count() > 1)
            {
                var groupGuid = groupAndRoleValues[1].AsGuidOrNull();
                if (groupGuid.HasValue)
                {
                    group = new GroupService(rockContext).Get(groupGuid.Value);

                    if (groupAndRoleValues.Count() > 2)
                    {
                        var groupTypeRoleGuid = groupAndRoleValues[2].AsGuidOrNull();
                        if (groupTypeRoleGuid.HasValue)
                        {
                            var groupRole = new GroupTypeRoleService(rockContext).Get(groupTypeRoleGuid.Value);
                            if (groupRole != null)
                            {
                                groupRoleId = groupRole.Id;
                            }
                        }
                    }

                    if (!groupRoleId.HasValue && group != null)
                    {
                        // use the group's grouptype's default group role if a group role wasn't specified
                        groupRoleId = group.GroupType.DefaultGroupRoleId;
                    }
                }
            }

            if (group == null)
            {
                errorMessages.Add("No group was provided");
            }

            if (!groupRoleId.HasValue)
            {
                errorMessages.Add("No group role was provided and group doesn't have a default group role");
            }

            // determine the person that will be added to the group
            Person person = null;

            // get the Attribute.Guid for this workflow's Person Attribute so that we can lookup the value
            var guidPersonAttribute = GetAttributeValue(action, "Person").AsGuidOrNull();

            if (guidPersonAttribute.HasValue)
            {
                var attributePerson = AttributeCache.Read(guidPersonAttribute.Value, rockContext);
                if (attributePerson != null)
                {
                    string attributePersonValue = action.GetWorklowAttributeValue(guidPersonAttribute.Value);
                    if (!string.IsNullOrWhiteSpace(attributePersonValue))
                    {
                        if (attributePerson.FieldType.Class == typeof(Rock.Field.Types.PersonFieldType).FullName)
                        {
                            Guid personAliasGuid = attributePersonValue.AsGuid();
                            if (!personAliasGuid.IsEmpty())
                            {
                                person = new PersonAliasService(rockContext).Queryable()
                                         .Where(a => a.Guid.Equals(personAliasGuid))
                                         .Select(a => a.Person)
                                         .FirstOrDefault();
                            }
                        }
                        else
                        {
                            errorMessages.Add("The attribute used to provide the person was not of type 'Person'.");
                        }
                    }
                }
            }

            if (person == null)
            {
                errorMessages.Add(string.Format("Person could not be found for selected value ('{0}')!", guidPersonAttribute.ToString()));
            }

            // Add Person to Group
            if (!errorMessages.Any())
            {
                var groupMemberService = new GroupMemberService(rockContext);
                var groupMember        = new GroupMember();
                groupMember.PersonId          = person.Id;
                groupMember.GroupId           = group.Id;
                groupMember.GroupRoleId       = groupRoleId.Value;
                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                if (groupMember.IsValid)
                {
                    groupMemberService.Add(groupMember);
                    rockContext.SaveChanges();
                }
                else
                {
                    // if the group member couldn't be added (for example, one of the group membership rules didn't pass), add the validation messages to the errormessages
                    errorMessages.AddRange(groupMember.ValidationResults.Select(a => a.ErrorMessage));
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

            return(true);
        }
示例#32
0
        private List<GroupMember> GetControlData()
        {
            var familyMembers = new List<GroupMember>();

            int? childMaritalStatusId = null;
            var childMaritalStatus = DefinedValueCache.Read( GetAttributeValue("ChildMaritalStatus").AsGuid() );
            if ( childMaritalStatus != null )
            {
                childMaritalStatusId = childMaritalStatus.Id;
            }
            int? adultMaritalStatusId = ddlMaritalStatus.SelectedValueAsInt();

            int recordTypePersonId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id;
            int recordStatusActiveId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE.AsGuid() ).Id;

            foreach ( NewFamilyMembersRow row in nfmMembers.FamilyMemberRows )
            {
                var groupMember = new GroupMember();
                groupMember.Person = new Person();
                groupMember.Person.Guid = row.PersonGuid.Value;
                groupMember.Person.RecordTypeValueId = recordTypePersonId;
                groupMember.Person.RecordStatusValueId = recordStatusActiveId;

                if ( row.RoleId.HasValue )
                {
                    groupMember.GroupRoleId = row.RoleId.Value;

                    if (groupMember.GroupRoleId == _childRoleId)
                    {
                        groupMember.Person.MaritalStatusValueId = childMaritalStatusId;
                    }
                    else
                    {
                        groupMember.Person.MaritalStatusValueId = adultMaritalStatusId;
                    }
                }

                groupMember.Person.TitleValueId = row.TitleValueId;
                groupMember.Person.FirstName = row.FirstName;
                groupMember.Person.NickName = groupMember.Person.FirstName;
                groupMember.Person.LastName = row.LastName;
                groupMember.Person.SuffixValueId = row.SuffixValueId;
                groupMember.Person.Gender = row.Gender;
                groupMember.Person.BirthDate = row.BirthDate;
                groupMember.Person.ConnectionStatusValueId = row.ConnectionStatusValueId;
                groupMember.Person.Grade = row.Grade;

                groupMember.Person.EmailPreference = EmailPreference.EmailAllowed;

                groupMember.Person.LoadAttributes();

                foreach ( var attributeControl in attributeControls )
                {
                    NewFamilyAttributesRow attributeRow = attributeControl.AttributesRows.FirstOrDefault( r => r.PersonGuid == row.PersonGuid );
                    if ( attributeRow != null )
                    {
                        attributeRow.GetEditValues( groupMember.Person );
                    }
                }

                familyMembers.Add( groupMember );
            }

            return familyMembers;
        }
示例#33
0
        public override async System.Threading.Tasks.Task ExecuteAsync(List <string> command, List <BaseMessage> originMessage, MessageSourceType sourceType, UserInfo qq, Group group, GroupMember member)
        {
            var fromQQ  = 0L;
            var toGroup = 0L;

            //var message = "";
            if (sourceType != MessageSourceType.Group)
            {
                return;
            }

            fromQQ  = member.QQ;
            toGroup = member.GroupNumber;
            var permit = member.PermitType;

            if (!command.Any())
            {
                if (!GroupNewsConfig.TryGetValue(toGroup, out var config))
                {
                    MessageManager.SendTextMessage(MessageSourceType.Group, "当前群尚未开启新闻功能", fromQQ, toGroup);
                    return;
                }
            }
            else
            {
                if (command[0].Equals("on", StringComparison.CurrentCultureIgnoreCase))
                {
                    if (permit == PermitType.None)
                    {
                        MessageManager.SendTextMessage(MessageSourceType.Group, "只有群主或管理员才有权限开启新闻功能", fromQQ, toGroup);
                        return;
                    }

                    UpdateGroupNewsConfig(toGroup, true);
                    MessageManager.SendTextMessage(MessageSourceType.Group, "新闻功能已开启", fromQQ, toGroup);
                    return;
                }
                else if (command[0].Equals("off", StringComparison.CurrentCultureIgnoreCase))
                {
                    if (permit == PermitType.None)
                    {
                        MessageManager.SendTextMessage(MessageSourceType.Group, "只有群主或管理员才有权限关闭新闻功能", fromQQ, toGroup);
                        return;
                    }

                    UpdateGroupNewsConfig(toGroup, false);
                    MessageManager.SendTextMessage(MessageSourceType.Group, "新闻功能已关闭", fromQQ, toGroup);
                    return;
                }
            }

            using (var client = new HttpClient())
            {
                var url = "https://news.topurl.cn/api";
                var res = await client.GetAsync(url);

                if (!res.IsSuccessStatusCode)
                {
                    MessageManager.SendTextMessage(sourceType, "请求失败了QAQ", fromQQ, toGroup);
                    return;
                }

                var strContent = await res.Content.ReadAsStringAsync();

                var jsonRes = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(strContent, new
                {
                    data = new
                    {
                        newsList = new List <NewsModel>()
                    }
                });

                if (!(jsonRes?.data?.newsList?.Any() ?? false))
                {
                    MessageManager.SendTextMessage(sourceType, "没找到新闻捏", fromQQ, toGroup);
                    return;
                }

                var news    = jsonRes.data.newsList.Take(4).ToList();
                var message = new List <string>();
                news.ForEach(n =>
                {
                    message.Add($"{n.Title}:{n.Url}");
                });

                MessageManager.SendTextMessage(sourceType, string.Join("\n", message), fromQQ, toGroup);
            }
        }
        /// <summary>
        /// Shows the form field edit.
        /// </summary>
        /// <param name="formGuid">The form unique identifier.</param>
        /// <param name="formFieldGuid">The form field unique identifier.</param>
        private void ShowFormFieldEdit( Guid formGuid, Guid formFieldGuid )
        {
            if ( FormFieldsState.ContainsKey( formGuid ) )
            {
                ShowDialog( "Attributes" );

                var fieldList = FormFieldsState[formGuid];

                RegistrationTemplateFormField formField = fieldList.FirstOrDefault( a => a.Guid.Equals( formFieldGuid ) );
                if ( formField == null )
                {
                    formField = new RegistrationTemplateFormField();
                    formField.Guid = formFieldGuid;
                    formField.FieldSource = RegistrationFieldSource.PersonAttribute;
                }

                ceAttributePreText.Text = formField.PreText;
                ceAttributePostText.Text = formField.PostText;
                ddlFieldSource.SetValue( formField.FieldSource.ConvertToInt() );
                ddlPersonField.SetValue( formField.PersonFieldType.ConvertToInt() );
                lPersonField.Text = formField.PersonFieldType.ConvertToString();

                ddlPersonAttributes.Items.Clear();
                var person = new Person();
                person.LoadAttributes();
                foreach ( var attr in person.Attributes
                    .OrderBy( a => a.Value.Name )
                    .Select( a => a.Value ) )
                {
                    if ( attr.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                    {
                        ddlPersonAttributes.Items.Add( new ListItem( attr.Name, attr.Id.ToString() ) );
                    }
                }

                ddlGroupTypeAttributes.Items.Clear();
                var group = new Group();
                group.GroupTypeId = gtpGroupType.SelectedGroupTypeId ?? 0;
                var groupMember = new GroupMember();
                groupMember.Group = group;
                groupMember.LoadAttributes();
                foreach ( var attr in groupMember.Attributes
                    .OrderBy( a => a.Value.Name )
                    .Select( a => a.Value ) )
                {
                    if ( attr.IsAuthorized( Authorization.VIEW, CurrentPerson ) )
                    {
                        ddlGroupTypeAttributes.Items.Add( new ListItem( attr.Name, attr.Id.ToString() ) );
                    }
                }

                var attribute = new Attribute();
                attribute.FieldTypeId = FieldTypeCache.Read( Rock.SystemGuid.FieldType.TEXT ).Id;

                if ( formField.FieldSource == RegistrationFieldSource.PersonAttribute )
                {
                    ddlPersonAttributes.SetValue( formField.AttributeId );
                }
                else if ( formField.FieldSource == RegistrationFieldSource.GroupMemberAttribute )
                {
                    ddlGroupTypeAttributes.SetValue( formField.AttributeId );
                }
                else if ( formField.FieldSource == RegistrationFieldSource.RegistrationAttribute )
                {
                    if ( formField.Attribute != null )
                    {
                        attribute = formField.Attribute;
                    }
                }

                edtRegistrationAttribute.SetAttributeProperties( attribute, typeof( RegistrationTemplate ) );

                cbInternalField.Checked = formField.IsInternal;
                cbShowOnGrid.Checked = formField.IsGridField;
                cbRequireInInitialEntry.Checked = formField.IsRequired;
                cbUsePersonCurrentValue.Checked = formField.ShowCurrentValue;
                cbCommonValue.Checked = formField.IsSharedValue;

                hfFormGuid.Value = formGuid.ToString();
                hfAttributeGuid.Value = formFieldGuid.ToString();

                lPersonField.Visible = formField.FieldSource == RegistrationFieldSource.PersonField && (
                    formField.PersonFieldType == RegistrationPersonFieldType.FirstName ||
                    formField.PersonFieldType == RegistrationPersonFieldType.LastName );

                SetFieldDisplay();
            }

            BuildControls( true );
        }
示例#35
0
 /// <summary>
 /// Casts the Restore vita restoration spell on a target.
 /// </summary>
 /// <param name="target">An external member of the caster's group.</param>
 /// <returns>True if the spell was cast; false otherwise.</returns>
 public async Task <bool> Restore(GroupMember target)
 {
     return(await Restore(target.Uid, target.Name));
 }
示例#36
0
        /// <summary>
        /// Saves the registration.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="hasPayment">if set to <c>true</c> [has payment].</param>
        /// <returns></returns>
        private Registration SaveRegistration( RockContext rockContext, bool hasPayment )
        {
            var registrationService = new RegistrationService( rockContext );
            var registrantService = new RegistrationRegistrantService( rockContext );
            var personService = new PersonService( rockContext );
            var groupMemberService = new GroupMemberService( rockContext );

            // variables to keep track of the family that new people should be added to
            int? singleFamilyId = null;
            var multipleFamilyGroupIds = new Dictionary<Guid, int>();

            var dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() );
            var dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() );
            var familyGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY );
            var adultRoleId = familyGroupType.Roles
                .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid() ) )
                .Select( r => r.Id )
                .FirstOrDefault();
            var childRoleId = familyGroupType.Roles
                .Where( r => r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid() ) )
                .Select( r => r.Id )
                .FirstOrDefault();

            var registration = new Registration();
            registrationService.Add( registration );
            registration.RegistrationInstanceId = RegistrationInstanceState.Id;
            registration.GroupId = GroupId;
            registration.FirstName = RegistrationState.FirstName;
            registration.LastName = RegistrationState.LastName;
            registration.ConfirmationEmail = RegistrationState.ConfirmationEmail;
            registration.DiscountCode = RegistrationState.DiscountCode;
            registration.DiscountAmount = RegistrationState.DiscountAmount;
            registration.DiscountPercentage = RegistrationState.DiscountPercentage;

            // If the 'your name' value equals the currently logged in person, use their person alias id
            if ( CurrentPerson != null &&
                ( CurrentPerson.NickName.Trim().Equals( registration.FirstName.Trim(), StringComparison.OrdinalIgnoreCase ) ||
                    CurrentPerson.FirstName.Trim().Equals( registration.FirstName.Trim(), StringComparison.OrdinalIgnoreCase ) ) &&
                CurrentPerson.LastName.Trim().Equals( registration.LastName.Trim(), StringComparison.OrdinalIgnoreCase ) )
            {
                registration.PersonAliasId = CurrentPerson.PrimaryAliasId;
            }
            else
            {
                // otherwise look for one and one-only match by name/email
                var personMatches = personService.GetByMatch( registration.FirstName, registration.LastName, registration.ConfirmationEmail );
                if ( personMatches.Count() == 1 )
                {
                    registration.PersonAliasId = personMatches.First().PrimaryAliasId;
                }
            }

            // If the registration includes a payment, make sure there's an actual person associated to registration
            if ( hasPayment && !registration.PersonAliasId.HasValue )
            {
                // If a match was not found, create a new person
                var person = new Person();
                person.FirstName = registration.FirstName;
                person.LastName = registration.LastName;
                person.IsEmailActive = true;
                person.Email = registration.ConfirmationEmail;
                person.EmailPreference = EmailPreference.EmailAllowed;
                person.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id;
                if ( dvcConnectionStatus != null )
                {
                    person.ConnectionStatusValueId = dvcConnectionStatus.Id;
                }
                if ( dvcRecordStatus != null )
                {
                    person.RecordStatusValueId = dvcRecordStatus.Id;
                }

                registration.PersonAliasId = SavePerson( rockContext, person, Guid.NewGuid(), null, null, adultRoleId, childRoleId, multipleFamilyGroupIds, singleFamilyId );
            }

            // Save the registration ( so we can get an id )
            rockContext.SaveChanges();

            // If the Registration Instance linkage specified a group, load it now
            Group group = null;
            if ( GroupId.HasValue )
            {
                group = new GroupService( rockContext ).Get( GroupId.Value );
            }

            // Get each registrant
            foreach ( var registrantInfo in RegistrationState.Registrants )
            {
                var changes = new List<string>();
                var familyChanges = new List<string>();

                Person person = null;

                // Try to find a matching person based on name and email address
                string firstName = registrantInfo.GetFirstName( RegistrationTemplate );
                string lastName = registrantInfo.GetLastName( RegistrationTemplate );
                string email = registrantInfo.GetEmail( RegistrationTemplate );
                var personMatches = personService.GetByMatch( firstName, lastName, email );
                if ( personMatches.Count() == 1 )
                {
                    person = personMatches.First();
                }

                if ( person == null )
                {
                    // If a match was not found, create a new person
                    person = new Person();
                    person.FirstName = firstName;
                    person.LastName = lastName;
                    person.IsEmailActive = true;
                    person.Email = email;
                    person.EmailPreference = EmailPreference.EmailAllowed;
                    person.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid() ).Id;
                    if ( dvcConnectionStatus != null )
                    {
                        person.ConnectionStatusValueId = dvcConnectionStatus.Id;
                    }

                    if ( dvcRecordStatus != null )
                    {
                        person.RecordStatusValueId = dvcRecordStatus.Id;
                    }
                }

                int? campusId = null;
                Location location = null;

                // Set any of the template's person fields
                foreach ( var field in RegistrationTemplate.Forms
                    .SelectMany( f => f.Fields
                        .Where( t => t.FieldSource == RegistrationFieldSource.PersonField ) ) )
                {
                    // Find the registrant's value
                    var fieldValue = registrantInfo.FieldValues
                        .Where( f => f.Key == field.Id )
                        .Select( f => f.Value )
                        .FirstOrDefault();

                    if ( fieldValue != null )
                    {
                        switch ( field.PersonFieldType )
                        {
                            case RegistrationPersonFieldType.Campus:
                                {
                                    if ( fieldValue != null )
                                    {
                                        campusId = fieldValue.ToString().AsIntegerOrNull();
                                    }
                                    break;
                                }

                            case RegistrationPersonFieldType.Address:
                                {
                                    location = fieldValue.ToString().FromJsonOrNull<Location>();
                                    break;
                                }

                            case RegistrationPersonFieldType.Birthdate:
                                {
                                    var birthMonth = person.BirthMonth;
                                    var birthDay = person.BirthDay;
                                    var birthYear = person.BirthYear;

                                    person.SetBirthDate( fieldValue as DateTime? );

                                    History.EvaluateChange( changes, "Birth Month", birthMonth, person.BirthMonth );
                                    History.EvaluateChange( changes, "Birth Day", birthDay, person.BirthDay );
                                    History.EvaluateChange( changes, "Birth Year", birthYear, person.BirthYear );

                                    break;
                                }

                            case RegistrationPersonFieldType.Gender:
                                {
                                    var newGender = fieldValue.ToString().ConvertToEnumOrNull<Gender>() ?? Gender.Unknown;
                                    History.EvaluateChange( changes, "Gender", person.Gender, newGender );
                                    person.Gender = newGender;
                                    break;
                                }

                            case RegistrationPersonFieldType.MaritalStatus:
                                {
                                    if ( fieldValue != null  )
                                    {
                                        int? newMaritalStatusId = fieldValue.ToString().AsIntegerOrNull();
                                        History.EvaluateChange( changes, "Marital Status", DefinedValueCache.GetName( person.MaritalStatusValueId ), DefinedValueCache.GetName( newMaritalStatusId ) );
                                        person.MaritalStatusValueId = newMaritalStatusId;
                                    }
                                    break;
                                }

                            case RegistrationPersonFieldType.MobilePhone:
                                {
                                    SavePhone( fieldValue, person, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid(), changes );
                                    break;
                                }

                            case RegistrationPersonFieldType.HomePhone:
                                {
                                    SavePhone( fieldValue, person, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME.AsGuid(), changes );
                                    break;
                                }

                            case RegistrationPersonFieldType.WorkPhone:
                                {
                                    SavePhone( fieldValue, person, Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK.AsGuid(), changes );
                                    break;
                                }
                        }
                    }
                }

                // Save the person ( and family if needed )
                SavePerson( rockContext, person, registrantInfo.FamilyGuid, campusId, location, adultRoleId, childRoleId, multipleFamilyGroupIds, singleFamilyId );

                // Load the person's attributes
                person.LoadAttributes();

                // Set any of the template's person fields
                foreach ( var field in RegistrationTemplate.Forms
                    .SelectMany( f => f.Fields
                        .Where( t =>
                            t.FieldSource == RegistrationFieldSource.PersonAttribute &&
                            t.AttributeId.HasValue ) ) )
                {
                    // Find the registrant's value
                    var fieldValue = registrantInfo.FieldValues
                        .Where( f => f.Key == field.Id )
                        .Select( f => f.Value )
                        .FirstOrDefault();

                    if ( fieldValue != null )
                    {
                        var attribute = AttributeCache.Read( field.AttributeId.Value );
                        if ( attribute != null )
                        {
                            string originalValue = person.GetAttributeValue( attribute.Key );
                            string newValue = fieldValue.ToString();
                            person.SetAttributeValue( attribute.Key, fieldValue.ToString() );

                            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( changes, attribute.Name, formattedOriginalValue, formattedNewValue );
                            }
                        }
                    }
                }

                person.SaveAttributeValues( rockContext );

                GroupMember groupMember = null;

                // If the registration instance linkage specified a group to add registrant to, add them if there not already
                // part of that group
                if ( group != null )
                {
                    groupMember = group.Members.Where( m => m.PersonId == person.Id ).FirstOrDefault();
                    if ( groupMember == null && group.GroupType.DefaultGroupRoleId.HasValue )
                    {
                        groupMember = new GroupMember();
                        groupMemberService.Add( groupMember );
                        groupMember.GroupId = group.Id;
                        groupMember.PersonId = person.Id;

                        if ( RegistrationTemplate.GroupTypeId.HasValue &&
                            RegistrationTemplate.GroupTypeId == group.GroupTypeId &&
                            RegistrationTemplate.GroupMemberRoleId.HasValue )
                        {
                            groupMember.GroupRoleId = RegistrationTemplate.GroupMemberRoleId.Value;
                            groupMember.GroupMemberStatus = RegistrationTemplate.GroupMemberStatus;
                        }
                        else
                        {
                            groupMember.GroupRoleId = group.GroupType.DefaultGroupRoleId.Value;
                            groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                        }
                    }

                    rockContext.SaveChanges();

                    // Set any of the template's group member attributes
                    groupMember.LoadAttributes();

                    foreach ( var field in RegistrationTemplate.Forms
                        .SelectMany( f => f.Fields
                            .Where( t =>
                                t.FieldSource == RegistrationFieldSource.GroupMemberAttribute &&
                                t.AttributeId.HasValue ) ) )
                    {
                        // Find the registrant's value
                        var fieldValue = registrantInfo.FieldValues
                            .Where( f => f.Key == field.Id )
                            .Select( f => f.Value )
                            .FirstOrDefault();

                        if ( fieldValue != null )
                        {
                            var attribute = AttributeCache.Read( field.AttributeId.Value );
                            if ( attribute != null )
                            {
                                groupMember.SetAttributeValue( attribute.Key, fieldValue.ToString() );
                            }
                        }
                    }

                    groupMember.SaveAttributeValues( rockContext );
                }

                var registrant = new RegistrationRegistrant();
                registrantService.Add( registrant );
                registrant.RegistrationId = registration.Id;
                registrant.PersonAliasId = person.PrimaryAliasId;
                registrant.Cost = registrantInfo.Cost;
                registrant.GroupMemberId = groupMember != null ? groupMember.Id : (int?)null;

                // Add or Update fees
                foreach ( var feeValue in registrantInfo.FeeValues.Where( f => f.Value != null ) )
                {
                    foreach ( var uiFee in feeValue.Value )
                    {
                        var fee = new RegistrationRegistrantFee();
                        registrant.Fees.Add( fee );
                        fee.RegistrationTemplateFeeId = feeValue.Key;
                        fee.Option = uiFee.Option;
                        fee.Quantity = uiFee.Quantity;
                        fee.Cost = uiFee.Cost;
                    }
                }

                rockContext.SaveChanges();

                // Set any of the templat's registrant attributes
                registrant.LoadAttributes();
                foreach ( var field in RegistrationTemplate.Forms
                    .SelectMany( f => f.Fields
                        .Where( t =>
                            t.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                            t.AttributeId.HasValue ) ) )
                {
                    // Find the registrant's value
                    var fieldValue = registrantInfo.FieldValues
                        .Where( f => f.Key == field.Id )
                        .Select( f => f.Value )
                        .FirstOrDefault();

                    if ( fieldValue != null )
                    {
                        var attribute = AttributeCache.Read( field.AttributeId.Value );
                        if ( attribute != null )
                        {
                            registrant.SetAttributeValue( attribute.Key, fieldValue.ToString() );
                        }
                    }

                    registrant.SaveAttributeValues( rockContext );
                }
            }

            return registration;
        }
示例#37
0
        public void UpdateSubscription(Guid communicationListGuid, bool subscribed)
        {
            using (var rockContext = new RockContext())
            {
                var groupMemberService = new GroupMemberService(rockContext);
                var group = new GroupService(rockContext).Get(communicationListGuid);
                var groupMemberRecordsForPerson = groupMemberService.Queryable()
                                                  .Where(a => a.GroupId == group.Id && a.PersonId == RequestContext.CurrentPerson.Id)
                                                  .ToList();

                if (groupMemberRecordsForPerson.Any())
                {
                    // normally there would be at most 1 group member record for the person, but just in case, mark them all
                    foreach (var groupMember in groupMemberRecordsForPerson)
                    {
                        if (subscribed)
                        {
                            if (groupMember.GroupMemberStatus == GroupMemberStatus.Inactive)
                            {
                                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                if (groupMember.Note == "Unsubscribed")
                                {
                                    groupMember.Note = string.Empty;
                                }
                            }
                        }
                        else
                        {
                            if (groupMember.GroupMemberStatus == GroupMemberStatus.Active)
                            {
                                groupMember.GroupMemberStatus = GroupMemberStatus.Inactive;
                                if (groupMember.Note.IsNullOrWhiteSpace())
                                {
                                    groupMember.Note = "Unsubscribed";
                                }
                            }
                        }

                        // TODO: Change this to null.
                        groupMember.CommunicationPreference = CommunicationType.Email;
                    }
                }
                else if (subscribed)
                {
                    var groupMember = new GroupMember
                    {
                        PersonId = RequestContext.CurrentPerson.Id,
                        GroupId  = group.Id
                    };

                    int?defaultGroupRoleId = GroupTypeCache.Get(group.GroupTypeId).DefaultGroupRoleId;
                    if (defaultGroupRoleId.HasValue)
                    {
                        groupMember.GroupRoleId = defaultGroupRoleId.Value;
                    }

                    groupMember.GroupMemberStatus = GroupMemberStatus.Active;

                    if (groupMember.IsValidGroupMember(rockContext))
                    {
                        groupMemberService.Add(groupMember);
                        rockContext.SaveChanges();
                    }
                }

                rockContext.SaveChanges();
            }
        }
示例#38
0
        private Person GetPersonOrBusiness( Person person )
        {
            if ( person != null && phGiveAsOption.Visible && !tglGiveAsOption.Checked )
            {
                var rockContext = new RockContext();
                var personService = new PersonService( rockContext );
                var groupService = new GroupService( rockContext );
                var groupMemberService = new GroupMemberService( rockContext );

                Group familyGroup = null;

                Person business = null;
                int? businessId = cblBusiness.SelectedValueAsInt();
                if ( businessId.HasValue )
                {
                    business = personService.Get( businessId.Value );
                }

                if ( business == null )
                {
                    DefinedValueCache dvcConnectionStatus = DefinedValueCache.Read( GetAttributeValue( "ConnectionStatus" ).AsGuid() );
                    DefinedValueCache dvcRecordStatus = DefinedValueCache.Read( GetAttributeValue( "RecordStatus" ).AsGuid() );

                    // Create Person
                    business = new Person();
                    business.LastName = txtLastName.Text;
                    business.IsEmailActive = true;
                    business.EmailPreference = EmailPreference.EmailAllowed;
                    business.RecordTypeValueId = DefinedValueCache.Read( Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_BUSINESS.AsGuid() ).Id;
                    if ( dvcConnectionStatus != null )
                    {
                        business.ConnectionStatusValueId = dvcConnectionStatus.Id;
                    }

                    if ( dvcRecordStatus != null )
                    {
                        business.RecordStatusValueId = dvcRecordStatus.Id;
                    }

                    // Create Person/Family
                    familyGroup = PersonService.SaveNewPerson( business, rockContext, null, false );

                    // Get the relationship roles to use
                    var knownRelationshipGroupType = GroupTypeCache.Read( Rock.SystemGuid.GroupType.GROUPTYPE_KNOWN_RELATIONSHIPS.AsGuid() );
                    int businessContactRoleId = knownRelationshipGroupType.Roles
                        .Where( r =>
                            r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS_CONTACT.AsGuid() ) )
                        .Select( r => r.Id )
                        .FirstOrDefault();
                    int businessRoleId = knownRelationshipGroupType.Roles
                        .Where( r =>
                            r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS.AsGuid() ) )
                        .Select( r => r.Id )
                        .FirstOrDefault();
                    int ownerRoleId = knownRelationshipGroupType.Roles
                        .Where( r =>
                            r.Guid.Equals( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER.AsGuid() ) )
                        .Select( r => r.Id )
                        .FirstOrDefault();

                    if ( ownerRoleId > 0 && businessContactRoleId > 0 && businessRoleId > 0 )
                    {
                        // get the known relationship group of the business contact
                        // add the business as a group member of that group using the group role of GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS
                        var contactKnownRelationshipGroup = groupMemberService.Queryable()
                            .Where( g =>
                                g.GroupRoleId == ownerRoleId &&
                                g.PersonId == person.Id )
                            .Select( g => g.Group )
                            .FirstOrDefault();
                        if ( contactKnownRelationshipGroup == null )
                        {
                            // In some cases person may not yet have a know relationship group type
                            contactKnownRelationshipGroup = new Group();
                            groupService.Add( contactKnownRelationshipGroup );
                            contactKnownRelationshipGroup.Name = "Known Relationship";
                            contactKnownRelationshipGroup.GroupTypeId = knownRelationshipGroupType.Id;

                            var ownerMember = new GroupMember();
                            ownerMember.PersonId = person.Id;
                            ownerMember.GroupRoleId = ownerRoleId;
                            contactKnownRelationshipGroup.Members.Add( ownerMember );
                        }
                        var groupMember = new GroupMember();
                        groupMember.PersonId = business.Id;
                        groupMember.GroupRoleId = businessRoleId;
                        contactKnownRelationshipGroup.Members.Add( groupMember );

                        // get the known relationship group of the business
                        // add the business contact as a group member of that group using the group role of GROUPROLE_KNOWN_RELATIONSHIPS_BUSINESS_CONTACT
                        var businessKnownRelationshipGroup = groupMemberService.Queryable()
                            .Where( g =>
                                g.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER ) ) &&
                                g.PersonId == business.Id )
                            .Select( g => g.Group )
                            .FirstOrDefault();
                        if ( businessKnownRelationshipGroup == null )
                        {
                            // In some cases business may not yet have a know relationship group type
                            businessKnownRelationshipGroup = new Group();
                            groupService.Add( businessKnownRelationshipGroup );
                            businessKnownRelationshipGroup.Name = "Known Relationship";
                            businessKnownRelationshipGroup.GroupTypeId = knownRelationshipGroupType.Id;

                            var ownerMember = new GroupMember();
                            ownerMember.PersonId = business.Id;
                            ownerMember.GroupRoleId = ownerRoleId;
                            businessKnownRelationshipGroup.Members.Add( ownerMember );
                        }
                        var businessGroupMember = new GroupMember();
                        businessGroupMember.PersonId = person.Id;
                        businessGroupMember.GroupRoleId = businessContactRoleId;
                        businessKnownRelationshipGroup.Members.Add( businessGroupMember );

                        rockContext.SaveChanges();
                    }
                }

                business.LastName = txtBusinessName.Text;
                business.Email = txtEmail.Text;

                if ( GetAttributeValue( "DisplayPhone" ).AsBooleanOrNull() ?? false )
                {
                    var numberTypeId = DefinedValueCache.Read( new Guid( Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_WORK ) ).Id;
                    var phone = business.PhoneNumbers.FirstOrDefault( p => p.NumberTypeValueId == numberTypeId );
                    if ( phone == null )
                    {
                        phone = new PhoneNumber();
                        business.PhoneNumbers.Add( phone );
                        phone.NumberTypeValueId = numberTypeId;
                    }
                    phone.CountryCode = PhoneNumber.CleanNumber( pnbPhone.CountryCode );
                    phone.Number = PhoneNumber.CleanNumber( pnbPhone.Number );
                }

                if ( familyGroup == null )
                {
                    var groupLocationService = new GroupLocationService( rockContext );
                    if ( GroupLocationId.HasValue )
                    {
                        familyGroup = groupLocationService.Queryable()
                            .Where( gl => gl.Id == GroupLocationId.Value )
                            .Select( gl => gl.Group )
                            .FirstOrDefault();
                    }
                    else
                    {
                        familyGroup = personService.GetFamilies( business.Id ).FirstOrDefault();
                    }
                }

                rockContext.SaveChanges();

                if ( familyGroup != null )
                {
                    GroupService.AddNewGroupAddress(
                        rockContext,
                        familyGroup,
                        Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_WORK,
                        acAddress.Street1, acAddress.Street2, acAddress.City, acAddress.State, acAddress.PostalCode, acAddress.Country,
                        false );
                }

                return business;
            }

            return person;
        }
示例#39
0
        /// <summary>
        /// Saves the people.
        /// </summary>
        /// <param name="familyList">The family list.</param>
        /// <param name="visitorList">The visitor list.</param>
        /// <param name="previousNamesList">The previous names list.</param>
        private static void SavePeople(List <Group> familyList, List <Group> visitorList, Dictionary <Guid, string> previousNamesList)
        {
            var rockContext        = new RockContext();
            var groupMemberService = new GroupMemberService(rockContext);

            rockContext.WrapTransaction(() =>
            {
                rockContext.Configuration.AutoDetectChangesEnabled = false;
                rockContext.Groups.AddRange(familyList);
                rockContext.SaveChanges(DisableAuditing);

                foreach (var familyGroups in familyList.GroupBy(g => g.ForeignId))
                {
                    var visitorsExist = familyGroups.Count() > 1;
                    foreach (var newFamilyGroup in familyGroups)
                    {
                        foreach (var groupMember in newFamilyGroup.Members)
                        {
                            // don't call LoadAttributes, it only rewrites existing cache objects
                            // groupMember.Person.LoadAttributes( rockContext );

                            var memberPersonAttributeValues = groupMember.Person.Attributes.Select(a => a.Value)
                                                              .Select(a => new AttributeValue
                            {
                                AttributeId = a.Id,
                                EntityId    = groupMember.Person.Id,
                                Value       = groupMember.Person.AttributeValues[a.Key].Value
                            }).ToList();

                            rockContext.AttributeValues.AddRange(memberPersonAttributeValues);

                            // add a default person alias
                            if (!groupMember.Person.Aliases.Any(a => a.AliasPersonId == groupMember.Person.Id))
                            {
                                groupMember.Person.Aliases.Add(new PersonAlias
                                {
                                    AliasPersonId   = groupMember.Person.Id,
                                    AliasPersonGuid = groupMember.Person.Guid,
                                    ForeignId       = groupMember.Person.ForeignId,
                                    ForeignKey      = groupMember.Person.ForeignKey
                                });
                            }

                            // assign the previous name
                            if (previousNamesList.Any(l => l.Key.Equals(groupMember.Person.Guid)))
                            {
                                var newPreviousName = new PersonPreviousName
                                {
                                    LastName    = previousNamesList[groupMember.Person.Guid],
                                    PersonAlias = groupMember.Person.Aliases.FirstOrDefault()
                                };

                                rockContext.PersonPreviousNames.Add(newPreviousName);
                            }

                            // assign the giving group
                            if (groupMember.GroupRoleId != FamilyChildRoleId)
                            {
                                groupMember.Person.GivingGroupId = newFamilyGroup.Id;
                            }

                            // Add known relationship group
                            var knownGroupMember = new GroupMember
                            {
                                PersonId    = groupMember.Person.Id,
                                GroupRoleId = KnownRelationshipOwnerRoleId
                            };

                            var knownRelationshipGroup = new Group
                            {
                                Name        = KnownRelationshipGroupType.Name,
                                GroupTypeId = KnownRelationshipGroupType.Id,
                                IsPublic    = true
                            };

                            knownRelationshipGroup.Members.Add(knownGroupMember);
                            rockContext.Groups.Add(knownRelationshipGroup);

                            // Add implied relationship group
                            var impliedGroupMember = new GroupMember
                            {
                                PersonId    = groupMember.Person.Id,
                                GroupRoleId = ImpliedRelationshipOwnerRoleId
                            };

                            var impliedGroup = new Group
                            {
                                Name        = ImpliedRelationshipGroupType.Name,
                                GroupTypeId = ImpliedRelationshipGroupType.Id,
                                IsPublic    = true
                            };

                            impliedGroup.Members.Add(impliedGroupMember);
                            rockContext.Groups.Add(impliedGroup);

                            if (visitorsExist)
                            {
                                // if this is a visitor, then add relationships to the family member(s)
                                if (visitorList.Where(v => v.ForeignId == newFamilyGroup.ForeignId)
                                    .Any(v => v.Members.Any(m => m.Person.ForeignId.Equals(groupMember.Person.ForeignId))))
                                {
                                    var familyMembers = familyGroups.Except(visitorList).SelectMany(g => g.Members);
                                    foreach (var familyMember in familyMembers.Select(m => m.Person))
                                    {
                                        var invitedByMember = new GroupMember
                                        {
                                            PersonId    = familyMember.Id,
                                            GroupRoleId = InvitedByKnownRelationshipId
                                        };

                                        knownRelationshipGroup.Members.Add(invitedByMember);

                                        if (groupMember.Person.Age < 15 && familyMember.Age > 15)
                                        {
                                            var allowCheckinMember = new GroupMember
                                            {
                                                PersonId    = familyMember.Id,
                                                GroupRoleId = AllowCheckInByKnownRelationshipId
                                            };

                                            knownRelationshipGroup.Members.Add(allowCheckinMember);
                                        }
                                    }
                                }
                                else
                                {   // not a visitor, add the visitors to the family member's known relationship
                                    var visitors = visitorList.Where(v => v.ForeignId == newFamilyGroup.ForeignId)
                                                   .SelectMany(g => g.Members).ToList();
                                    foreach (var visitor in visitors.Select(g => g.Person))
                                    {
                                        var inviteeMember = new GroupMember
                                        {
                                            PersonId    = visitor.Id,
                                            GroupRoleId = InviteeKnownRelationshipId
                                        };

                                        knownRelationshipGroup.Members.Add(inviteeMember);

                                        // if visitor can be checked in and this person is considered an adult
                                        if (visitor.Age < 18 && groupMember.Person.Age > 18)
                                        {
                                            var canCheckInMember = new GroupMember
                                            {
                                                PersonId    = visitor.Id,
                                                GroupRoleId = CanCheckInKnownRelationshipId
                                            };

                                            knownRelationshipGroup.Members.Add(canCheckInMember);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                rockContext.ChangeTracker.DetectChanges();
                rockContext.SaveChanges(DisableAuditing);
            });  // end wrap transaction

            // add the new people to our tracking list
            if (familyList.Any())
            {
                var familyMembers = familyList.SelectMany(gm => gm.Members);
                ImportedPeople.AddRange(familyMembers.Select(m => new PersonKeys
                {
                    PersonAliasId   = ( int )m.Person.PrimaryAliasId,
                    PersonId        = m.Person.Id,
                    PersonGender    = m.Person.Gender,
                    PersonForeignId = m.Person.ForeignId,
                    GroupForeignId  = m.Group.ForeignId,
                    FamilyRoleId    = m.Person.ReviewReasonNote.ConvertToEnum <FamilyRole>()
                }).ToList()
                                        );
            }

            if (visitorList.Any())
            {
                var visitors = visitorList.SelectMany(gm => gm.Members);
                ImportedPeople.AddRange(visitors.Select(m => new PersonKeys
                {
                    PersonAliasId   = ( int )m.Person.PrimaryAliasId,
                    PersonId        = m.Person.Id,
                    PersonGender    = m.Person.Gender,
                    PersonForeignId = m.Person.ForeignId,
                    GroupForeignId  = m.Group.ForeignId,
                    FamilyRoleId    = m.Person.ReviewReasonNote.ConvertToEnum <FamilyRole>()
                }).ToList()
                                        );
            }
        }
        /// <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 )
        {
            // confirmation was disabled by btnSave on client-side.  So if returning without a redirect,
            // it should be enabled.  If returning with a redirect, the control won't be updated to reflect
            // confirmation being enabled, so it's ok to enable it here
            confirmExit.Enabled = true;

            if ( Page.IsValid )
            {
                confirmExit.Enabled = true;

                RockTransactionScope.WrapTransaction( () =>
                {
                    var rockContext = new RockContext();
                    var familyService = new GroupService( rockContext );
                    var familyMemberService = new GroupMemberService( rockContext );
                    var personService = new PersonService( rockContext );
                    var historyService = new HistoryService( rockContext );

                    var familyChanges = new List<string>();

                    // SAVE FAMILY
                    _family = familyService.Get( _family.Id );

                    History.EvaluateChange( familyChanges, "Family Name", _family.Name, tbFamilyName.Text );
                    _family.Name = tbFamilyName.Text;

                    int? campusId = cpCampus.SelectedValueAsInt();
                    if ( _family.CampusId != campusId )
                    {
                        History.EvaluateChange( familyChanges, "Campus",
                            _family.CampusId.HasValue ? CampusCache.Read( _family.CampusId.Value ).Name : string.Empty,
                            campusId.HasValue ? CampusCache.Read( campusId.Value ).Name : string.Empty );
                        _family.CampusId = campusId;
                    }

                    var familyGroupTypeId = _family.GroupTypeId;

                    rockContext.SaveChanges();

                    // SAVE FAMILY MEMBERS
                    int? recordStatusValueID = ddlRecordStatus.SelectedValueAsInt();
                    int? reasonValueId = ddlReason.SelectedValueAsInt();
                    var newFamilies = new List<Group>();

                    foreach ( var familyMember in FamilyMembers )
                    {
                        var memberChanges = new List<string>();
                        var demographicChanges = new List<string>();

                        var role = familyRoles.Where( r => r.Guid.Equals( familyMember.RoleGuid ) ).FirstOrDefault();
                        if ( role == null )
                        {
                            role = familyRoles.FirstOrDefault();
                        }

                        bool isChild = role != null && role.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD ) );

                        // People added to family (new or from other family)
                        if ( !familyMember.ExistingFamilyMember )
                        {
                            var groupMember = new GroupMember();

                            if ( familyMember.Id == -1 )
                            {
                                // added new person
                                demographicChanges.Add( "Created" );

                                var person = new Person();
                                person.FirstName = familyMember.FirstName;
                                person.NickName = familyMember.NickName;
                                History.EvaluateChange( demographicChanges, "First Name", string.Empty, person.FirstName );

                                person.LastName = familyMember.LastName;
                                History.EvaluateChange( demographicChanges, "Last Name", string.Empty, person.LastName );

                                person.Gender = familyMember.Gender;
                                History.EvaluateChange( demographicChanges, "Gender", null, person.Gender );

                                person.BirthDate = familyMember.BirthDate;
                                History.EvaluateChange( demographicChanges, "Birth Date", null, person.BirthDate );

                                if ( !isChild )
                                {
                                    person.GivingGroupId = _family.Id;
                                    History.EvaluateChange( demographicChanges, "Giving Group", string.Empty, _family.Name );
                                }

                                person.EmailPreference = EmailPreference.EmailAllowed;

                                groupMember.Person = person;
                            }
                            else
                            {
                                // added from other family
                                groupMember.Person = personService.Get( familyMember.Id );
                            }

                            if ( recordStatusValueID > 0 )
                            {
                                History.EvaluateChange( demographicChanges, "Record Status", DefinedValueCache.GetName( groupMember.Person.RecordStatusValueId ), DefinedValueCache.GetName( recordStatusValueID ) );
                                groupMember.Person.RecordStatusValueId = recordStatusValueID;

                                History.EvaluateChange( demographicChanges, "Record Status Reason", DefinedValueCache.GetName( groupMember.Person.RecordStatusReasonValueId ), DefinedValueCache.GetName( reasonValueId ) );
                                groupMember.Person.RecordStatusReasonValueId = reasonValueId;
                            }

                            groupMember.GroupId = _family.Id;
                            if ( role != null )
                            {
                                History.EvaluateChange( memberChanges, "Role", string.Empty, role.Name );
                                groupMember.GroupRoleId = role.Id;
                            }

                            if ( groupMember.Person != null )
                            {
                                familyMemberService.Add( groupMember );
                                rockContext.SaveChanges();
                                familyMember.Id = groupMember.Person.Id;
                            }

                        }
                        else
                        {
                            // existing family members
                            var groupMember = familyMemberService.Queryable( "Person" ).Where( m =>
                                m.PersonId == familyMember.Id &&
                                m.Group.GroupTypeId == familyGroupTypeId &&
                                m.GroupId == _family.Id ).FirstOrDefault();

                            if ( groupMember != null )
                            {
                                if ( familyMember.Removed )
                                {
                                    var newFamilyChanges = new List<string>();

                                    // Family member was removed and should be created in their own new family
                                    var newFamily = new Group();
                                    newFamily.Name = familyMember.LastName + " Family";
                                    History.EvaluateChange( newFamilyChanges, "Family", string.Empty, newFamily.Name );

                                    newFamily.GroupTypeId = familyGroupTypeId;

                                    if ( _family.CampusId.HasValue )
                                    {
                                        History.EvaluateChange( newFamilyChanges, "Campus", string.Empty, CampusCache.Read( _family.CampusId.Value ).Name );
                                    }
                                    newFamily.CampusId = _family.CampusId;

                                    familyService.Add( newFamily );
                                    rockContext.SaveChanges();

                                    // If person's previous giving group was this family, set it to their new family id
                                    if ( groupMember.Person.GivingGroup != null && groupMember.Person.GivingGroupId == _family.Id )
                                    {
                                        History.EvaluateChange( demographicChanges, "Giving Group", groupMember.Person.GivingGroup.Name, _family.Name );
                                        groupMember.Person.GivingGroupId = newFamily.Id;
                                    }

                                    groupMember.Group = newFamily;
                                    rockContext.SaveChanges();

                                    var newMemberChanges = new List<string>();
                                    History.EvaluateChange( newMemberChanges, "Role", string.Empty, groupMember.GroupRole.Name );

                                    HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                        groupMember.Person.Id, newFamilyChanges, newFamily.Name, typeof( Group ), newFamily.Id );

                                    newFamilies.Add( newFamily );

                                    History.EvaluateChange( memberChanges, "Role", groupMember.GroupRole.Name, string.Empty );
                                }
                                else
                                {
                                    // Existing member was not remvoved
                                    if ( role != null )
                                    {
                                        History.EvaluateChange( memberChanges, "Role",
                                            groupMember.GroupRole != null ? groupMember.GroupRole.Name : string.Empty, role.Name );
                                        groupMember.GroupRoleId = role.Id;

                                        if ( recordStatusValueID > 0 )
                                        {
                                            History.EvaluateChange( demographicChanges, "Record Status", DefinedValueCache.GetName( groupMember.Person.RecordStatusValueId ), DefinedValueCache.GetName( recordStatusValueID ) );
                                            groupMember.Person.RecordStatusValueId = recordStatusValueID;

                                            History.EvaluateChange( demographicChanges, "Record Status Reason", DefinedValueCache.GetName( groupMember.Person.RecordStatusReasonValueId ), DefinedValueCache.GetName( reasonValueId ) );
                                            groupMember.Person.RecordStatusReasonValueId = reasonValueId;
                                        }

                                        rockContext.SaveChanges();
                                    }
                                }
                            }
                        }

                        // Remove anyone that was moved from another family
                        if ( familyMember.RemoveFromOtherFamilies )
                        {
                            var otherFamilies = familyMemberService.Queryable()
                                .Where( m =>
                                    m.PersonId == familyMember.Id &&
                                    m.Group.GroupTypeId == familyGroupTypeId &&
                                    m.GroupId != _family.Id )
                                .ToList();

                            foreach ( var otherFamilyMember in otherFamilies )
                            {
                                var fm = familyMemberService.Get( otherFamilyMember.Id );

                                // If the person's giving group id was the family they are being removed from, update it to this new family's id
                                if ( fm.Person.GivingGroupId == fm.GroupId )
                                {
                                    var person = personService.Get( fm.PersonId );

                                    History.EvaluateChange( demographicChanges, "Giving Group", person.GivingGroup.Name, _family.Name );
                                    person.GivingGroupId = _family.Id;

                                    rockContext.SaveChanges();
                                }

                                var oldMemberChanges = new List<string>();
                                History.EvaluateChange( oldMemberChanges, "Role", fm.GroupRole.Name, string.Empty );
                                History.EvaluateChange( oldMemberChanges, "Family", fm.Group.Name, string.Empty );
                                HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                                    fm.Person.Id, oldMemberChanges, fm.Group.Name, typeof( Group ), fm.Group.Id );

                                familyMemberService.Delete( fm );
                                rockContext.SaveChanges();

                                var f = familyService.Queryable()
                                    .Where( g =>
                                        g.Id == otherFamilyMember.GroupId &&
                                        !g.Members.Any() )
                                    .FirstOrDefault();
                                if ( f != null )
                                {
                                    familyService.Delete( f );
                                    rockContext.SaveChanges();
                                }

                            }
                        }

                        HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_DEMOGRAPHIC_CHANGES.AsGuid(),
                            familyMember.Id, demographicChanges );

                        HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                            familyMember.Id, memberChanges, _family.Name, typeof( Group ), _family.Id );
                    }

                    // SAVE LOCATIONS
                    var groupLocationService = new GroupLocationService( rockContext );

                    // delete any group locations that were removed
                    var remainingLocationIds = FamilyAddresses.Where( a => a.Id > 0 ).Select( a => a.Id ).ToList();
                    foreach ( var removedLocation in groupLocationService.Queryable( "GroupLocationTypeValue,Location" )
                        .Where( l => l.GroupId == _family.Id &&
                            !remainingLocationIds.Contains( l.Id ) ) )
                    {
                        History.EvaluateChange( familyChanges, removedLocation.GroupLocationTypeValue.Name + " Location",
                            removedLocation.Location.ToString(), string.Empty );
                        groupLocationService.Delete( removedLocation );
                    }
                    rockContext.SaveChanges();

                    foreach ( var familyAddress in FamilyAddresses )
                    {
                        Location updatedAddress = null;
                        if ( familyAddress.LocationIsDirty )
                        {
                            updatedAddress = new LocationService( rockContext ).Get(
                                familyAddress.Street1, familyAddress.Street2, familyAddress.City,
                                familyAddress.State, familyAddress.Zip );
                        }

                        GroupLocation groupLocation = null;
                        if ( familyAddress.Id > 0 )
                        {
                            groupLocation = groupLocationService.Get( familyAddress.Id );
                        }
                        if ( groupLocation == null )
                        {
                            groupLocation = new GroupLocation();
                            groupLocation.GroupId = _family.Id;
                            groupLocationService.Add( groupLocation );
                        }

                        History.EvaluateChange( familyChanges, "Location Type",
                            groupLocation.GroupLocationTypeValueId.HasValue ? DefinedValueCache.Read( groupLocation.GroupLocationTypeValueId.Value ).Name : string.Empty,
                            familyAddress.LocationTypeName );
                        groupLocation.GroupLocationTypeValueId = familyAddress.LocationTypeId;

                        History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Is Mailing",
                            groupLocation.IsMailingLocation.ToString(), familyAddress.IsMailing.ToString() );
                        groupLocation.IsMailingLocation = familyAddress.IsMailing;

                        History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Is Map Location",
                            groupLocation.IsMappedLocation.ToString(), familyAddress.IsLocation.ToString() );
                        groupLocation.IsMappedLocation = familyAddress.IsLocation;

                        if ( updatedAddress != null )
                        {
                            History.EvaluateChange( familyChanges, familyAddress.LocationTypeName + " Location",
                                groupLocation.Location != null ? groupLocation.Location.ToString() : "", updatedAddress.ToString() );
                            groupLocation.Location = updatedAddress;
                        }

                        rockContext.SaveChanges();

                        // Add the same locations to any new families created by removing an existing family member
                        if ( newFamilies.Any() )
                        {
                            //reload grouplocation for access to child properties
                            groupLocation = groupLocationService.Get( groupLocation.Id );
                            foreach ( var newFamily in newFamilies )
                            {
                                var newFamilyLocation = new GroupLocation();
                                newFamilyLocation.GroupId = newFamily.Id;
                                newFamilyLocation.LocationId = groupLocation.LocationId;
                                newFamilyLocation.GroupLocationTypeValueId = groupLocation.GroupLocationTypeValueId;
                                newFamilyLocation.IsMailingLocation = groupLocation.IsMailingLocation;
                                newFamilyLocation.IsMappedLocation = groupLocation.IsMappedLocation;
                                groupLocationService.Add( newFamilyLocation );
                            }

                            rockContext.SaveChanges();
                        }
                    }

                    foreach ( var fm in _family.Members )
                    {
                        HistoryService.SaveChanges( rockContext, typeof( Person ), Rock.SystemGuid.Category.HISTORY_PERSON_FAMILY_CHANGES.AsGuid(),
                            fm.PersonId, familyChanges, _family.Name, typeof( Group ), _family.Id );
                    }

                    _family = familyService.Get( _family.Id );
                    if ( _family.Members.Any( m => m.PersonId == Person.Id ) )
                    {
                        Response.Redirect( string.Format( "~/Person/{0}", Person.Id ), false );
                    }
                    else
                    {
                        var fm = _family.Members
                            .Where( m =>
                                m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) &&
                                m.Person.Gender == Gender.Male )
                            .OrderByDescending( m => m.Person.Age )
                            .FirstOrDefault();
                        if ( fm == null )
                        {
                            fm = _family.Members
                                .Where( m =>
                                    m.GroupRole.Guid.Equals( new Guid( Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT ) ) )
                                .OrderByDescending( m => m.Person.Age )
                                .FirstOrDefault();
                        }
                        if ( fm == null )
                        {
                            fm = _family.Members
                                .OrderByDescending( m => m.Person.Age )
                                .FirstOrDefault();
                        }
                        if ( fm != null )
                        {
                            Response.Redirect( string.Format( "~/Person/{0}", fm.PersonId ), false );
                        }
                        else
                        {
                            Response.Redirect( "~", false );
                        }
                    }

                } );
            }
        }
示例#41
0
        /// <summary>
        /// Maps the person.
        /// </summary>
        /// <param name="tableData">The table data.</param>
        /// <param name="totalRows">The total rows.</param>
        public void MapPerson(IQueryable <Row> tableData, long totalRows = 0)
        {
            var lookupContext = new RockContext();

            // Marital statuses: Married, Single, Separated, etc
            var maritalStatusTypes = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS), lookupContext).DefinedValues;

            // Connection statuses: Member, Visitor, Attendee, etc
            var connectionStatusTypes = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS), lookupContext).DefinedValues;

            // Title type: Mr., Mrs., Dr., etc
            var titleTypes = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.PERSON_TITLE), lookupContext).DefinedValues;

            // Suffix type: Sr., Jr., II, etc
            var suffixTypes = DefinedTypeCache.Get(new Guid(Rock.SystemGuid.DefinedType.PERSON_SUFFIX), lookupContext).DefinedValues;

            // Look up additional Person attributes (existing)
            var personAttributes = new AttributeService(lookupContext).GetByEntityTypeId(PersonEntityTypeId).AsNoTracking().ToList();

            // F1 attributes: IndividualId, HouseholdId
            // Core attributes: PreviousChurch, Membership Date, First Visit, Allergy, Employer, Position, School
            var previousChurchAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("PreviousChurch", StringComparison.OrdinalIgnoreCase));
            var membershipDateAttribute = personAttributes.FirstOrDefault(a => a.Key.Equals("MembershipDate", StringComparison.OrdinalIgnoreCase));
            var firstVisitAttribute     = personAttributes.FirstOrDefault(a => a.Key.Equals("FirstVisit", StringComparison.OrdinalIgnoreCase));
            var allergyNoteAttribute    = personAttributes.FirstOrDefault(a => a.Key.Equals("Allergy", StringComparison.OrdinalIgnoreCase));
            var employerAttribute       = personAttributes.FirstOrDefault(a => a.Key.Equals("Employer", StringComparison.OrdinalIgnoreCase));
            var positionAttribute       = personAttributes.FirstOrDefault(a => a.Key.Equals("Position", StringComparison.OrdinalIgnoreCase));
            var schoolAttribute         = personAttributes.FirstOrDefault(a => a.Key.Equals("School", StringComparison.OrdinalIgnoreCase));
            var envelopeNumberAttribute = personAttributes.FirstOrDefault(a => a.Guid.ToString().Equals(Rock.SystemGuid.Attribute.PERSON_GIVING_ENVELOPE_NUMBER, StringComparison.OrdinalIgnoreCase));
            var barcodeAttribute        = AddEntityAttribute(lookupContext, PersonEntityTypeId, string.Empty, string.Empty, string.Empty, string.Empty,
                                                             "Personal Barcode", "PersonalBarcode", TextFieldTypeId, true);

            var familyList          = new List <Group>();
            var visitorList         = new List <Group>();
            var previousNamesList   = new Dictionary <Guid, string>();
            var householdCampusList = new List <string>();

            if (totalRows == 0)
            {
                totalRows = tableData.Count();
            }

            var importedPeopleCount = ImportedPeople.Count;
            var completedItems      = importedPeopleCount;
            var percentage          = (totalRows - 1) / 100 + 1;

            ReportProgress(0, $"Verifying person import ({totalRows:N0} found, {importedPeopleCount:N0} already exist).");

            foreach (var groupedRows in tableData.GroupBy(r => r["Household_ID"] as int?))
            {
                var familyGroup = new Group();
                householdCampusList.Clear();

                foreach (var row in groupedRows.Where(r => r != null))
                {
                    var familyRoleId  = FamilyRole.Adult;
                    var currentCampus = string.Empty;
                    var individualId  = row["Individual_ID"] as int?;
                    var householdId   = row["Household_ID"] as int?;
                    var personKeys    = GetPersonKeys(individualId, householdId);
                    if (personKeys == null)
                    {
                        var person = new Person();
                        person.FirstName  = row["First_Name"] as string;
                        person.MiddleName = row["Middle_Name"] as string;
                        person.NickName   = row["Goes_By"] as string ?? person.FirstName;
                        person.LastName   = row["Last_Name"] as string;
                        person.IsDeceased = false;

                        var DOB = row["Date_Of_Birth"] as DateTime?;
                        if (DOB.HasValue)
                        {
                            var birthDate = ( DateTime )DOB;
                            person.BirthDay   = birthDate.Day;
                            person.BirthMonth = birthDate.Month;
                            person.BirthYear  = birthDate.Year;
                        }

                        person.CreatedByPersonAliasId = ImportPersonAliasId;
                        person.RecordTypeValueId      = PersonRecordTypeId;
                        person.ForeignKey             = individualId.ToString();
                        person.ForeignId = individualId;

                        var gender = row["Gender"] as string;
                        if (!string.IsNullOrWhiteSpace(gender))
                        {
                            person.Gender = ( Gender )Enum.Parse(typeof(Gender), gender);
                        }

                        var prefix = row["Prefix"] as string;
                        if (!string.IsNullOrWhiteSpace(prefix))
                        {
                            prefix = prefix.RemoveSpecialCharacters();
                            person.TitleValueId = titleTypes.Where(s => prefix.Equals(s.Value.RemoveSpecialCharacters(), StringComparison.OrdinalIgnoreCase))
                                                  .Select(s => ( int? )s.Id).FirstOrDefault();

                            if (!person.TitleValueId.HasValue)
                            {
                                var newTitle = AddDefinedValue(lookupContext, Rock.SystemGuid.DefinedType.PERSON_TITLE, prefix);
                                if (newTitle != null)
                                {
                                    titleTypes.Add(newTitle);
                                    person.TitleValueId = newTitle.Id;
                                }
                            }
                        }

                        var suffix = row["Suffix"] as string;
                        if (!string.IsNullOrWhiteSpace(suffix))
                        {
                            suffix = suffix.RemoveSpecialCharacters();
                            person.SuffixValueId = suffixTypes.Where(s => suffix.Equals(s.Value.RemoveSpecialCharacters(), StringComparison.OrdinalIgnoreCase))
                                                   .Select(s => ( int? )s.Id).FirstOrDefault();

                            if (!person.SuffixValueId.HasValue)
                            {
                                var newSuffix = AddDefinedValue(lookupContext, Rock.SystemGuid.DefinedType.PERSON_SUFFIX, suffix);
                                if (newSuffix != null)
                                {
                                    suffixTypes.Add(newSuffix);
                                    person.SuffixValueId = newSuffix.Id;
                                }
                            }
                        }

                        var maritalStatus = row["Marital_Status"] as string;
                        if (!string.IsNullOrWhiteSpace(maritalStatus))
                        {
                            maritalStatus = maritalStatus.RemoveSpecialCharacters();
                            person.MaritalStatusValueId = maritalStatusTypes.Where(s => maritalStatus.Equals(s.Value.RemoveSpecialCharacters(), StringComparison.OrdinalIgnoreCase))
                                                          .Select(dv => ( int? )dv.Id).FirstOrDefault();

                            if (!person.MaritalStatusValueId.HasValue)
                            {
                                var newMaritalStatus = AddDefinedValue(lookupContext, Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS, maritalStatus);
                                if (newMaritalStatus != null)
                                {
                                    maritalStatusTypes.Add(newMaritalStatus);
                                    person.MaritalStatusValueId = newMaritalStatus.Id;
                                }
                            }
                        }
                        else
                        {
                            person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value.Equals("Unknown", StringComparison.OrdinalIgnoreCase))
                                                          .Select(dv => ( int? )dv.Id).FirstOrDefault();
                        }

                        var familyRole = row["Household_Position"] as string;
                        if (!string.IsNullOrWhiteSpace(familyRole))
                        {
                            if (familyRole.Equals("Visitor", StringComparison.OrdinalIgnoreCase))
                            {
                                familyRoleId = FamilyRole.Visitor;
                            }
                            else if (familyRole.Equals("Child", StringComparison.OrdinalIgnoreCase) || person.Age < 18)
                            {
                                familyRoleId = FamilyRole.Child;
                            }
                        }

                        var memberStatus = row["Status_Name"] as string;
                        if (!string.IsNullOrWhiteSpace(memberStatus))
                        {
                            memberStatus = memberStatus.Trim();
                            if (memberStatus.Equals("Member", StringComparison.OrdinalIgnoreCase))
                            {
                                person.ConnectionStatusValueId = MemberConnectionStatusId;
                                person.RecordStatusValueId     = ActivePersonRecordStatusId;
                            }
                            else if (memberStatus.Equals("Visitor", StringComparison.OrdinalIgnoreCase))
                            {
                                person.ConnectionStatusValueId = VisitorConnectionStatusId;
                                person.RecordStatusValueId     = ActivePersonRecordStatusId;
                            }
                            else if (memberStatus.Equals("Deceased", StringComparison.OrdinalIgnoreCase))
                            {
                                person.IsDeceased = true;
                                person.RecordStatusReasonValueId = DeceasedPersonRecordReasonId;
                                person.RecordStatusValueId       = InactivePersonRecordStatusId;
                            }
                            else if (memberStatus.Equals("Dropped", StringComparison.OrdinalIgnoreCase) || memberStatus.StartsWith("Inactive", StringComparison.OrdinalIgnoreCase))
                            {
                                person.RecordStatusReasonValueId = NoActivityPersonRecordReasonId;
                                person.RecordStatusValueId       = InactivePersonRecordStatusId;
                            }
                            else
                            {
                                // create user-defined connection type if it doesn't exist
                                person.RecordStatusValueId     = ActivePersonRecordStatusId;
                                person.ConnectionStatusValueId = connectionStatusTypes.Where(dv => dv.Value.Equals(memberStatus, StringComparison.OrdinalIgnoreCase))
                                                                 .Select(dv => ( int? )dv.Id).FirstOrDefault();

                                if (!person.ConnectionStatusValueId.HasValue)
                                {
                                    var newConnectionStatus = AddDefinedValue(lookupContext, Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS, memberStatus);
                                    if (newConnectionStatus != null)
                                    {
                                        connectionStatusTypes.Add(newConnectionStatus);
                                        person.ConnectionStatusValueId = newConnectionStatus.Id;
                                    }
                                }
                            }
                        }
                        else
                        {
                            person.ConnectionStatusValueId = VisitorConnectionStatusId;
                            person.RecordStatusValueId     = ActivePersonRecordStatusId;
                        }

                        var campus = row["SubStatus_Name"] as string;
                        if (!string.IsNullOrWhiteSpace(campus))
                        {
                            currentCampus = campus;
                        }

                        var status_comment = row["Status_Comment"] as string;
                        if (!string.IsNullOrWhiteSpace(status_comment))
                        {
                            person.SystemNote = status_comment;
                        }

                        var previousName = row["Former_Name"] as string;
                        if (!string.IsNullOrWhiteSpace(previousName))
                        {
                            previousNamesList.Add(person.Guid, previousName);
                        }

                        // set a flag to keep visitors from receiving household info
                        person.ReviewReasonNote = familyRoleId.ToString();

                        // Map F1 attributes
                        person.Attributes      = new Dictionary <string, AttributeCache>();
                        person.AttributeValues = new Dictionary <string, AttributeValueCache>();

                        // IndividualId already defined in scope
                        AddEntityAttributeValue(lookupContext, IndividualIdAttribute, person, individualId.ToString());

                        // HouseholdId already defined in scope
                        AddEntityAttributeValue(lookupContext, HouseholdIdAttribute, person, householdId.ToString());

                        var previousChurch = row["Former_Church"] as string;
                        if (!string.IsNullOrWhiteSpace(previousChurch))
                        {
                            AddEntityAttributeValue(lookupContext, previousChurchAttribute, person, previousChurch);
                        }

                        var employer = row["Employer"] as string;
                        if (!string.IsNullOrWhiteSpace(employer))
                        {
                            AddEntityAttributeValue(lookupContext, employerAttribute, person, employer);
                        }

                        var position = row["Occupation_Name"] as string ?? row["Occupation_Description"] as string;
                        if (!string.IsNullOrWhiteSpace(position))
                        {
                            AddEntityAttributeValue(lookupContext, positionAttribute, person, position);
                        }

                        var school = row["School_Name"] as string;
                        if (!string.IsNullOrWhiteSpace(school))
                        {
                            AddEntityAttributeValue(lookupContext, schoolAttribute, person, school);
                        }

                        var firstVisit = row["First_Record"] as DateTime?;
                        if (firstVisit.HasValue)
                        {
                            person.CreatedDateTime = firstVisit;
                            AddEntityAttributeValue(lookupContext, firstVisitAttribute, person, firstVisit.Value.ToString("yyyy-MM-dd"));
                        }

                        // Only import membership date if they are a member
                        var membershipDate = row["Status_Date"] as DateTime?;
                        if (membershipDate.HasValue && memberStatus.Contains("member"))
                        {
                            AddEntityAttributeValue(lookupContext, membershipDateAttribute, person, membershipDate.Value.ToString("yyyy-MM-dd"));
                        }

                        var checkinNote = row["Default_tag_comment"] as string;
                        if (!string.IsNullOrWhiteSpace(checkinNote))
                        {
                            AddEntityAttributeValue(lookupContext, allergyNoteAttribute, person, checkinNote);
                        }

                        var barcode = row["Bar_Code"] as string;
                        if (!string.IsNullOrWhiteSpace(barcode))
                        {
                            AddEntityAttributeValue(lookupContext, barcodeAttribute, person, barcode);
                        }

                        var envelopeNumber = row["Member_Env_Code"] as string;
                        if (!string.IsNullOrWhiteSpace(envelopeNumber))
                        {
                            AddEntityAttributeValue(lookupContext, envelopeNumberAttribute, person, envelopeNumber);
                        }

                        var groupMember = new GroupMember
                        {
                            Person            = person,
                            GroupRoleId       = familyRoleId != FamilyRole.Child ? FamilyAdultRoleId : FamilyChildRoleId,
                            GroupMemberStatus = GroupMemberStatus.Active
                        };

                        if (familyRoleId != FamilyRole.Visitor)
                        {
                            householdCampusList.Add(currentCampus);
                            familyGroup.Members.Add(groupMember);
                            familyGroup.ForeignKey = householdId.ToString();
                            familyGroup.ForeignId  = householdId;
                            familyGroup.Name       = row["Household_Name"] as string;
                        }
                        else
                        {
                            var visitorGroup = new Group
                            {
                                GroupTypeId = FamilyGroupTypeId,
                                ForeignKey  = householdId.ToString(),
                                ForeignId   = householdId,
                                Name        = person.LastName + " Family",
                                CampusId    = GetCampusId(currentCampus)
                            };
                            visitorGroup.Members.Add(groupMember);
                            familyList.Add(visitorGroup);
                            completedItems += visitorGroup.Members.Count;

                            visitorList.Add(visitorGroup);
                        }
                    }
                }

                if (familyGroup.Members.Any())
                {
                    // Moved group name set to read Household Name due to grandparents throwing off calculated name
                    // familyGroup.Name = familyGroup.Members.OrderByDescending( p => p.Person.Age ).FirstOrDefault().Person.LastName + " Family";
                    familyGroup.GroupTypeId = FamilyGroupTypeId;

                    var primaryCampusTag = householdCampusList.GroupBy(c => c).OrderByDescending(c => c.Count())
                                           .Select(c => c.Key).FirstOrDefault();
                    if (!string.IsNullOrWhiteSpace(primaryCampusTag))
                    {
                        familyGroup.CampusId = GetCampusId(primaryCampusTag);
                    }

                    familyList.Add(familyGroup);
                    completedItems += familyGroup.Members.Count;
                    // average family has 2.3 members, so fudge the math a little
                    if (completedItems % percentage < 2)
                    {
                        var percentComplete = completedItems / percentage;
                        ReportProgress(percentComplete, $"{completedItems - importedPeopleCount:N0} people imported ({percentComplete}% complete).");
                    }

                    if (completedItems % ReportingNumber < 1)
                    {
                        SavePeople(familyList, visitorList, previousNamesList);

                        familyList.Clear();
                        visitorList.Clear();
                        previousNamesList.Clear();
                        ReportPartialProgress();
                    }
                }
            }

            // Save any remaining families in the batch
            if (familyList.Any())
            {
                SavePeople(familyList, visitorList, previousNamesList);
            }

            ReportProgress(100, $"Finished person import: {completedItems - importedPeopleCount:N0} people imported.");
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (lopAddress.Location == null ||
                string.IsNullOrWhiteSpace(lopAddress.Location.Street1) ||
                string.IsNullOrWhiteSpace(lopAddress.Location.PostalCode))
            {
                nbValidation.Visible = true;
                ScriptManager.RegisterStartupScript(Page, this.GetType(), "ScrollPage", "setTimeout(function(){window.scroll(0,0);},200)", true);
                return;
            }
            else
            {
                nbValidation.Visible = false;
            }


            if (_group == null)
            {
                ShowMessage("There was an issue with the viewstate. Please reload and try again. If the problem perssits contact an administrator.", "Error", "panel panel-danger");
                return;
            }

            GroupService groupService = new GroupService(_rockContext);
            //Add basic information

            Group group;

            if (_group.Id == 0)
            {
                group = new Group()
                {
                    GroupTypeId = _groupType.Id
                };
                var destinationGroup = groupService.Get(GetAttributeValue("DestinationGroup").AsGuid());
                if (destinationGroup != null)
                {
                    group.ParentGroupId = destinationGroup.Id;
                }

                var parentMapping = GetAttributeValue("CampusGroupMap").ToKeyValuePairList();
                foreach (var pair in parentMapping)
                {
                    if (pair.Key.AsInteger() == cpCampus.SelectedValueAsId())
                    {
                        group.ParentGroupId = (( string )pair.Value).AsInteger();
                    }
                }

                var zip = "No Zip";
                if (lopAddress.Location != null && !string.IsNullOrWhiteSpace(lopAddress.Location.PostalCode))
                {
                    zip = lopAddress.Location.PostalCode;
                }
                group.Name = string.Format("{0} - {1}", tbName.Text, zip);
                groupService.Add(group);
                group.CreatedByPersonAliasId = _person.PrimaryAliasId;
                group.IsActive = true;
            }
            else
            {
                group          = groupService.Get(_group.Id);
                group.IsActive = true;
            }

            group.CampusId    = cpCampus.SelectedValueAsId();
            group.Description = tbDescription.Text;


            //Set location
            if (lopAddress.Location != null && lopAddress.Location.Id != 0)
            {
                if (group.GroupLocations != null && !group.GroupLocations.Select(gl => gl.LocationId).Contains(lopAddress.Location.Id))
                {
                    // Disassociate the old address(es)
                    GroupLocationService groupLocationService = new GroupLocationService(_rockContext);
                    var meetingLocationDv = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_MEETING_LOCATION);
                    var homeLocationDv    = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME);

                    groupLocationService.DeleteRange(group.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == meetingLocationDv.Id || gl.GroupLocationTypeValueId == homeLocationDv.Id || gl.GroupLocationTypeValueId == null));
                    group.GroupLocations.Add(new GroupLocation()
                    {
                        LocationId = lopAddress.Location.Id, GroupLocationTypeValueId = meetingLocationDv.Id
                    });
                }
            }

            //Set Schedule
            if (_groupType.AllowedScheduleTypes != ScheduleType.None)
            {
                switch (rblSchedule.SelectedValueAsEnum <ScheduleType>())
                {
                case ScheduleType.None:
                    group.ScheduleId = null;
                    break;

                case ScheduleType.Weekly:
                    var weeklySchedule = new Schedule()
                    {
                        WeeklyDayOfWeek = dowWeekly.SelectedDayOfWeek, WeeklyTimeOfDay = timeWeekly.SelectedTime
                    };
                    group.Schedule = weeklySchedule;
                    break;

                case ScheduleType.Custom:
                    var customSchedule = new Schedule()
                    {
                        iCalendarContent = sbSchedule.iCalendarContent
                    };
                    group.Schedule = customSchedule;
                    break;

                case ScheduleType.Named:
                    if (spSchedule.SelectedValue.AsInteger() != 0)
                    {
                        group.ScheduleId = spSchedule.SelectedValue.AsInteger();
                    }
                    break;

                default:
                    break;
                }
            }

            if (group.Members != null && group.Members.Any())
            {
                foreach (var member in group.Members.Where(gm => gm.PersonId != _person.Id))
                {
                    member.GroupMemberStatus = GroupMemberStatus.Inactive;
                }

                foreach (int groupMemberId in gMembers.SelectedKeys)
                {
                    var groupMember = group.Members.Where(m => m.Id == groupMemberId).FirstOrDefault();
                    if (groupMember != null)
                    {
                        groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                    }
                }
            }
            else
            {
                var groupRoleId = new GroupTypeRoleService(_rockContext).Get(GetAttributeValue("GroupRole").AsGuid()).Id;
                group.Members.Add(new GroupMember()
                {
                    PersonId = _person.Id, GroupRoleId = groupRoleId
                });
            }

            //Save attributes
            _rockContext.SaveChanges();
            group.LoadAttributes();
            Rock.Attribute.Helper.GetEditValues(phAttributes, group);
            var attributeGuid        = GetAttributeValue("MultiSelectAttribute");
            var multiselectAttribute = new AttributeService(_rockContext).Get(attributeGuid.AsGuid());

            if (multiselectAttribute != null)
            {
                var attributeValue = group.GetAttributeValue(multiselectAttribute.Key)
                                     .Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                     .ToList();
                var newAttributeText = GetAttributeValue("AttributeText");
                if (!attributeValue.Contains(newAttributeText))
                {
                    attributeValue.Add(newAttributeText);
                }
                group.SetAttributeValue(multiselectAttribute.Key, string.Join(",", attributeValue));
            }
            group.SaveAttributeValues();

            //Update cache
            var availableGroupIds = (List <int>)GetCacheItem(GetAttributeValue("DestinationGroup"));

            if (availableGroupIds != null)
            {
                availableGroupIds.Add(group.Id);
                AddCacheItem(GetAttributeValue("DestinationGroup"), availableGroupIds);
            }

            var          workflowTypeService = new WorkflowTypeService(_rockContext);
            WorkflowType workflowType        = null;
            Guid?        workflowTypeGuid    = GetAttributeValue("Workflow").AsGuidOrNull();

            if (workflowTypeGuid.HasValue)
            {
                workflowType = workflowTypeService.Get(workflowTypeGuid.Value);
            }
            GroupMember currentGroupMember = group.Members.Where(gm => gm.PersonId == _person.Id).FirstOrDefault();

            if (currentGroupMember != null && workflowType != null && (workflowType.IsActive ?? true))
            {
                try
                {
                    List <string> workflowErrors;
                    var           workflow = Workflow.Activate(workflowType, _person.FullName);

                    if (workflow.AttributeValues.ContainsKey("Group"))
                    {
                        if (group != null)
                        {
                            workflow.AttributeValues["Group"].Value = group.Guid.ToString();
                        }
                    }

                    if (workflow.AttributeValues.ContainsKey("Person"))
                    {
                        if (_person != null)
                        {
                            workflow.AttributeValues["Person"].Value = _person.PrimaryAlias.Guid.ToString();
                        }
                    }
                    new WorkflowService(_rockContext).Process(workflow, currentGroupMember, out workflowErrors);
                }
                catch (Exception ex)
                {
                    ExceptionLogService.LogException(ex, this.Context);
                }
            }
            ShowMessage(GetAttributeValue("SuccessText"), "Thank you!", "panel panel-success");
        }
示例#43
0
        /// <summary>
        /// Loads the individual data.
        /// </summary>
        /// <param name="csvData">The CSV data.</param>
        private int LoadIndividuals(CsvDataModel csvData)
        {
            var lookupContext        = new RockContext();
            var groupTypeRoleService = new GroupTypeRoleService(lookupContext);
            var groupMemberService   = new GroupMemberService(lookupContext);

            // Marital statuses: Married, Single, Separated, etc
            var maritalStatusTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_MARITAL_STATUS), lookupContext).DefinedValues;

            // Connection statuses: Member, Visitor, Attendee, etc
            var connectionStatusTypes      = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_CONNECTION_STATUS), lookupContext).DefinedValues;
            int memberConnectionStatusId   = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_MEMBER)).Id;
            int visitorConnectionStatusId  = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_VISITOR)).Id;
            int attendeeConnectionStatusId = connectionStatusTypes.FirstOrDefault(dv => dv.Guid == new Guid(Rock.SystemGuid.DefinedValue.PERSON_CONNECTION_STATUS_ATTENDEE)).Id;

            // Suffix type: Dr., Jr., II, etc
            var suffixTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_SUFFIX), lookupContext).DefinedValues;

            // Title type: Mr., Mrs. Dr., etc
            var titleTypes = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_TITLE), lookupContext).DefinedValues;

            // Record statuses: Active, Inactive, Pending
            int?recordStatusActiveId   = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_ACTIVE), lookupContext).Id;
            int?recordStatusInactiveId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_INACTIVE), lookupContext).Id;
            int?recordStatusPendingId  = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_PENDING), lookupContext).Id;

            // Deceased record status reason (others available: No Activity, Moved, etc)
            var recordStatusDeceasedId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_STATUS_REASON_DECEASED)).Id;

            // Record type: Person
            int?personRecordTypeId = DefinedValueCache.Read(new Guid(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON), lookupContext).Id;

            // Group roles: Owner, Adult, Child, others
            GroupTypeRole ownerRole   = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_KNOWN_RELATIONSHIPS_OWNER));
            int           adultRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT)).Id;
            int           childRoleId = groupTypeRoleService.Get(new Guid(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD)).Id;

            // Phone types: Home, Work, Mobile
            var numberTypeValues = DefinedTypeCache.Read(new Guid(Rock.SystemGuid.DefinedType.PERSON_PHONE_TYPE), lookupContext).DefinedValues;

            // Timeline note type id
            var noteTimelineTypeId = new NoteTypeService(lookupContext).Get(new Guid("7E53487C-D650-4D85-97E2-350EB8332763")).Id;

            // School defined type
            var schoolDefinedType = DefinedTypeCache.Read(new Guid("576FF1E2-6225-4565-A16D-230E26167A3D"));

            // Look up existing Person attributes
            var personAttributes = new AttributeService(lookupContext).GetByEntityTypeId(PersonEntityTypeId).ToList();
            var schoolAttribute  = AttributeCache.Read(personAttributes.FirstOrDefault(a => a.Key == "School"));

            // Text field type id
            int textFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.TEXT), lookupContext).Id;
            int dateFieldTypeId = FieldTypeCache.Read(new Guid(Rock.SystemGuid.FieldType.DATE), lookupContext).Id;

            // Attribute entity type id
            int attributeEntityTypeId = EntityTypeCache.Read("Rock.Model.Attribute").Id;

            // Visit info category
            var visitInfoCategory = new CategoryService(lookupContext).GetByEntityTypeId(attributeEntityTypeId)
                                    .Where(c => c.Name == "Visit Information").FirstOrDefault();

            // Look for custom attributes in the Individual file
            var allFields = csvData.TableNodes.FirstOrDefault().Columns.Select((node, index) => new { node = node, index = index }).ToList();
            Dictionary <int, string> customAttributes = allFields
                                                        .Where(f => f.index > SecurityNote)
                                                        .ToDictionary(f => f.index, f => f.node.Name.RemoveWhitespace());

            // Add any attributes if they don't already exist
            if (customAttributes.Any())
            {
                var newAttributes = new List <Rock.Model.Attribute>();
                foreach (var newAttributePair in customAttributes.Where(ca => !personAttributes.Any(a => a.Key == ca.Value)))
                {
                    var newAttribute = new Rock.Model.Attribute();
                    newAttribute.Name        = newAttributePair.Value;
                    newAttribute.Key         = newAttributePair.Value.RemoveWhitespace();
                    newAttribute.Description = newAttributePair.Value + " created by CSV import";
                    newAttribute.EntityTypeQualifierValue  = string.Empty;
                    newAttribute.EntityTypeQualifierColumn = string.Empty;
                    newAttribute.EntityTypeId = PersonEntityTypeId;
                    newAttribute.FieldTypeId  = textFieldTypeId;
                    newAttribute.DefaultValue = string.Empty;
                    newAttribute.IsMultiValue = false;
                    newAttribute.IsGridColumn = false;
                    newAttribute.IsRequired   = false;
                    newAttribute.Order        = 0;
                    newAttributes.Add(newAttribute);
                }

                lookupContext.Attributes.AddRange(newAttributes);
                lookupContext.SaveChanges(true);
                personAttributes.AddRange(newAttributes);
            }

            // Set the supported date formats
            var dateFormats = new[] { "yyyy-MM-dd", "MM/dd/yyyy", "MM/dd/yy" };

            var currentFamilyGroup = new Group();
            var newFamilyList      = new List <Group>();
            var newVisitorList     = new List <Group>();
            var newNoteList        = new List <Note>();
            var importDate         = DateTime.Now;

            int completed   = 0;
            int newFamilies = 0;

            ReportProgress(0, string.Format("Starting Individual import ({0:N0} already exist).", ImportedPeople.Count(p => p.Members.Any(m => m.Person.ForeignId != null))));

            string[] row;
            // Uses a look-ahead enumerator: this call will move to the next record immediately
            while ((row = csvData.Database.FirstOrDefault()) != null)
            {
                int  groupRoleId          = adultRoleId;
                bool isFamilyRelationship = true;

                string rowFamilyId   = row[FamilyId];
                string rowPersonId   = row[PersonId];
                string rowFamilyName = row[FamilyName];

                // Check that this person isn't already in our data
                var personExists = ImportedPeople.Any(p => p.Members.Any(m => m.Person.ForeignId == rowPersonId));
                if (!personExists)
                {
                    #region person create

                    var person = new Person();
                    person.ForeignId              = rowPersonId;
                    person.SystemNote             = string.Format("Imported via Excavator on {0}", importDate.ToString());
                    person.RecordTypeValueId      = personRecordTypeId;
                    person.CreatedByPersonAliasId = ImportPersonAlias.Id;
                    string firstName = row[FirstName];
                    string nickName  = row[NickName];
                    person.FirstName  = firstName;
                    person.NickName   = string.IsNullOrWhiteSpace(nickName) ? firstName : nickName;
                    person.MiddleName = row[MiddleName];
                    person.LastName   = row[LastName];

                    DateTime createdDateValue;
                    if (DateTime.TryParseExact(row[CreatedDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out createdDateValue))
                    {
                        person.CreatedDateTime  = createdDateValue;
                        person.ModifiedDateTime = importDate;
                    }
                    else
                    {
                        person.CreatedDateTime  = importDate;
                        person.ModifiedDateTime = importDate;
                    }

                    DateTime birthDate;
                    if (DateTime.TryParseExact(row[DateOfBirth], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out birthDate))
                    {
                        person.BirthDate = birthDate;
                    }

                    DateTime graduationDate;
                    if (DateTime.TryParseExact(row[GraduationDate], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out graduationDate))
                    {
                        person.GraduationDate = graduationDate;
                    }

                    DateTime anniversary;
                    if (DateTime.TryParseExact(row[Anniversary], dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out anniversary))
                    {
                        person.AnniversaryDate = anniversary;
                    }

                    string gender = row[Gender];
                    if (gender != null)
                    {
                        switch (gender.Trim().ToLower())
                        {
                        case "m":
                        case "male":
                            person.Gender = Rock.Model.Gender.Male;
                            break;

                        case "f":
                        case "female":
                            person.Gender = Rock.Model.Gender.Female;
                            break;

                        default:
                            person.Gender = Rock.Model.Gender.Unknown;
                            break;
                        }
                    }

                    string prefix = row[Prefix];
                    if (!string.IsNullOrWhiteSpace(prefix))
                    {
                        prefix = prefix.RemoveSpecialCharacters().Trim();
                        person.TitleValueId = titleTypes.Where(s => prefix == s.Value.RemoveSpecialCharacters())
                                              .Select(s => (int?)s.Id).FirstOrDefault();
                    }

                    string suffix = row[Suffix];
                    if (!string.IsNullOrWhiteSpace(suffix))
                    {
                        suffix = suffix.RemoveSpecialCharacters().Trim();
                        person.SuffixValueId = suffixTypes.Where(s => suffix == s.Value.RemoveSpecialCharacters())
                                               .Select(s => (int?)s.Id).FirstOrDefault();
                    }

                    string maritalStatus = row[MaritalStatus];
                    if (!string.IsNullOrWhiteSpace(maritalStatus))
                    {
                        person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value == maritalStatus)
                                                      .Select(dv => (int?)dv.Id).FirstOrDefault();
                    }
                    else
                    {
                        person.MaritalStatusValueId = maritalStatusTypes.Where(dv => dv.Value == "Unknown")
                                                      .Select(dv => (int?)dv.Id).FirstOrDefault();
                    }

                    string familyRole = row[FamilyRole];
                    if (!string.IsNullOrWhiteSpace(familyRole))
                    {
                        if (familyRole == "Visitor")
                        {
                            isFamilyRelationship = false;
                        }

                        if (familyRole == "Child" || person.Age < 18)
                        {
                            groupRoleId = childRoleId;
                        }
                    }

                    string connectionStatus = row[ConnectionStatus];
                    if (!string.IsNullOrWhiteSpace(connectionStatus))
                    {
                        if (connectionStatus == "Member")
                        {
                            person.ConnectionStatusValueId = memberConnectionStatusId;
                        }
                        else if (connectionStatus == "Visitor")
                        {
                            person.ConnectionStatusValueId = visitorConnectionStatusId;
                        }
                        else
                        {
                            // look for user-defined connection type or default to Attendee
                            var customConnectionType = connectionStatusTypes.Where(dv => dv.Value == connectionStatus)
                                                       .Select(dv => (int?)dv.Id).FirstOrDefault();

                            person.ConnectionStatusValueId = customConnectionType ?? attendeeConnectionStatusId;
                            person.RecordStatusValueId     = recordStatusActiveId;
                        }
                    }

                    string recordStatus = row[RecordStatus];
                    if (!string.IsNullOrWhiteSpace(recordStatus))
                    {
                        switch (recordStatus.Trim().ToLower())
                        {
                        case "active":
                            person.RecordStatusValueId = recordStatusActiveId;
                            break;

                        case "inactive":
                            person.RecordStatusValueId = recordStatusInactiveId;
                            break;

                        default:
                            person.RecordStatusValueId = recordStatusPendingId;
                            break;
                        }
                    }

                    string isDeceasedValue = row[IsDeceased];
                    if (!string.IsNullOrWhiteSpace(isDeceasedValue))
                    {
                        switch (isDeceasedValue.Trim().ToLower())
                        {
                        case "y":
                        case "yes":
                            person.IsDeceased = true;
                            person.RecordStatusReasonValueId = recordStatusDeceasedId;
                            person.RecordStatusValueId       = recordStatusInactiveId;
                            break;

                        default:
                            person.IsDeceased = false;
                            break;
                        }
                    }

                    var personNumbers = new Dictionary <string, string>();
                    personNumbers.Add("Home", row[HomePhone]);
                    personNumbers.Add("Mobile", row[MobilePhone]);
                    personNumbers.Add("Work", row[WorkPhone]);
                    string smsAllowed = row[AllowSMS];

                    foreach (var numberPair in personNumbers.Where(n => !string.IsNullOrWhiteSpace(n.Value)))
                    {
                        var extension        = string.Empty;
                        var countryCode      = Rock.Model.PhoneNumber.DefaultCountryCode();
                        var normalizedNumber = string.Empty;
                        var countryIndex     = numberPair.Value.IndexOf('+');
                        int extensionIndex   = numberPair.Value.LastIndexOf('x') > 0 ? numberPair.Value.LastIndexOf('x') : numberPair.Value.Length;
                        if (countryIndex >= 0)
                        {
                            countryCode      = numberPair.Value.Substring(countryIndex, countryIndex + 3).AsNumeric();
                            normalizedNumber = numberPair.Value.Substring(countryIndex + 3, extensionIndex - 3).AsNumeric();
                            extension        = numberPair.Value.Substring(extensionIndex);
                        }
                        else if (extensionIndex > 0)
                        {
                            normalizedNumber = numberPair.Value.Substring(0, extensionIndex).AsNumeric();
                            extension        = numberPair.Value.Substring(extensionIndex).AsNumeric();
                        }
                        else
                        {
                            normalizedNumber = numberPair.Value.AsNumeric();
                        }

                        if (!string.IsNullOrWhiteSpace(normalizedNumber))
                        {
                            var currentNumber = new PhoneNumber();
                            currentNumber.CountryCode            = countryCode;
                            currentNumber.CreatedByPersonAliasId = ImportPersonAlias.Id;
                            currentNumber.Extension         = extension.Left(20);
                            currentNumber.Number            = normalizedNumber.Left(20);
                            currentNumber.NumberTypeValueId = numberTypeValues.Where(v => v.Value.Equals(numberPair.Key))
                                                              .Select(v => (int?)v.Id).FirstOrDefault();
                            if (numberPair.Key == "Mobile")
                            {
                                switch (smsAllowed.Trim().ToLower())
                                {
                                case "y":
                                case "yes":
                                case "active":
                                    currentNumber.IsMessagingEnabled = true;
                                    break;

                                default:
                                    currentNumber.IsMessagingEnabled = false;
                                    break;
                                }
                            }

                            person.PhoneNumbers.Add(currentNumber);
                        }
                    }

                    // Map Person attributes
                    person.Attributes      = new Dictionary <string, AttributeCache>();
                    person.AttributeValues = new Dictionary <string, AttributeValue>();

                    bool isEmailActive;
                    switch (row[IsEmailActive].Trim().ToLower())
                    {
                    case "n":
                    case "no":
                    case "inactive":
                        isEmailActive = false;
                        break;

                    default:
                        isEmailActive = true;
                        break;
                    }

                    EmailPreference emailPreference;
                    switch (row[AllowBulkEmail].Trim().ToLower())
                    {
                    case "n":
                    case "no":
                    case "inactive":
                        emailPreference = EmailPreference.NoMassEmails;
                        break;

                    default:
                        emailPreference = EmailPreference.EmailAllowed;
                        break;
                    }

                    person.EmailPreference = emailPreference;
                    string primaryEmail = row[Email].Trim();
                    if (!string.IsNullOrWhiteSpace(primaryEmail))
                    {
                        if (primaryEmail.IsEmail())
                        {
                            person.Email         = primaryEmail;
                            person.IsEmailActive = isEmailActive;
                        }
                        else
                        {
                            LogException("InvalidPrimaryEmail", string.Format("PersonId: {0} - Email: {1}", rowPersonId, primaryEmail));
                        }
                    }

                    string schoolName = row[School];
                    if (!string.IsNullOrWhiteSpace(schoolName))
                    {
                        // Add school if it doesn't exist
                        Guid schoolGuid;
                        var  schoolExists = schoolDefinedType.DefinedValues.Any(s => s.Value.Equals(schoolName));
                        if (!schoolExists)
                        {
                            var newSchool = new DefinedValue();
                            newSchool.DefinedTypeId = schoolDefinedType.Id;
                            newSchool.Value         = schoolName;
                            newSchool.Order         = 0;

                            lookupContext.DefinedValues.Add(newSchool);
                            lookupContext.SaveChanges();

                            schoolGuid = newSchool.Guid;
                        }
                        else
                        {
                            schoolGuid = schoolDefinedType.DefinedValues.FirstOrDefault(s => s.Value.Equals(schoolName)).Guid;
                        }

                        AddPersonAttribute(schoolAttribute, person, schoolGuid.ToString().ToUpper());
                    }

                    foreach (var attributePair in customAttributes)
                    {
                        string newAttributeValue = row[attributePair.Key];
                        if (!string.IsNullOrWhiteSpace(newAttributeValue))
                        {
                            // check if this attribute value is a date
                            DateTime valueAsDateTime;
                            if (DateTime.TryParseExact(newAttributeValue, dateFormats, CultureInfo.InvariantCulture, DateTimeStyles.None, out valueAsDateTime))
                            {
                                newAttributeValue = valueAsDateTime.ToString("yyyy-MM-dd");
                            }

                            int?newAttributeId = personAttributes.Where(a => a.Key == attributePair.Value.RemoveWhitespace())
                                                 .Select(a => (int?)a.Id).FirstOrDefault();
                            if (newAttributeId != null)
                            {
                                var newAttribute = AttributeCache.Read((int)newAttributeId);
                                AddPersonAttribute(newAttribute, person, newAttributeValue);
                            }
                        }
                    }

                    // Add notes to timeline
                    var notePairs = new Dictionary <string, string>();
                    notePairs.Add("General", row[GeneralNote]);
                    notePairs.Add("Medical", row[MedicalNote]);
                    notePairs.Add("Security", row[SecurityNote]);

                    foreach (var notePair in notePairs.Where(n => !string.IsNullOrWhiteSpace(n.Value)))
                    {
                        var newNote = new Note();
                        newNote.CreatedByPersonAliasId = ImportPersonAlias.Id;
                        newNote.CreatedDateTime        = importDate;
                        newNote.Text       = notePair.Value;
                        newNote.ForeignId  = rowPersonId;
                        newNote.NoteTypeId = noteTimelineTypeId;
                        newNote.Caption    = string.Format("{0} Note", notePair.Key);

                        if (!notePair.Key.Equals("General"))
                        {
                            newNote.IsAlert = true;
                        }

                        newNoteList.Add(newNote);
                    }

                    #endregion person create

                    var groupMember = new GroupMember();
                    groupMember.Person                 = person;
                    groupMember.GroupRoleId            = groupRoleId;
                    groupMember.CreatedDateTime        = importDate;
                    groupMember.ModifiedDateTime       = importDate;
                    groupMember.CreatedByPersonAliasId = ImportPersonAlias.Id;
                    groupMember.GroupMemberStatus      = GroupMemberStatus.Active;

                    if (rowFamilyId != currentFamilyGroup.ForeignId)
                    {
                        // person not part of the previous family, see if that family exists or create a new one
                        currentFamilyGroup = ImportedPeople.FirstOrDefault(p => p.ForeignId == rowFamilyId);
                        if (currentFamilyGroup == null)
                        {
                            currentFamilyGroup = CreateFamilyGroup(row[FamilyName], rowFamilyId);
                            newFamilyList.Add(currentFamilyGroup);
                            newFamilies++;
                        }
                        else
                        {
                            lookupContext.Groups.Attach(currentFamilyGroup);
                            lookupContext.Entry(currentFamilyGroup).State = EntityState.Modified;
                        }

                        currentFamilyGroup.Members.Add(groupMember);
                    }
                    else
                    {
                        // person is part of this family group, check if they're a visitor
                        if (isFamilyRelationship || currentFamilyGroup.Members.Count() < 1)
                        {
                            currentFamilyGroup.Members.Add(groupMember);
                        }
                        else
                        {
                            var visitorFamily = CreateFamilyGroup(person.LastName + " Family", rowFamilyId);
                            visitorFamily.Members.Add(groupMember);
                            newFamilyList.Add(visitorFamily);
                            newVisitorList.Add(visitorFamily);
                            newFamilies++;
                        }
                    }

                    completed++;
                    if (completed % (ReportingNumber * 10) < 1)
                    {
                        ReportProgress(0, string.Format("{0:N0} people imported.", completed));
                    }
                    else if (completed % ReportingNumber < 1)
                    {
                        SaveIndividuals(newFamilyList, newVisitorList, newNoteList);
                        lookupContext.SaveChanges();
                        ReportPartialProgress();

                        // Clear out variables
                        currentFamilyGroup = new Group();
                        newFamilyList.Clear();
                        newVisitorList.Clear();
                        newNoteList.Clear();
                    }
                }
            }

            // Save any changes to new families
            if (newFamilyList.Any())
            {
                SaveIndividuals(newFamilyList, newVisitorList, newNoteList);
            }

            // Save any changes to existing families
            lookupContext.SaveChanges();
            lookupContext.Dispose();

            ReportProgress(0, string.Format("Finished individual import: {0:N0} families and {1:N0} people added.", newFamilies, completed));
            return(completed);
        }
示例#44
0
 public GroupMemberAttributes(GroupMember groupMember, Person person, IEnumerable <AttributeValue> attributeValues)
 {
     GroupMember     = groupMember;
     AttributeValues = attributeValues;
     Person          = person;
 }
示例#45
0
        public async Task <(int Count, string Message, GroupMember?Member)> AddMemberAsync(ClaimsPrincipal?principal, GroupMember groupMember)
        {
            using var dbContext = Factory.CreateDbContext();
            if (principal.IsGroupMemberAdministrator(dbContext.GroupMembers.Where(gm => gm.GroupId == groupMember.GroupId)))
            {
                var existing = dbContext.GroupMembers.SingleOrDefault(gm => gm.PersonId == groupMember.PersonId && gm.GroupId == groupMember.GroupId);
                if (existing is not null)
                {
                    return(existing.AlreadyExists());
                }
                dbContext.GroupMembers.Add(groupMember);
                var result = await dbContext.SaveChangesAsync();

                return(result.SaveResult(groupMember));
            }
            return(principal.SaveNotAuthorised <GroupMember>());
        }
示例#46
0
        /// <summary>
        /// Handles the Click event of the btnSaveEditPreferences 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 btnSaveEditPreferences_Click(object sender, EventArgs e)
        {
            var rockContext   = new RockContext();
            var groupMember   = new GroupMemberService(rockContext).Get(hfGroupMemberId.Value.AsInteger());
            var personService = new PersonService(rockContext);
            var person        = personService.Get(groupMember.PersonId);

            int?orphanedPhotoId = null;

            if (person.PhotoId != imgProfilePhoto.BinaryFileId)
            {
                orphanedPhotoId = person.PhotoId;
                person.PhotoId  = imgProfilePhoto.BinaryFileId;

                // add or update the Photo Verify group to have this person as Pending since the photo was changed or deleted
                using (var photoRequestRockContext = new RockContext())
                {
                    GroupMemberService groupMemberService = new GroupMemberService(photoRequestRockContext);
                    Group photoRequestGroup = new GroupService(photoRequestRockContext).Get(Rock.SystemGuid.Group.GROUP_PHOTO_REQUEST.AsGuid());

                    var photoRequestGroupMember = groupMemberService.Queryable().Where(a => a.GroupId == photoRequestGroup.Id && a.PersonId == person.Id).FirstOrDefault();
                    if (photoRequestGroupMember == null)
                    {
                        photoRequestGroupMember             = new GroupMember();
                        photoRequestGroupMember.GroupId     = photoRequestGroup.Id;
                        photoRequestGroupMember.PersonId    = person.Id;
                        photoRequestGroupMember.GroupRoleId = photoRequestGroup.GroupType.DefaultGroupRoleId ?? -1;
                        groupMemberService.Add(photoRequestGroupMember);
                    }

                    photoRequestGroupMember.GroupMemberStatus = GroupMemberStatus.Pending;

                    photoRequestRockContext.SaveChanges();
                }
            }

            // Save the GroupMember Attributes
            groupMember.LoadAttributes();
            Rock.Attribute.Helper.GetEditValues(phGroupMemberAttributes, groupMember);

            // Save selected Person Attributes (The ones picked in Block Settings)
            var personAttributes = this.GetAttributeValue("PersonAttributes").SplitDelimitedValues().AsGuidList().Select(a => AttributeCache.Get(a));

            if (personAttributes.Any())
            {
                person.LoadAttributes(rockContext);
                foreach (var personAttribute in personAttributes)
                {
                    Control attributeControl = phPersonAttributes.FindControl(string.Format("attribute_field_{0}", personAttribute.Id));
                    if (attributeControl != null)
                    {
                        // Save Attribute value to the database
                        string newValue = personAttribute.FieldType.Field.GetEditValue(attributeControl, personAttribute.QualifierValues);
                        Rock.Attribute.Helper.SaveAttributeValue(person, personAttribute, newValue, rockContext);
                    }
                }
            }

            // Save everything else to the database in a db transaction
            rockContext.WrapTransaction(() =>
            {
                rockContext.SaveChanges();
                groupMember.SaveAttributeValues(rockContext);

                if (orphanedPhotoId.HasValue)
                {
                    BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                    var binaryFile = binaryFileService.Get(orphanedPhotoId.Value);
                    if (binaryFile != null)
                    {
                        // marked the old images as IsTemporary so they will get cleaned up later
                        binaryFile.IsTemporary = true;
                        rockContext.SaveChanges();
                    }
                }

                // if they used the ImageEditor, and cropped it, the uncropped file is still in BinaryFile. So clean it up
                if (imgProfilePhoto.CropBinaryFileId.HasValue)
                {
                    if (imgProfilePhoto.CropBinaryFileId != person.PhotoId)
                    {
                        BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                        var binaryFile = binaryFileService.Get(imgProfilePhoto.CropBinaryFileId.Value);
                        if (binaryFile != null && binaryFile.IsTemporary)
                        {
                            string errorMessage;
                            if (binaryFileService.CanDelete(binaryFile, out errorMessage))
                            {
                                binaryFileService.Delete(binaryFile);
                                rockContext.SaveChanges();
                            }
                        }
                    }
                }
            });

            ShowView(hfGroupId.Value.AsInteger(), hfGroupMemberId.Value.AsInteger());
        }
        private string GetGroupMemberAttributeValues()
        {
            var groupId = ddlPlacementGroup.SelectedValueAsInt();
            var groupMemberRoleId = ddlPlacementGroupRole.SelectedValueAsInt();
            var groupMemberStatus = ddlPlacementGroupStatus.SelectedValueAsEnumOrNull<GroupMemberStatus>();

            var values = new Dictionary<string, string>();

            if ( groupId.HasValue && groupMemberRoleId.HasValue && groupMemberStatus != null )
            {
                using ( var rockContext = new RockContext() )
                {
                    var group = new GroupService( rockContext ).Get( groupId.Value );
                    var role = new GroupTypeRoleService( rockContext ).Get( groupMemberRoleId.Value );
                    if ( group != null && role != null )
                    {
                        var groupMember = new GroupMember();
                        groupMember.Group = group;
                        groupMember.GroupId = group.Id;
                        groupMember.GroupRole = role;
                        groupMember.GroupRoleId = role.Id;
                        groupMember.GroupMemberStatus = groupMemberStatus.Value;

                        groupMember.LoadAttributes();
                        Rock.Attribute.Helper.GetEditValues( phGroupMemberAttributes, groupMember );

                        foreach( var attrValue in groupMember.AttributeValues )
                        {
                            values.Add( attrValue.Key, attrValue.Value.Value );
                        }

                        return JsonConvert.SerializeObject( values, Formatting.None );
                    }
                }
            }

            return string.Empty;
        }
示例#48
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtFirstName.Text) ||
                string.IsNullOrWhiteSpace(txtLastName.Text) ||
                string.IsNullOrWhiteSpace(txtEmail.Text))
            {
                ShowError("Missing Information", "Please enter a value for First Name, Last Name, and Email");
            }
            else
            {
                var person = GetPerson();
                if (person != null)
                {
                    int groupId = int.MinValue;
                    if (int.TryParse(GetAttributeValue("Group"), out groupId))
                    {
                        using (new UnitOfWorkScope())
                        {
                            var groupService       = new GroupService();
                            var groupMemberService = new GroupMemberService();

                            var group = groupService.Get(groupId);
                            if (group != null && group.GroupType.DefaultGroupRoleId.HasValue)
                            {
                                string linkedPage = GetAttributeValue("ConfirmationPage");
                                if (!string.IsNullOrWhiteSpace(linkedPage))
                                {
                                    var member = group.Members.Where(m => m.PersonId == person.Id).FirstOrDefault();

                                    // If person has not registered or confirmed their registration
                                    if (member == null || member.GroupMemberStatus != GroupMemberStatus.Active)
                                    {
                                        Email email = null;

                                        Guid guid = Guid.Empty;
                                        if (Guid.TryParse(GetAttributeValue("ConfirmationEmail"), out guid))
                                        {
                                            email = new Email(guid);
                                        }

                                        if (member == null)
                                        {
                                            member             = new GroupMember();
                                            member.GroupId     = group.Id;
                                            member.PersonId    = person.Id;
                                            member.GroupRoleId = group.GroupType.DefaultGroupRoleId.Value;

                                            // If a confirmation email is configured, set status to Pending otherwise set it to active
                                            member.GroupMemberStatus = email != null ? GroupMemberStatus.Pending : GroupMemberStatus.Active;

                                            groupMemberService.Add(member, CurrentPersonId);
                                            groupMemberService.Save(member, CurrentPersonId);
                                            member = groupMemberService.Get(member.Id);
                                        }

                                        // Send the confirmation
                                        if (email != null)
                                        {
                                            var mergeObjects = new Dictionary <string, object>();
                                            mergeObjects.Add("Member", member);

                                            var pageParams = new Dictionary <string, string>();
                                            pageParams.Add("gm", member.UrlEncodedKey);
                                            var pageReference = new Rock.Web.PageReference(linkedPage, pageParams);
                                            mergeObjects.Add("ConfirmationPage", pageReference.BuildUrl());

                                            var recipients = new Dictionary <string, Dictionary <string, object> >();
                                            recipients.Add(person.Email, mergeObjects);
                                            email.Send(recipients);
                                        }

                                        ShowSuccess(GetAttributeValue("SuccessMessage"));
                                    }
                                    else
                                    {
                                        var pageParams = new Dictionary <string, string>();
                                        pageParams.Add("gm", member.UrlEncodedKey);
                                        var pageReference = new Rock.Web.PageReference(linkedPage, pageParams);
                                        Response.Redirect(pageReference.BuildUrl(), false);
                                    }
                                }
                                else
                                {
                                    ShowError("Configuration Error", "Invalid Confirmation Page setting");
                                }
                            }
                            else
                            {
                                ShowError("Configuration Error",
                                          "The configured group does not exist, or it's group type does not have a default role configured.");
                            }
                        }
                    }
                    else
                    {
                        ShowError("Configuration Error", "Invalid Group setting");
                    }
                }
            }
        }
示例#49
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad( EventArgs e )
        {
            base.OnLoad( e );

            if ( !Page.IsPostBack )
            {
                RockContext rockContext = new RockContext();

                Group group = null;
                Guid personGuid = Guid.Empty;
                GroupTypeRole groupMemberRole = null;

                // get group id from url
                if ( Request["GroupId"] != null )
                {
                    int groupId = 0;
                    if ( Int32.TryParse( Request["GroupId"], out groupId ) )
                    {
                        group = new GroupService( rockContext ).Queryable("GroupType,GroupType.Roles").Where(g => g.Id == groupId ).FirstOrDefault();
                    }
                }
                else
                {
                    Guid groupGuid = Guid.Empty;
                    if ( Guid.TryParse( GetAttributeValue( "DefaultGroup" ), out groupGuid ) ) {
                        group = new GroupService( rockContext ).Queryable( "GroupType,GroupType.Roles" ).Where( g => g.Guid == groupGuid ).FirstOrDefault(); ;
                    }
                }

                if ( group == null )
                {
                    lAlerts.Text = "Could not determine the group to add to.";
                    return;
                }

                // get group role id from url
                if ( Request["GroupMemberRoleId"] != null )
                {
                    int groupMemberRoleId = 0;
                    if ( Int32.TryParse( Request["GroupMemberRoleId"], out groupMemberRoleId ) )
                    {
                        groupMemberRole = new GroupTypeRoleService( rockContext ).Get( groupMemberRoleId );
                    }
                }
                else
                {
                    Guid groupMemberRoleGuid = Guid.Empty;
                    if ( Guid.TryParse( GetAttributeValue( "DefaultGroupMemberRole" ), out groupMemberRoleGuid ) )
                    {
                        groupMemberRole = new GroupTypeRoleService( rockContext ).Get( groupMemberRoleGuid );
                    }
                }

                if ( groupMemberRole == null )
                {
                    lAlerts.Text += "Could not determine the group role to use for the add.";
                    return;
                }

                // get person
                if ( Request["PersonGuid"] != null )
                {
                    Guid.TryParse( Request["PersonGuid"], out personGuid );
                }

                if ( personGuid == Guid.Empty )
                {
                    lAlerts.Text += "A valid person identifier was not found in the page address.";
                    return;
                }

                // ensure that the group type has this role
                if ( ! group.GroupType.Roles.Contains( groupMemberRole ) )
                {
                    lAlerts.Text += "The group you have provided does not have the group member role configured.";
                    return;
                }

                // get person
                Person person = new PersonService( rockContext ).Get( personGuid );

                if ( person == null )
                {
                    lAlerts.Text += "A person could not be found for the identifier provided.";
                    return;
                }

                // hide alert
                divAlert.Visible = false;

                // get status
                var groupMemberStatus = this.GetAttributeValue( "GroupMemberStatus" ).ConvertToEnum<GroupMemberStatus>( GroupMemberStatus.Active );

                // load merge fields
                var mergeFields = new Dictionary<string, object>();
                mergeFields.Add( "GroupMemberStatus", groupMemberStatus.ToString() );
                mergeFields.Add( "Group", group );
                mergeFields.Add( "Person", person );
                mergeFields.Add( "Role", groupMemberRole );
                mergeFields.Add( "CurrentPerson", CurrentPerson );

                // show debug info?
                bool enableDebug = GetAttributeValue( "EnableDebug" ).AsBoolean();
                if ( enableDebug && IsUserAuthorized( Authorization.EDIT ) )
                {
                    lDebug.Visible = true;
                    lDebug.Text = mergeFields.lavaDebugInfo();
                }

                // ensure that the person is not already in the group
                if ( group.Members.Where( m => m.PersonId == person.Id && m.GroupRoleId == groupMemberRole.Id ).Count() != 0 )
                {
                    string templateInGroup = GetAttributeValue( "AlreadyInGroupMessage" );
                    lContent.Text = templateInGroup.ResolveMergeFields( mergeFields );
                    return;

                }

                // add person to group
                GroupMember groupMember = new GroupMember();
                groupMember.GroupId = group.Id;
                groupMember.PersonId = person.Id;
                groupMember.GroupRoleId = groupMemberRole.Id;
                groupMember.GroupMemberStatus = groupMemberStatus;
                group.Members.Add( groupMember );

                try
                {
                    rockContext.SaveChanges();
                }
                catch ( Exception ex )
                {
                    divAlert.Visible = true;
                    lAlerts.Text = String.Format( "An error occurred adding {0} to the group {1}. Message: {2}.", person.FullName, group.Name, ex.Message );
                }

                string templateSuccess = GetAttributeValue( "SuccessMessage" );
                lContent.Text = templateSuccess.ResolveMergeFields( mergeFields );
            }
        }
示例#50
0
 public void JoinGroup(GroupMember gm)
 {
     db.GroupMembers.Add(gm);
     db.SaveChanges();
 }
        private int? AddRegistrantToGroup( RegistrationRegistrant registrant )
        {
            if ( registrant.PersonAliasId.HasValue &&
                registrant.Registration != null &&
                registrant.Registration.Group != null &&
                registrant.Registration.Group.GroupType != null && _template != null )
            {
                var group = registrant.Registration.Group;

                var groupService = new GroupService( _rockContext );
                var personAliasService = new PersonAliasService( _rockContext );
                var groupMemberService = new GroupMemberService( _rockContext );

                var personAlias = personAliasService.Get( registrant.PersonAliasId.Value );
                GroupMember groupMember = group.Members.Where( m => m.PersonId == personAlias.PersonId ).FirstOrDefault();
                if ( groupMember == null )
                {
                    groupMember = new GroupMember();
                    groupMemberService.Add( groupMember );
                    groupMember.GroupId = group.Id;
                    groupMember.PersonId = personAlias.PersonId;

                    if ( _template.GroupTypeId.HasValue &&
                        _template.GroupTypeId == group.GroupTypeId &&
                        _template.GroupMemberRoleId.HasValue )
                    {
                        groupMember.GroupRoleId = _template.GroupMemberRoleId.Value;
                        groupMember.GroupMemberStatus = _template.GroupMemberStatus;
                    }
                    else
                    {
                        if ( group.GroupType.DefaultGroupRoleId.HasValue )
                        {
                            groupMember.GroupRoleId = group.GroupType.DefaultGroupRoleId.Value;
                        }
                        else
                        {
                            groupMember.GroupRoleId = group.GroupType.Roles.Select( r => r.Id ).FirstOrDefault();
                        }
                    }
                }

                groupMember.GroupMemberStatus = GroupMemberStatus.Active;

                _rockContext.SaveChanges();

                return groupMember.Id;
            }

            return (int?)null;
        }
        /// <summary>
        /// Executes the specified workflow.
        /// </summary>
        /// <param name="rockContext">The rock context.</param>
        /// <param name="action">The action.</param>
        /// <param name="entity">The entity.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <returns></returns>
        public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            Guid?  groupGuid          = null;
            Person person             = null;
            var    attendanceDateTime = RockDateTime.Now;
            bool   addToGroup         = true;

            // get the group attribute
            Guid groupAttributeGuid = GetAttributeValue(action, "Group").AsGuid();

            if (!groupAttributeGuid.IsEmpty())
            {
                groupGuid = action.GetWorkflowAttributeValue(groupAttributeGuid).AsGuidOrNull();

                if (!groupGuid.HasValue)
                {
                    errorMessages.Add("The group could not be found!");
                }
            }

            // get person alias guid
            Guid   personAliasGuid = Guid.Empty;
            string personAttribute = GetAttributeValue(action, "Person");

            Guid guid = personAttribute.AsGuid();

            if (!guid.IsEmpty())
            {
                var attribute = AttributeCache.Get(guid, rockContext);
                if (attribute != null)
                {
                    string value = action.GetWorkflowAttributeValue(guid);
                    personAliasGuid = value.AsGuid();
                }

                if (personAliasGuid != Guid.Empty)
                {
                    person = new PersonAliasService(rockContext).Queryable().AsNoTracking()
                             .Where(p => p.Guid.Equals(personAliasGuid))
                             .Select(p => p.Person)
                             .FirstOrDefault();
                }
                else
                {
                    errorMessages.Add("The person could not be found in the attribute!");
                }
            }

            // get attendance date
            Guid dateTimeAttributeGuid = GetAttributeValue(action, "AttendanceDatetime").AsGuid();

            if (!dateTimeAttributeGuid.IsEmpty())
            {
                string attributeDatetime = action.GetWorkflowAttributeValue(dateTimeAttributeGuid);

                if (!string.IsNullOrWhiteSpace(attributeDatetime))
                {
                    if (!DateTime.TryParse(attributeDatetime, out attendanceDateTime))
                    {
                        errorMessages.Add(string.Format("Could not parse the date provided {0}.", attributeDatetime));
                    }
                }
            }

            // get add to group
            addToGroup = GetAttributeValue(action, "AddToGroup").AsBoolean();

            // get location
            Guid locationGuid          = Guid.Empty;
            Guid locationAttributeGuid = GetAttributeValue(action, "Location").AsGuid();

            if (!locationAttributeGuid.IsEmpty())
            {
                var locationAttribute = AttributeCache.Get(locationAttributeGuid, rockContext);

                if (locationAttribute != null)
                {
                    locationGuid = action.GetWorkflowAttributeValue(locationAttributeGuid).AsGuid();
                }
            }

            //// get Schedule
            Guid scheduleGuid          = Guid.Empty;
            Guid scheduleAttributeGuid = GetAttributeValue(action, "Schedule").AsGuid();

            if (!scheduleAttributeGuid.IsEmpty())
            {
                var scheduleAttribute = AttributeCache.Get(scheduleAttributeGuid, rockContext);
                if (scheduleAttribute != null)
                {
                    scheduleGuid = action.GetWorkflowAttributeValue(scheduleAttributeGuid).AsGuid();
                }
            }

            // set attribute
            if (groupGuid.HasValue && person != null && attendanceDateTime != DateTime.MinValue)
            {
                var group = new GroupService(rockContext).Queryable("GroupType.DefaultGroupRole")
                            .Where(g => g.Guid == groupGuid)
                            .FirstOrDefault();
                if (group != null)
                {
                    GroupMemberService groupMemberService = new GroupMemberService(rockContext);

                    // get group member
                    var groupMember = groupMemberService.Queryable()
                                      .Where(m => m.Group.Guid == groupGuid &&
                                             m.PersonId == person.Id)
                                      .FirstOrDefault();
                    if (groupMember == null)
                    {
                        if (addToGroup)
                        {
                            if (group != null)
                            {
                                groupMember                   = new GroupMember();
                                groupMember.GroupId           = group.Id;
                                groupMember.PersonId          = person.Id;
                                groupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                groupMember.GroupRole         = group.GroupType.DefaultGroupRole;
                                groupMemberService.Add(groupMember);
                                rockContext.SaveChanges();
                            }
                        }
                        else
                        {
                            action.AddLogEntry(string.Format("{0} was not a member of the group {1} and the action was not configured to add them.", person.FullName, group.Name));
                        }
                    }

                    int?locationId = null;
                    if (locationGuid != Guid.Empty)
                    {
                        var location = new LocationService(rockContext).Queryable().AsNoTracking()
                                       .Where(l => l.Guid == locationGuid)
                                       .FirstOrDefault();

                        if (location != null)
                        {
                            locationId = location.Id;
                        }
                    }

                    int?scheduleId = null;
                    if (scheduleGuid != Guid.Empty)
                    {
                        var schedule = new ScheduleService(rockContext).Queryable().AsNoTracking()
                                       .Where(l => l.Guid == scheduleGuid)
                                       .FirstOrDefault();

                        if (schedule != null)
                        {
                            scheduleId = schedule.Id;
                        }
                    }

                    int?personAliasId = person.PrimaryAliasId;
                    if (personAliasId.HasValue)
                    {
                        /*
                         * 3/31/2020 - SK
                         * Updated code to consider time with attendance date to fix the issue raised in #4159
                         * https://github.com/SparkDevNetwork/Rock/issues/4159
                         */
                        new AttendanceService(rockContext).AddOrUpdate(personAliasId.Value, attendanceDateTime, group.Id, locationId, scheduleId, group.CampusId);
                        rockContext.SaveChanges();

                        if (locationId.HasValue)
                        {
                            Rock.CheckIn.KioskLocationAttendance.Remove(locationId.Value);
                        }
                    }
                }
                else
                {
                    errorMessages.Add(string.Format("Could not find group matching the guid '{0}'.", groupGuid));
                }
            }

            errorMessages.ForEach(m => action.AddLogEntry(m, true));

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

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

            RegistrationTemplate RegistrationTemplate = null;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                var groupService = new GroupService( rockContext );

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

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

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

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

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

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

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

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

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

                rockContext.SaveChanges();

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

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

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

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

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

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

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

                rockContext.SaveChanges();

                AttributeCache.FlushEntityAttributes();

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

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

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

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

                var qryParams = new Dictionary<string, string>();
                qryParams["RegistrationTemplateId"] = RegistrationTemplate.Id.ToString();
                NavigateToPage( RockPage.Guid, qryParams );
            }
        }
示例#54
0
        override public void Execute()
        {
            inviteUsersToMyAccount();
            displayAccountGroupsAndMembers();
            Group emptyGroup = GroupBuilder.NewGroup(Guid.NewGuid().ToString())
                               .WithId(new GroupId(Guid.NewGuid().ToString()))
                               .WithEmail("*****@*****.**")
                               .WithoutIndividualMemberEmailing()
                               .Build();

            createdEmptyGroup = eslClient.GroupService.CreateGroup(emptyGroup);
            List <GroupMember> retrievedEmptyGroup = eslClient.GroupService.GetGroupMembers(createdEmptyGroup.Id);

            GroupMember addMember = eslClient.GroupService.AddMember(createdEmptyGroup.Id,
                                                                     GroupMemberBuilder.NewGroupMember(email1)
                                                                     .AsMemberType(GroupMemberType.MANAGER)
                                                                     .Build());
            Group inviteMember = eslClient.GroupService.InviteMember(createdEmptyGroup.Id,
                                                                     GroupMemberBuilder.NewGroupMember(email3)
                                                                     .AsMemberType(GroupMemberType.MANAGER)
                                                                     .Build());

            Console.Out.WriteLine("GroupId: " + createdEmptyGroup.Id.Id);
            retrievedEmptyGroup = eslClient.GroupService.GetGroupMembers(createdEmptyGroup.Id);

            String groupName = Guid.NewGuid().ToString();
            Group  group1    = GroupBuilder.NewGroup(GROUP_NAME_PREFIX + groupName)
                               .WithId(new GroupId(Guid.NewGuid().ToString()))
                               .WithMember(GroupMemberBuilder.NewGroupMember(email1)
                                           .AsMemberType(GroupMemberType.MANAGER))
                               .WithMember(GroupMemberBuilder.NewGroupMember(email3)
                                           .AsMemberType(GroupMemberType.MANAGER))
                               .WithEmail(EMAIL)
                               .WithIndividualMemberEmailing()
                               .Build();

            createdGroup1 = eslClient.GroupService.CreateGroup(group1);
            Console.Out.WriteLine("GroupId #1: " + createdGroup1.Id.Id);

            eslClient.GroupService.AddMember(createdGroup1.Id,
                                             GroupMemberBuilder.NewGroupMember(email3)
                                             .AsMemberType(GroupMemberType.MANAGER)
                                             .Build());

            eslClient.GroupService.AddMember(createdGroup1.Id,
                                             GroupMemberBuilder.NewGroupMember(email4)
                                             .AsMemberType(GroupMemberType.REGULAR)
                                             .Build());

            retrievedGroup1 = eslClient.GroupService.GetGroup(createdGroup1.Id);
            // Retrieve by group name
            retrievedGroupByName1 = eslClient.GroupService.GetMyGroups(createdGroup1.Name);

            String groupName2 = Guid.NewGuid().ToString();
            Group  group2     = GroupBuilder.NewGroup(GROUP_NAME_PREFIX + groupName2)
                                .WithMember(GroupMemberBuilder.NewGroupMember(email2)
                                            .AsMemberType(GroupMemberType.MANAGER))
                                .WithEmail(EMAIL)
                                .WithIndividualMemberEmailing()
                                .Build();

            createdGroup2   = eslClient.GroupService.CreateGroup(group2);
            retrievedGroup2 = eslClient.GroupService.GetGroup(createdGroup2.Id);
            Console.Out.WriteLine("GroupId #2: " + createdGroup2.Id.Id);

            String groupName3 = Guid.NewGuid().ToString();
            Group  group3     = GroupBuilder.NewGroup(GROUP_NAME_PREFIX + groupName3)
                                .WithMember(GroupMemberBuilder.NewGroupMember(email3)
                                            .AsMemberType(GroupMemberType.MANAGER))
                                .WithEmail(EMAIL)
                                .WithIndividualMemberEmailing()
                                .Build();

            createdGroup3 = eslClient.GroupService.CreateGroup(group3);
            Console.Out.WriteLine("GroupId #3: " + createdGroup3.Id.Id);
            retrievedGroup3 = eslClient.GroupService.GetGroup(createdGroup3.Id);
            // Retrieve by group name
            retrievedByNamePrefix = eslClient.GroupService.GetMyGroups(GROUP_NAME_PREFIX);

            allGroupsBeforeDelete = eslClient.GroupService.GetMyGroups();

            allGroupsAfterDelete = eslClient.GroupService.GetMyGroups();

            Group updatedGroup = GroupBuilder.NewGroup(Guid.NewGuid().ToString())
                                 .WithMember(GroupMemberBuilder.NewGroupMember(email2)
                                             .AsMemberType(GroupMemberType.MANAGER))
                                 .WithMember(GroupMemberBuilder.NewGroupMember(email3)
                                             .AsMemberType(GroupMemberType.REGULAR))
                                 .WithMember(GroupMemberBuilder.NewGroupMember(email4)
                                             .AsMemberType(GroupMemberType.REGULAR))
                                 .WithEmail(EMAIL)
                                 .WithIndividualMemberEmailing()
                                 .Build();

            createdGroup3Updated = eslClient.GroupService.UpdateGroup(updatedGroup, createdGroup3.Id);

            groupMemberEmailsAfterUpdate = eslClient.GroupService.GetGroupMemberEmails(createdGroup3Updated.Id);

            DocumentPackage superDuperPackage = PackageBuilder.NewPackageNamed(PackageName)
                                                .WithSigner(SignerBuilder.NewSignerFromGroup(createdGroup1.Id)
                                                            .CanChangeSigner()
                                                            .DeliverSignedDocumentsByEmail())
                                                .WithDocument(DocumentBuilder.NewDocumentNamed("First Document")
                                                              .FromStream(fileStream1, DocumentType.PDF)
                                                              .WithSignature(SignatureBuilder.SignatureFor(createdGroup1.Id)
                                                                             .OnPage(0)
                                                                             .AtPosition(100, 100)))
                                                .Build();

            PackageId packageId = eslClient.CreatePackage(superDuperPackage);

            eslClient.SendPackage(packageId);

            eslClient.PackageService.NotifySigner(packageId, createdGroup1.Id);

            DocumentPackage result = eslClient.GetPackage(packageId);

            eslClient.GroupService.DeleteGroup(createdGroup1.Id);
            eslClient.GroupService.DeleteGroup(createdGroup2.Id);
            eslClient.GroupService.DeleteGroup(createdGroup3.Id);
        }
示例#55
0
 /// <summary>
 /// Binds the attributes.
 /// </summary>
 private void BindAttributes()
 {
     // Parse the attribute filters
     AvailableAttributes = new List<AttributeCache>();
     if ( _group != null )
     {
         int entityTypeId = new GroupMember().TypeId;
         string groupQualifier = _group.Id.ToString();
         string groupTypeQualifier = _group.GroupTypeId.ToString();
         foreach ( var attributeModel in new AttributeService( new RockContext() ).Queryable()
             .Where( a =>
                 a.EntityTypeId == entityTypeId &&
                 a.IsGridColumn &&
                 ( ( a.EntityTypeQualifierColumn.Equals( "GroupId", StringComparison.OrdinalIgnoreCase ) && a.EntityTypeQualifierValue.Equals( groupQualifier ) ) ||
                  ( a.EntityTypeQualifierColumn.Equals( "GroupTypeId", StringComparison.OrdinalIgnoreCase ) && a.EntityTypeQualifierValue.Equals( groupTypeQualifier ) ) ) )
             .OrderByDescending( a => a.EntityTypeQualifierColumn )
             .ThenBy( a => a.Order )
             .ThenBy( a => a.Name ) )
         {
             AvailableAttributes.Add( AttributeCache.Read( attributeModel ) );
         }
     }
 }
 /// <summary>
 /// Recursive function which determines whether
 /// a <see cref="Group"/> is a member of a group
 /// or of a descendant group.
 /// </summary>
 /// <param name="group">
 /// An instance of <see cref="Group"/> to check for
 /// the presence of <paramref name="memberGroup"/>
 /// among its members or descendants.
 /// </param>
 /// <param name="memberGroup">
 /// Another group which may potentially be added to the
 /// members of <paramref name="group"/> if it's allowed.
 /// </param>
 /// <returns>
 /// <c>true</c> if the given <paramref name="memberGroup"/>
 /// is a member of the given <paramref name="group"/> or of
 /// a descendant group; otherwise, <c>false</c>.
 /// </returns>
 public bool IsMemberGroup(Group group, GroupMember memberGroup)
 {
     return(this.IsMemberGroup(group, memberGroup, 0));
 }
        /// <summary>
        /// Adds or updates the given person into the given group.
        /// </summary>
        /// <param name="person">The person.</param>
        /// <param name="group">The group.</param>
        /// <param name="rockContext">The rock context.</param>
        private void AddOrUpdatePersonInGroup( Person person, Group group, RockContext rockContext )
        {
            try
            {
                var groupMember = group.Members.Where( m => m.PersonId == person.Id ).FirstOrDefault();
                if ( groupMember == null )
                {
                    groupMember = new GroupMember();
                    groupMember.GroupId = group.Id;
                    groupMember.PersonId = person.Id;
                    groupMember.GroupRoleId = group.GroupType.DefaultGroupRoleId ?? 0;
                    group.Members.Add( groupMember );
                }
                var groupMemberStatus = GetAttributeValue( "GroupMemberStatus" );
                groupMember.GroupMemberStatus = (GroupMemberStatus)groupMemberStatus.AsInteger();
                rockContext.SaveChanges();

                // Now update any member attributes for the person...
                AddOrUpdateGroupMemberAttributes( person, group, rockContext );

                string successPage = GetAttributeValue( "SuccessPage" );
                if ( ! string.IsNullOrWhiteSpace( successPage ) )
                {
                    var pageReference = new Rock.Web.PageReference( successPage );
                    Response.Redirect( pageReference.BuildUrl(), false );
                    // this remaining stuff prevents .NET from quietly throwing ThreadAbortException
                    Context.ApplicationInstance.CompleteRequest();
                    return;
                }
                else
                {
                    lSuccess.Visible = true;
                    lSuccess.Text = GetAttributeValue( "SuccessMessage" );
                }
            }
            catch ( Exception ex )
            {
                LogException( ex );
                nbMessage.Visible = true;
                nbMessage.NotificationBoxType = NotificationBoxType.Danger;
                nbMessage.Text = "Something went wrong and we could not save your request. If it happens again please contact our office at the number below.";
            }
        }
示例#58
0
        /// <summary>
        /// Job that will sync groups.
        ///
        /// Called by the <see cref="IScheduler" /> when a
        /// <see cref="ITrigger" /> fires that is associated with
        /// the <see cref="IJob" />.
        /// </summary>
        public virtual void Execute(IJobExecutionContext context)
        {
            // Get the job setting(s)
            JobDataMap dataMap = context.JobDetail.JobDataMap;
            bool       requirePasswordReset = dataMap.GetBoolean("RequirePasswordReset");
            var        commandTimeout       = dataMap.GetString("CommandTimeout").AsIntegerOrNull() ?? 180;

            // Counters for displaying results
            int    groupsSynced  = 0;
            int    groupsChanged = 0;
            string groupName     = string.Empty;
            string dataViewName  = string.Empty;
            var    errors        = new List <string>();

            try
            {
                // get groups set to sync
                var activeSyncIds = new List <int>();
                using (var rockContext = new RockContext())
                {
                    // Get groups that are not archived and are still active.
                    activeSyncIds = new GroupSyncService(rockContext)
                                    .Queryable().AsNoTracking()
                                    .Where(x => !x.Group.IsArchived && x.Group.IsActive)
                                    .Select(x => x.Id)
                                    .ToList();
                }

                foreach (var syncId in activeSyncIds)
                {
                    bool hasSyncChanged = false;

                    // Use a fresh rockContext per sync so that ChangeTracker doesn't get bogged down
                    using (var rockContext = new RockContext())
                    {
                        // increase the timeout just in case the data view source is slow
                        rockContext.Database.CommandTimeout = commandTimeout;
                        rockContext.SourceOfChange          = "Group Sync";

                        // Get the Sync
                        var sync = new GroupSyncService(rockContext)
                                   .Queryable().AsNoTracking()
                                   .FirstOrDefault(s => s.Id == syncId);

                        // Ensure that the group's Sync Data View is a person data view
                        if (sync != null && sync.SyncDataView.EntityTypeId == EntityTypeCache.Get(typeof(Person)).Id)
                        {
                            List <string> syncErrors = new List <string>();

                            dataViewName = sync.SyncDataView.Name;
                            groupName    = sync.Group.Name;

                            // Get the person id's from the data view (source)
                            var personService   = new PersonService(rockContext);
                            var sourcePersonIds = sync.SyncDataView.GetQuery(null, rockContext, commandTimeout, out syncErrors)
                                                  .Select(q => q.Id).ToList();

                            // If any error occurred trying get the 'where expression' from the sync-data-view,
                            // just skip trying to sync that particular group's Sync Data View for now.
                            if (syncErrors.Count > 0)
                            {
                                errors.AddRange(syncErrors);
                                ExceptionLogService.LogException(new Exception(string.Format("An error occurred while trying to GroupSync group '{0}' and data view '{1}' so the sync was skipped. Error: {2}", groupName, dataViewName, String.Join(",", syncErrors))));
                                continue;
                            }

                            // Get the person id's in the group (target) for the role being synced.
                            // Note: targetPersonIds must include archived group members
                            // so we don't try to delete anyone who's already archived, and
                            // it must include deceased members so we can remove them if they
                            // are no longer in the data view.
                            var targetPersonIds = new GroupMemberService(rockContext)
                                                  .Queryable(true, true).AsNoTracking()
                                                  .Where(gm => gm.GroupId == sync.GroupId)
                                                  .Where(gm => gm.GroupRoleId == sync.GroupTypeRoleId)
                                                  .Select(gm => new {
                                PersonId   = gm.PersonId,
                                IsArchived = gm.IsArchived
                            })
                                                  .ToList();

                            // Delete people from the group/role that are no longer in the data view --
                            // but not the ones that are already archived.
                            foreach (var targetPerson in targetPersonIds.Where(t => !sourcePersonIds.Contains(t.PersonId) && t.IsArchived != true))
                            {
                                try
                                {
                                    // Use a new context to limit the amount of change-tracking required
                                    using (var groupMemberContext = new RockContext())
                                    {
                                        // Delete the records for that person's group and role
                                        var groupMemberService = new GroupMemberService(groupMemberContext);
                                        foreach (var groupMember in groupMemberService
                                                 .Queryable(true, true)
                                                 .Where(m =>
                                                        m.GroupId == sync.GroupId &&
                                                        m.GroupRoleId == sync.GroupTypeRoleId &&
                                                        m.PersonId == targetPerson.PersonId)
                                                 .ToList())
                                        {
                                            groupMemberService.Delete(groupMember);
                                        }

                                        groupMemberContext.SaveChanges();

                                        // If the Group has an exit email, and person has an email address, send them the exit email
                                        if (sync.ExitSystemEmail != null)
                                        {
                                            var person = new PersonService(groupMemberContext).Get(targetPerson.PersonId);
                                            if (person.Email.IsNotNullOrWhiteSpace())
                                            {
                                                // Send the exit email
                                                var mergeFields = new Dictionary <string, object>();
                                                mergeFields.Add("Group", sync.Group);
                                                mergeFields.Add("Person", person);
                                                var emailMessage = new RockEmailMessage(sync.ExitSystemEmail);
                                                emailMessage.AddRecipient(new RecipientData(person.Email, mergeFields));
                                                var emailErrors = new List <string>();
                                                emailMessage.Send(out emailErrors);
                                                errors.AddRange(emailErrors);
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    ExceptionLogService.LogException(ex);
                                    continue;
                                }

                                hasSyncChanged = true;
                            }

                            // Now find all the people in the source list who are NOT already in the target list
                            // or in the target list as archived (so we can restore them).
                            foreach (var personId in sourcePersonIds.Where(s => !targetPersonIds.Any(t => t.PersonId == s) ||
                                                                           targetPersonIds.Any(t => t.PersonId == s && t.IsArchived)))
                            {
                                try
                                {
                                    // Use a new context to limit the amount of change-tracking required
                                    using (var groupMemberContext = new RockContext())
                                    {
                                        var groupMemberService = new GroupMemberService(groupMemberContext);

                                        // If this person is currently archived...
                                        if (targetPersonIds.Any(t => t.PersonId == personId && t.IsArchived == true))
                                        {
                                            // ...then we'll just restore them;

                                            // NOTE: AddOrRestoreGroupMember will find the exact group member record and
                                            // sets their IsArchived back to false.
                                            var newGroupMember = groupMemberService.AddOrRestoreGroupMember(sync.Group, personId, sync.GroupTypeRoleId);
                                            newGroupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                            groupMemberContext.SaveChanges();
                                        }
                                        else
                                        {
                                            // ...otherwise we will add a new person to the group with the role specified in the sync.
                                            var newGroupMember = new GroupMember {
                                                Id = 0
                                            };
                                            newGroupMember.PersonId          = personId;
                                            newGroupMember.GroupId           = sync.GroupId;
                                            newGroupMember.GroupMemberStatus = GroupMemberStatus.Active;
                                            newGroupMember.GroupRoleId       = sync.GroupTypeRoleId;

                                            if (newGroupMember.IsValidGroupMember(groupMemberContext))
                                            {
                                                groupMemberService.Add(newGroupMember);
                                                groupMemberContext.SaveChanges();
                                            }
                                            else
                                            {
                                                // Validation errors will get added to the ValidationResults collection. Add those results to the log and then move on to the next person.
                                                var ex = new GroupMemberValidationException(string.Join(",", newGroupMember.ValidationResults.Select(r => r.ErrorMessage).ToArray()));
                                                ExceptionLogService.LogException(ex);
                                                continue;
                                            }
                                        }

                                        // If the Group has a welcome email, and person has an email address, send them the welcome email and possibly create a login
                                        if (sync.WelcomeSystemEmail != null)
                                        {
                                            var person = new PersonService(groupMemberContext).Get(personId);
                                            if (person.Email.IsNotNullOrWhiteSpace())
                                            {
                                                // If the group is configured to add a user account for anyone added to the group, and person does not yet have an
                                                // account, add one for them.
                                                string newPassword = string.Empty;
                                                bool   createLogin = sync.AddUserAccountsDuringSync;

                                                // Only create a login if requested, no logins exist and we have enough information to generate a user name.
                                                if (createLogin && !person.Users.Any() && !string.IsNullOrWhiteSpace(person.NickName) && !string.IsNullOrWhiteSpace(person.LastName))
                                                {
                                                    newPassword = System.Web.Security.Membership.GeneratePassword(9, 1);
                                                    string username = Rock.Security.Authentication.Database.GenerateUsername(person.NickName, person.LastName);

                                                    UserLogin login = UserLoginService.Create(
                                                        groupMemberContext,
                                                        person,
                                                        AuthenticationServiceType.Internal,
                                                        EntityTypeCache.Get(Rock.SystemGuid.EntityType.AUTHENTICATION_DATABASE.AsGuid()).Id,
                                                        username,
                                                        newPassword,
                                                        true,
                                                        requirePasswordReset);
                                                }

                                                // Send the welcome email
                                                var mergeFields = new Dictionary <string, object>();
                                                mergeFields.Add("Group", sync.Group);
                                                mergeFields.Add("Person", person);
                                                mergeFields.Add("NewPassword", newPassword);
                                                mergeFields.Add("CreateLogin", createLogin);
                                                var emailMessage = new RockEmailMessage(sync.WelcomeSystemEmail);
                                                emailMessage.AddRecipient(new RecipientData(person.Email, mergeFields));
                                                var emailErrors = new List <string>();
                                                emailMessage.Send(out emailErrors);
                                                errors.AddRange(emailErrors);
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    ExceptionLogService.LogException(ex);
                                    continue;
                                }

                                hasSyncChanged = true;
                            }

                            // Increment Groups Changed Counter (if people were deleted or added to the group)
                            if (hasSyncChanged)
                            {
                                groupsChanged++;
                            }

                            // Increment the Groups Synced Counter
                            groupsSynced++;
                        }
                    }
                }

                // Format the result message
                var resultMessage = string.Empty;
                if (groupsSynced == 0)
                {
                    resultMessage = "No groups to sync";
                }
                else if (groupsSynced == 1)
                {
                    resultMessage = "1 group was synced";
                }
                else
                {
                    resultMessage = string.Format("{0} groups were synced", groupsSynced);
                }

                resultMessage += string.Format(" and {0} groups were changed", groupsChanged);

                if (errors.Any())
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine();
                    sb.Append("Errors: ");
                    errors.ForEach(e => { sb.AppendLine(); sb.Append(e); });
                    string errorMessage = sb.ToString();
                    resultMessage += errorMessage;
                    throw new Exception(errorMessage);
                }

                context.Result = resultMessage;
            }
            catch (System.Exception ex)
            {
                HttpContext context2 = HttpContext.Current;
                ExceptionLogService.LogException(ex, context2);
                throw;
            }
        }
        public FamilyMember( GroupMember familyMember, bool existingFamilyMember )
        {
            if ( familyMember != null )
            {
                SetValuesFromPerson( familyMember.Person );

                if ( familyMember.GroupRole != null )
                {
                    RoleGuid = familyMember.GroupRole.Guid;
                    RoleName = familyMember.GroupRole.Name;
                }
            }

            ExistingFamilyMember = existingFamilyMember;
            Removed = false;
        }
示例#60
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);
                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 List <string>();

                if (registrant == null)
                {
                    newRegistrant             = true;
                    registrant                = new RegistrationRegistrant();
                    registrant.RegistrationId = RegistrantState.RegistrationId;
                    registrantService.Add(registrant);
                    registrantChanges.Add("Created Registrant");
                }

                if (!registrant.PersonAliasId.Equals(ppPerson.PersonAliasId))
                {
                    string prevPerson = (registrant.PersonAlias != null && registrant.PersonAlias.Person != null) ?
                                        registrant.PersonAlias.Person.FullName : string.Empty;
                    string newPerson = ppPerson.PersonName;
                    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.Option == dbFee.Option &&
                             f.Quantity > 0))
                    {
                        registrantChanges.Add(string.Format("Removed '{0}' Fee (Quantity:{1:N0}, Cost:{2:C2}, Option:{3}",
                                                            dbFee.RegistrationTemplateFee.Name, dbFee.Quantity, dbFee.Cost, dbFee.Option));

                        registrant.Fees.Remove(dbFee);
                        registrantFeeService.Delete(dbFee);
                    }
                }

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

                        if (dbFee == null)
                        {
                            dbFee = new RegistrationRegistrantFee();
                            dbFee.RegistrationTemplateFeeId = uiFee.Key;
                            dbFee.Option = uiFeeOption.Option;
                            registrant.Fees.Add(dbFee);
                        }

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

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

                        if (dbFee.Id <= 0)
                        {
                            registrantChanges.Add(feeName + " Fee Added");
                        }

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

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

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

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

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

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

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

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

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

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

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

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

                    registrant.LoadAttributes();
                    foreach (var field in TemplateState.Forms
                             .SelectMany(f => f.Fields
                                         .Where(t =>
                                                t.FieldSource == RegistrationFieldSource.RegistrationAttribute &&
                                                t.AttributeId.HasValue)))
                    {
                        var attribute = AttributeCache.Read(field.AttributeId.Value);
                        if (attribute != null)
                        {
                            string originalValue = registrant.GetAttributeValue(attribute.Key);
                            var fieldValue       = RegistrantState.FieldValues
                                                   .Where(f => f.Key == field.Id)
                                                   .Select(f => f.Value.FieldValue)
                                                   .FirstOrDefault();
                            string newValue = fieldValue != null ? fieldValue.ToString() : string.Empty;

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

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

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

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

                    registrant.SaveAttributeValues(rockContext);
                });

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

                                    newRockContext.SaveChanges();

                                    registrantChanges.Add(string.Format("Registrant added to {0} group", reloadedRegistrant.Registration.Group.Name));
                                }
                                else
                                {
                                    registrantChanges.Add(string.Format("Registrant group member reference updated to existing person in {0} group", reloadedRegistrant.Registration.Group.Name));
                                }

                                // Record this to the Person's and Registrants Notes and History...
                                reloadedRegistrant.Registration.SavePersonNotesAndHistory(reloadedRegistrant.Registration.PersonAlias.Person, this.CurrentPersonAliasId, previousRegistrantPersonIds);

                                reloadedRegistrant.GroupMemberId = groupMember.Id;
                                newRockContext.SaveChanges();
                            }
                        }
                    }
                }

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

            NavigateToRegistration();
        }