public void ShouldUpdatePreviouslySavedAttributeNotes()
        {
            var contactAttributes = new Dictionary <int, ObjectAttributeTypeDTO>();

            var contactSingleAttributes = new Dictionary <int, ObjectSingleAttributeDTO>
            {
                { 1, new ObjectSingleAttributeDTO
                  {
                      Value = new AttributeDTO
                      {
                          AttributeId = 23,
                          Category    = "Allergies",
                          Name        = "All Allergies"
                      },
                      Notes = _updatedNote
                  } }
            };

            var configuration = MpObjectAttributeConfigurationFactory.Contact();

            _contactAttributeService.Setup(x => x.GetCurrentObjectAttributes(_fakeToken, _fakeContactId, configuration, null)).Returns(_currentAttributes);
            _apiUserService.Setup(x => x.GetToken()).Returns(_fakeToken);
            _contactAttributeService.Setup(x => x.UpdateAttribute(_fakeToken, It.IsAny <MpObjectAttribute>(), configuration)).Callback <string, MpObjectAttribute, MpObjectAttributeConfiguration>((id, actual, objectConfiguration) =>
            {
                Assert.AreEqual(actual.Notes, _updatedNote);
                Assert.AreEqual(actual.ObjectAttributeId, 123456);
                Assert.AreEqual(configuration, objectConfiguration);
            });
            _fixture.SaveObjectAttributes(_fakeContactId, contactAttributes, contactSingleAttributes, configuration);
            _apiUserService.VerifyAll();
            _attributeService.VerifyAll();
            _mpAttributeService.VerifyAll();
            _contactAttributeService.Verify(update => update.UpdateAttribute(_fakeToken, It.IsAny <MpObjectAttribute>(), It.IsAny <MpObjectAttributeConfiguration>()), Times.Once);
        }
예제 #2
0
        /// <summary>
        /// Gets a list of groups with group attributes for either the logged in user or a participant you pass in.
        /// </summary>
        /// <param name="token"></param>
        /// <param name="participantId">if null we load the calling user's participant record</param>
        /// <param name="groupTypeId"></param>
        /// <param name="groupId"></param>
        /// <returns></returns>
        public List <GroupDTO> GetGroupsByTypeOrId(string token, int?participantId = null, int[] groupTypeIds = null, int?groupId = null, bool?withParticipants = true, bool?withAttributes = true)
        {
            if (participantId == null)
            {
                participantId = _participantService.GetParticipantRecord(token).ParticipantId;
            }
            var groupsByType = _mpGroupRepository.GetGroupsForParticipantByTypeOrID(participantId.Value, null, groupTypeIds, groupId);

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

            var groupDetail = groupsByType.Select(Mapper.Map <MpGroup, GroupDTO>).ToList();

            if (withAttributes == true)
            {
                var configuration = MpObjectAttributeConfigurationFactory.Group();
                var mpAttributes  = _attributeRepository.GetAttributes(null);
                foreach (var group in groupDetail)
                {
                    var attributesTypes = _objectAttributeService.GetObjectAttributes(token, group.GroupId, configuration, mpAttributes);
                    group.AttributeTypes   = attributesTypes.MultiSelect;
                    group.SingleAttributes = attributesTypes.SingleSelect;
                }
            }
            if (withParticipants == true)
            {
                GetGroupParticipants(groupDetail);
            }

            return(groupDetail);
        }
예제 #3
0
        public GroupDTO CreateGroup(GroupDTO group)
        {
            try
            {
                var mpGroup = Mapper.Map <MpGroup>(group);

                if (group.AttributeTypes.ContainsKey(_groupCategoryAttributeTypeId) && group.AttributeTypes[90].Attributes.Any(a => a.AttributeId == 0))
                {
                    var categoryAttributes = Mapper.Map <List <MpAttribute> >(group.AttributeTypes[90].Attributes);

                    categoryAttributes = _attributeService.CreateMissingAttributes(categoryAttributes, _groupCategoryAttributeTypeId);
                    group.AttributeTypes[_groupCategoryAttributeTypeId].Attributes = Mapper.Map <List <ObjectAttributeDTO> >(categoryAttributes);
                }

                group.GroupId = _mpGroupRepository.CreateGroup(mpGroup);
                //save group attributes
                var configuration = MpObjectAttributeConfigurationFactory.Group();
                _objectAttributeService.SaveObjectAttributes(group.GroupId, group.AttributeTypes, group.SingleAttributes, configuration);

                if (group.MinorAgeGroupsAdded)
                {
                    _mpGroupRepository.SendNewStudentMinistryGroupAlertEmail((List <MpGroupParticipant>)mpGroup.Participants);
                }
            }
            catch (Exception e)
            {
                var message = String.Format("Could not create group {0}", group.GroupName);
                _logger.Error(message, e);
                throw (new ApplicationException(message, e));
            }

            return(group);
        }
        public void GetObjectAttributes()
        {
            const int contactId = 123456;

            //mock GetSubpageViewRecords
            var getSubpageViewRecordsResponse = new List <Dictionary <string, object> >
            {
                new Dictionary <string, object>()
                {
                    { "Contact_Attribute_ID", 1 },
                    { "Start_Date", "10/10/2014" },
                    { "End_Date", null },
                    { "Notes", "These are my notes" },
                    { "Attribute_ID", 2 },
                    { "Attribute_Type_ID", 3 },
                    { "Attribute_Type", "AttributeType #1" }
                },
                new Dictionary <string, object>()
                {
                    { "Contact_Attribute_ID", 4 },
                    { "Start_Date", "11/11/2015" },
                    { "End_Date", null },
                    { "Notes", "" },
                    { "Attribute_ID", 5 },
                    { "Attribute_Type_ID", 6 },
                    { "Attribute_Type", "AttributeType #2" }
                }
            };

            _ministryPlatformService.Setup(
                mocked =>
                mocked.GetSubpageViewRecords(It.IsAny <int>(), contactId, It.IsAny <string>(), "", "", 0))
            .Returns(getSubpageViewRecordsResponse);

            var configuration = MpObjectAttributeConfigurationFactory.Contact();
            var attributes    = _fixture.GetCurrentObjectAttributes("fakeToken", contactId, configuration, null).ToList();

            _ministryPlatformService.VerifyAll();

            Assert.IsNotNull(attributes);
            Assert.AreEqual(2, attributes.Count());

            var attribute = attributes[0];

            Assert.AreEqual(1, attribute.ObjectAttributeId);
            Assert.AreEqual(new DateTime(2014, 10, 10), attribute.StartDate);
            Assert.AreEqual(null, attribute.EndDate);
            Assert.AreEqual("These are my notes", attribute.Notes);
            Assert.AreEqual(2, attribute.AttributeId);
            Assert.AreEqual(3, attribute.AttributeTypeId);

            attribute = attributes[1];
            Assert.AreEqual(4, attribute.ObjectAttributeId);
            Assert.AreEqual(new DateTime(2015, 11, 11), attribute.StartDate);
            Assert.AreEqual(null, attribute.EndDate);
            Assert.AreEqual(string.Empty, attribute.Notes);
            Assert.AreEqual(5, attribute.AttributeId);
            Assert.AreEqual(6, attribute.AttributeTypeId);
        }
 public IHttpActionResult Post(int contactId, [FromBody] ObjectAttributeDTO objectAttribute)
 {
     return(Authorized(token =>
     {
         var configuration = MpObjectAttributeConfigurationFactory.MyContact();
         _objectAttributeService.SaveObjectMultiAttribute(token, contactId, objectAttribute, configuration);
         return this.Ok();
     }));
 }
예제 #6
0
        private ObjectAttributeTypeDTO ContactSkills(string token, string apiToken)
        {
            var contact         = _contactService.GetMyProfile(token);
            var configuration   = MpObjectAttributeConfigurationFactory.Contact();
            var attributesTypes = _objectAttributeService.GetObjectAttributes(apiToken, contact.Contact_ID, configuration);
            ObjectAttributeTypeDTO contactSkills;
            var skillsAttributeTypeId = _configurationWrapper.GetConfigIntValue("AttributeTypeIdSkills");

            attributesTypes.MultiSelect.TryGetValue(skillsAttributeTypeId, out contactSkills);
            return(contactSkills);
        }
예제 #7
0
        public CampReservationDTO GetCamperInfo(string token, int eventId, int contactId)
        {
            var loggedInContact = _contactRepository.GetMyProfile(token);
            var family          = _contactRepository.GetHouseholdFamilyMembers(loggedInContact.Household_ID);

            family.AddRange(_contactRepository.GetOtherHouseholdMembers(loggedInContact.Household_ID));

            if (family.Where(f => f.ContactId == contactId).ToList().Count <= 0)
            {
                return(null);
            }
            var camperContact = _contactRepository.GetContactById(contactId);

            var apiToken = _apiUserRepository.GetToken();

            // get camper grade if they have one
            var groupResult = _groupRepository.GetGradeGroupForContact(contactId, apiToken);

            var campFormId = _configurationWrapper.GetConfigIntValue("SummerCampFormID");
            var nextYearSchoolFormFieldId = _configurationWrapper.GetConfigIntValue("SummerCampForm.SchoolAttendingNextYear");
            var nextYearSchool            = _formSubmissionRepository.GetFormResponseAnswer(campFormId, camperContact.Contact_ID, nextYearSchoolFormFieldId, eventId);

            var preferredRoommateFieldId = _configurationWrapper.GetConfigIntValue("SummerCampForm.PreferredRoommate");
            var preferredRoommate        = _formSubmissionRepository.GetFormResponseAnswer(campFormId, camperContact.Contact_ID, preferredRoommateFieldId, eventId);
            var crossroadsSiteFieldId    = _configurationWrapper.GetConfigIntValue("SummerCampForm.CamperCongregation");
            var crossroadsSite           = _formSubmissionRepository.GetFormResponseAnswer(campFormId, camperContact.Contact_ID, crossroadsSiteFieldId, eventId);

            var congregation = (string.IsNullOrEmpty(crossroadsSite))
                ? new Err <MpCongregation>("Congregation not set")
                : _congregationRepository.GetCongregationByName(crossroadsSite, apiToken);
            var configuration   = MpObjectAttributeConfigurationFactory.Contact();
            var attributesTypes = _objectAttributeService.GetObjectAttributes(apiToken, contactId, configuration);

            return(new CampReservationDTO
            {
                ContactId = camperContact.Contact_ID,
                FirstName = camperContact.First_Name,
                LastName = camperContact.Last_Name,
                MiddleName = camperContact.Middle_Name,
                PreferredName = camperContact.Nickname,
                MobilePhone = camperContact.Mobile_Phone,
                CrossroadsSite = congregation.Status ? congregation.Value.CongregationId : 0,
                BirthDate = Convert.ToString(camperContact.Date_Of_Birth),
                SchoolAttending = camperContact.Current_School,
                SchoolAttendingNext = nextYearSchool,
                Gender = Convert.ToInt32(camperContact.Gender_ID),
                CurrentGrade = groupResult.Status ? groupResult.Value.GroupId : 0,
                RoomMate = preferredRoommate,
                AttributeTypes = attributesTypes.MultiSelect,
                SingleAttributes = attributesTypes.SingleSelect
            });
        }
예제 #8
0
        public void UpdateSkills(int participantId, List <GoSkills> skills, string token)
        {
            MpObjectAttributeConfiguration configuration;

            if (token == String.Empty)
            {
                token         = _apiUserService.GetToken();
                configuration = MpObjectAttributeConfigurationFactory.Contact();
            }
            else
            {
                configuration = MpObjectAttributeConfigurationFactory.MyContact();
            }

            var contactObs = Observable.Start(() => _contactService.GetContactByParticipantId(participantId));

            contactObs.Subscribe(con =>
            {
                var attrs = Observable.Start(() => _objectAttributeService.GetObjectAttributes(token, con.Contact_ID, configuration));

                attrs.Subscribe(attr =>
                {
                    var curSk = attr.MultiSelect
                                .FirstOrDefault(kvp => kvp.Value.AttributeTypeId == _configurationWrapper.GetConfigIntValue("AttributeTypeIdSkills")).Value.Attributes
                                .Where(attribute => attribute.Selected).ToList();

                    var skillsEndDate = SkillsToEndDate(skills, curSk).Select(sk =>
                    {
                        sk.EndDate = DateTime.Now;
                        return(sk);
                    });

                    var addSkills    = SkillsToAdd(skills, curSk).ToList();
                    var allSkills    = addSkills.Concat(skillsEndDate).ToList();
                    var allSkillsObs = allSkills.ToObservable();
                    try
                    {
                        allSkillsObs.ForEachAsync(skill =>
                        {
                            _objectAttributeService.SaveObjectMultiAttribute(token, con.Contact_ID, skill, configuration, true);
                        });
                    }
                    catch (Exception e)
                    {
                        throw new ApplicationException("Updating skills caused an error");
                    }
                });
            });
        }
예제 #9
0
        public void SetProfile(string token, Person person)
        {
            var contactDictionary = getDictionary(person.GetContact());
            var householdDictionary = getDictionary(person.GetHousehold());
            var addressDictionary = getDictionary(person.GetAddress());
            addressDictionary.Add("State/Region", addressDictionary["State"]);

            // Some front-end consumers require an Address (e.g., /profile/personal), and
            // some do not (e.g., /undivided/facilitator).  Don't attempt to create/update
            // an Address record if we have no data.
            if (addressDictionary.Values.All(i => i == null))
            {
                addressDictionary = null;
            }

            _contactRepository.UpdateContact(person.ContactId, contactDictionary, householdDictionary, addressDictionary);
            var configuration = MpObjectAttributeConfigurationFactory.Contact();            
            _objectAttributeService.SaveObjectAttributes(person.ContactId, person.AttributeTypes, person.SingleAttributes, configuration);

            var participant = _participantService.GetParticipant(person.ContactId);
            if (participant.AttendanceStart != person.AttendanceStartDate)
            {                
                participant.AttendanceStart = person.AttendanceStartDate;
                _participantService.UpdateParticipant(participant);
            }

            // TODO: It appears we are updating the contact records email address above if the email address is changed
            // TODO: If the password is invalid we would not run the update on user, and therefore create a data integrity problem
            // TODO: See About moving the check for new password above or moving the update for user / person into an atomic operation
            //
            // update the user values if the email and/or password has changed
            if (!(String.IsNullOrEmpty(person.NewPassword)) || (person.EmailAddress != person.OldEmail && person.OldEmail != null))
            {
                var authData = _authenticationService.Authenticate(person.OldEmail, person.OldPassword);

                if (authData == null)
                {
                    throw new Exception("Old password did not match profile");
                }
                else
                {
                    var userUpdateValues = person.GetUserUpdateValues();
                    userUpdateValues["User_ID"] = _userRepository.GetUserIdByUsername(person.OldEmail);
                    _userRepository.UpdateUser(userUpdateValues);
                }
            }
        }
예제 #10
0
        public Person GetPerson(int contactId)
        {
            var contact = _contactRepository.GetContactById(contactId);
            var person = Mapper.Map<Person>(contact);

            var family = _contactRepository.GetHouseholdFamilyMembers(person.HouseholdId);
            person.HouseholdMembers = family;

            // TODO: Should this move to _contactService or should update move it's call out to this service?
            var apiUser = _apiUserService.GetToken();
            var configuration = MpObjectAttributeConfigurationFactory.Contact();
            var attributesTypes = _objectAttributeService.GetObjectAttributes(apiUser, contactId, configuration);
            person.AttributeTypes = attributesTypes.MultiSelect;
            person.SingleAttributes = attributesTypes.SingleSelect;

            return person;
        }
예제 #11
0
        public void addParticipantToGroupNoEvents(int groupId, ParticipantSignup participant)
        {
            MpGroup group;

            try
            {
                group = _mpGroupRepository.getGroupDetails(groupId);
            }
            catch (Exception e)
            {
                var message = String.Format("Could not retrieve group details for group {0}: {1}", groupId, e.Message);
                _logger.Error(message, e);
                throw (new ApplicationException(message, e));
            }

            checkSpaceRemaining(new List <ParticipantSignup> {
                participant
            }, group);

            try
            {
                var roleId = participant.groupRoleId ?? _groupRoleDefaultId;

                var participantId      = participant.particpantId.Value;
                var groupParticipantId = _mpGroupRepository.addParticipantToGroup(participantId,
                                                                                  Convert.ToInt32(groupId),
                                                                                  roleId,
                                                                                  participant.childCareNeeded,
                                                                                  DateTime.Now,
                                                                                  null, false, participant.EnrolledBy);

                var configuration = MpObjectAttributeConfigurationFactory.GroupParticipant();
                _objectAttributeService.SaveObjectAttributes(groupParticipantId, participant.AttributeTypes, participant.SingleAttributes, configuration);

                if (participant.capacityNeeded > 0)
                {
                    DecrementCapacity(participant.capacityNeeded, group);
                }
            }
            catch (Exception e)
            {
                _logger.Error("Could not add user to group", e);
                throw;
            }
        }
예제 #12
0
        public void SetProfile(String token, Person person)
        {
            var contactDictionary   = getDictionary(person.GetContact());
            var householdDictionary = getDictionary(person.GetHousehold());
            var addressDictionary   = getDictionary(person.GetAddress());

            addressDictionary.Add("State/Region", addressDictionary["State"]);
            _contactService.UpdateContact(person.ContactId, contactDictionary, householdDictionary, addressDictionary);

            var configuration = MpObjectAttributeConfigurationFactory.Contact();

            _objectAttributeService.SaveObjectAttributes(person.ContactId, person.AttributeTypes, person.SingleAttributes, configuration);

            var participant = _participantService.GetParticipant(person.ContactId);

            if (participant.AttendanceStart != person.AttendanceStartDate)
            {
                participant.AttendanceStart = person.AttendanceStartDate;
                _participantService.UpdateParticipant(participant);
            }

            // TODO: It appears we are updating the contact records email address above if the email address is changed
            // TODO: If the password is invalid we would not run the update on user, and therefore create a data integrity problem
            // TODO: See About moving the check for new password above or moving the update for user / person into an atomic operation
            //
            // update the user values if the email and/or password has changed
            if (!(String.IsNullOrEmpty(person.NewPassword)) || (person.EmailAddress != person.OldEmail && person.OldEmail != null))
            {
                var authData = TranslationService.Login(person.OldEmail, person.OldPassword);

                if (authData == null)
                {
                    throw new Exception("Old password did not match profile");
                }
                else
                {
                    var userUpdateValues = person.GetUserUpdateValues();
                    userUpdateValues["User_ID"] = _userService.GetUserIdByUsername(person.OldEmail);
                    _userService.UpdateUser(userUpdateValues);
                }
            }
        }
예제 #13
0
        public bool ParticipantGroupHasStudents(string token, int participantId, int groupParticipantId)
        {
            var groups  = GetGroupsForParticipant(token, participantId);
            var groupId = 0;

            foreach (var group in groups)
            {
                var participants = LoadGroupParticipants(group.GroupId, token);
                if (participants.Exists(x => x.GroupParticipantId == groupParticipantId))
                {
                    groupId = group.GroupId;
                    break;
                }
            }
            var configuration = MpObjectAttributeConfigurationFactory.Group();
            var attributes    = _objectAttributeRepository.GetCurrentObjectAttributes(token, groupId, configuration);

            return(attributes.Find(x => x.AttributeId == GroupHasMiddleSchoolStudents ||
                                   x.AttributeId == GroupHasHighSchoolStudents) != null
                                        ?true:false);
        }
예제 #14
0
        private void GetGroupAttributes(string token, List <GroupDTO> groups)
        {
            var configuration = MpObjectAttributeConfigurationFactory.Group();

            foreach (var attributeType in new[] { _groupCategoryAttributeTypeId, _groupTypeAttributeTypeId, _groupAgeRangeAttributeTypeId })
            {
                var types = _attributeRepository.GetAttributes(attributeType);
                foreach (var group in groups)
                {
                    var attributesTypes = _objectAttributeService.GetObjectAttributes(token, group.GroupId, configuration, types);
                    foreach (var multi in attributesTypes.MultiSelect)
                    {
                        group.AttributeTypes.Add(multi.Key, multi.Value);
                    }
                    foreach (var single in attributesTypes.SingleSelect)
                    {
                        group.SingleAttributes.Add(single.Key, single.Value);
                    }
                }
            }
        }
예제 #15
0
        public GroupDTO UpdateGroup(GroupDTO group)
        {
            try
            {
                var mpGroup = Mapper.Map <MpGroup>(group);
                _mpGroupRepository.UpdateGroup(mpGroup);

                List <MpGroupParticipant> groupParticipants = _mpGroupRepository.GetGroupParticipants(group.GroupId, true);

                if (groupParticipants.Count(participant => participant.StartDate < group.StartDate) > 0)
                {
                    UpdateGroupParticipantStartDate(groupParticipants.Where(part => part.StartDate < group.StartDate).ToList(), group.StartDate);
                }

                if (group.AttributeTypes.ContainsKey(_groupCategoryAttributeTypeId) && group.AttributeTypes[90].Attributes.Any(a => a.AttributeId == 0))
                {
                    var categoryAttributes = Mapper.Map <List <MpAttribute> >(group.AttributeTypes[90].Attributes);

                    categoryAttributes = _attributeService.CreateMissingAttributes(categoryAttributes, _groupCategoryAttributeTypeId);
                    group.AttributeTypes[_groupCategoryAttributeTypeId].Attributes = Mapper.Map <List <ObjectAttributeDTO> >(categoryAttributes);
                }

                var configuration = MpObjectAttributeConfigurationFactory.Group();
                _objectAttributeService.SaveObjectAttributes(group.GroupId, group.AttributeTypes, group.SingleAttributes, configuration);

                if (group.MinorAgeGroupsAdded)
                {
                    var leaders = groupParticipants.Where(p => p.GroupRoleId == _groupRoleLeader).ToList();
                    _mpGroupRepository.SendNewStudentMinistryGroupAlertEmail(leaders);
                }
            }
            catch (Exception e)
            {
                var message = String.Format("Could not update group {0}", group.GroupName);
                _logger.Error(message, e);
                throw (new ApplicationException(message, e));
            }

            return(group);
        }
예제 #16
0
        public List <GroupDTO> GetGroupsForParticipant(string token, int participantId)
        {
            var groups = _mpGroupRepository.GetGroupsForParticipant(token, participantId);

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

            var groupDetail   = groups.Select(Mapper.Map <MpGroup, GroupDTO>).ToList();
            var configuration = MpObjectAttributeConfigurationFactory.Group();
            var mpAttributes  = _attributeRepository.GetAttributes(null);

            foreach (var group in groupDetail)
            {
                var attributesTypes = _objectAttributeService.GetObjectAttributes(token, group.GroupId, configuration, mpAttributes);
                group.AttributeTypes   = attributesTypes.MultiSelect;
                group.SingleAttributes = attributesTypes.SingleSelect;
            }

            return(groupDetail);
        }
예제 #17
0
        public List <GroupParticipantDTO> GetGroupParticipants(int groupId, bool active = true)
        {
            var groupParticipants = _mpGroupRepository.GetGroupParticipants(groupId, active);

            if (groupParticipants == null)
            {
                return(null);
            }
            var participants = groupParticipants.Select(Mapper.Map <MpGroupParticipant, GroupParticipantDTO>).ToList();

            var configuration = MpObjectAttributeConfigurationFactory.GroupParticipant();

            var apiToken = _apiUserService.GetToken();

            foreach (var participant in participants)
            {
                var attributesTypes = _objectAttributeService.GetObjectAttributes(apiToken, participant.GroupParticipantId, configuration);
                participant.AttributeTypes   = attributesTypes.MultiSelect;
                participant.SingleAttributes = attributesTypes.SingleSelect;
            }

            return(participants);
        }
예제 #18
0
        public IHttpActionResult GetGroupAttributes([FromUri] int groupId)
        {
            //var filter = new List<MpAttribute>
            //{
            //    new MpAttribute
            //    {
            //        AttributeTypeId = 90
            //    }
            //};
            var filter = _attributeRepository.GetAttributes(90);

            return(Authorized(token =>
            {
                var result = _objectAttributeService.GetObjectAttributes(token, groupId, MpObjectAttributeConfigurationFactory.Group(), filter);
                return Ok(result);
            }));
        }
예제 #19
0
        public void addParticipantsToGroup(int groupId, List <ParticipantSignup> participants)
        {
            MpGroup group;

            try
            {
                group = _mpGroupService.getGroupDetails(groupId);
            }
            catch (Exception e)
            {
                var message = String.Format("Could not retrieve group details for group {0}: {1}", groupId, e.Message);
                _logger.Error(message, e);
                throw (new ApplicationException(message, e));
            }

            checkSpaceRemaining(participants, group);

            try
            {
                foreach (var participant in participants)
                {
                    int groupParticipantId;

                    var roleId = participant.groupRoleId ?? _groupRoleDefaultId;

                    var participantId = participant.particpantId.Value;
                    groupParticipantId = _mpGroupService.addParticipantToGroup(participantId,
                                                                               Convert.ToInt32(groupId),
                                                                               roleId,
                                                                               participant.childCareNeeded,
                                                                               DateTime.Now);

                    var configuration = MpObjectAttributeConfigurationFactory.GroupParticipant();
                    _objectAttributeService.SaveObjectAttributes(groupParticipantId, participant.AttributeTypes, participant.SingleAttributes, configuration);

                    if (participant.capacityNeeded > 0)
                    {
                        DecrementCapacity(participant.capacityNeeded, group);
                    }

                    _logger.Debug("Added user - group/participant id = " + groupParticipantId);

                    // Now see what future events are scheduled for this group, and register the user for those
                    var events = _mpGroupService.getAllEventsForGroup(Convert.ToInt32(groupId));
                    _logger.Debug("Scheduled events for this group: " + events);
                    if (events != null && events.Count > 0)
                    {
                        foreach (var e in events.Where(x => x.EventType != "Childcare"))
                        {
                            _eventService.RegisterParticipantForEvent(participantId, e.EventId, groupId, groupParticipantId);
                            _logger.Debug("Added participant " + participant + " to group event " + e.EventId);
                        }
                    }

                    if (participant.SendConfirmationEmail)
                    {
                        var waitlist = group.GroupType == _configurationWrapper.GetConfigIntValue("GroupType_Waitlist");
                        _mpGroupService.SendCommunityGroupConfirmationEmail(participantId, groupId, waitlist, participant.childCareNeeded);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error("Could not add user to group", e);
                throw;
            }
        }
예제 #20
0
        public void GetObjectAttributes()
        {
            const int contactId = 123456;

            //mock MpRestSearch
            var mockResponse = new List <MpObjectAttribute>
            {
                new MpObjectAttribute()
                {
                    EndDate           = null,
                    Notes             = "These are my notes",
                    ObjectAttributeId = 1,
                    StartDate         = new DateTime(2014, 10, 10),
                    AttributeId       = 2,
                    AttributeTypeId   = 3,
                    AttributeTypeName = "AttributeType #1"
                },
                new MpObjectAttribute()
                {
                    ObjectAttributeId = 4,
                    StartDate         = new DateTime(2015, 11, 11),
                    EndDate           = null,
                    Notes             = "",
                    AttributeId       = 5,
                    AttributeTypeId   = 6,
                    AttributeTypeName = "AttributeType #2"
                }
            };

            _ministryPlatformRest.Setup(m => m.UsingAuthenticationToken("fakeToken")).Returns(_ministryPlatformRest.Object);

            _ministryPlatformRest.Setup(m => m.SearchTable <MpObjectAttribute>("Contact_Attributes", It.IsAny <String>(), It.IsAny <String>(), (string)null, false))
            .Returns(mockResponse);



            var configuration = MpObjectAttributeConfigurationFactory.Contact();
            var attributes    = _fixture.GetCurrentObjectAttributes("fakeToken", contactId, configuration, null);

            _ministryPlatformRest.VerifyAll();

            Assert.IsNotNull(attributes);
            Assert.AreEqual(2, attributes.Count());

            var attribute = attributes[0];

            Assert.AreEqual(1, attribute.ObjectAttributeId);
            Assert.AreEqual(new DateTime(2014, 10, 10), attribute.StartDate);
            Assert.AreEqual(null, attribute.EndDate);
            Assert.AreEqual("These are my notes", attribute.Notes);
            Assert.AreEqual(2, attribute.AttributeId);
            Assert.AreEqual(3, attribute.AttributeTypeId);

            attribute = attributes[1];
            Assert.AreEqual(4, attribute.ObjectAttributeId);
            Assert.AreEqual(new DateTime(2015, 11, 11), attribute.StartDate);
            Assert.AreEqual(null, attribute.EndDate);
            Assert.AreEqual(string.Empty, attribute.Notes);
            Assert.AreEqual(5, attribute.AttributeId);
            Assert.AreEqual(6, attribute.AttributeTypeId);
        }
예제 #21
0
        public GroupDTO getGroupDetails(int groupId, int contactId, MpParticipant participant, string authUserToken)
        {
            int     participantId = participant.ParticipantId;
            MpGroup g             = _mpGroupRepository.getGroupDetails(groupId);

            var signupRelations = _mpGroupRepository.GetGroupSignupRelations(g.GroupType);

            var currRelationships = _contactRelationshipService.GetMyCurrentRelationships(contactId, authUserToken);

            var events = _mpGroupRepository.getAllEventsForGroup(groupId);

            MpContactRelationship[] familyToReturn = null;

            if (currRelationships != null)
            {
                familyToReturn = currRelationships.Where(
                    c => signupRelations.Select(s => s.RelationshipId).Contains(c.Relationship_Id)).ToArray();
            }

            var apiToken        = _apiUserService.GetToken();
            var configuration   = MpObjectAttributeConfigurationFactory.Group();
            var attributesTypes = _objectAttributeService.GetObjectAttributes(apiToken, groupId, configuration);

            var detail = new GroupDTO();

            {
                detail.ContactId            = g.ContactId;
                detail.CongregationId       = g.CongregationId;
                detail.KidsWelcome          = g.KidsWelcome;
                detail.GroupName            = g.Name;
                detail.GroupDescription     = g.GroupDescription;
                detail.GroupId              = g.GroupId;
                detail.GroupFullInd         = g.Full;
                detail.WaitListInd          = g.WaitList ?? false;
                detail.ChildCareAvailable   = g.ChildCareAvailable;
                detail.WaitListGroupId      = g.WaitListGroupId;
                detail.OnlineRsvpMinimumAge = g.MinimumAge;
                detail.MeetingFrequencyID   = g.MeetingFrequencyID;
                detail.AvailableOnline      = g.AvailableOnline;
                detail.MeetingTime          = g.MeetingTime;
                detail.MeetingDayId         = g.MeetingDayId;
                detail.Address              = Mapper.Map <MpAddress, AddressDTO>(g.Address);
                detail.StartDate            = g.StartDate;
                detail.Participants         = (g.Participants.Count > 0) ? g.Participants.Select(p => Mapper.Map <MpGroupParticipant, GroupParticipantDTO>(p)).ToList() : null;

                if (events != null)
                {
                    detail.Events = events.Select(Mapper.Map <MpEvent, Event>).ToList();
                }
                //the first instance of family must always be the logged in user
                var fam = new SignUpFamilyMembers
                {
                    EmailAddress    = participant.EmailAddress,
                    PreferredName   = participant.PreferredName,
                    UserInGroup     = _mpGroupRepository.checkIfUserInGroup(participantId, g.Participants),
                    ParticpantId    = participantId,
                    ChildCareNeeded = false
                };
                detail.SignUpFamilyMembers = new List <SignUpFamilyMembers> {
                    fam
                };

                if (familyToReturn != null)
                {
                    foreach (var f in familyToReturn)
                    {
                        var fm = new SignUpFamilyMembers
                        {
                            EmailAddress  = f.Email_Address,
                            PreferredName = f.Preferred_Name,
                            UserInGroup   = _mpGroupRepository.checkIfUserInGroup(f.Participant_Id, g.Participants),
                            ParticpantId  = f.Participant_Id,
                        };
                        detail.SignUpFamilyMembers.Add(fm);
                    }
                }

                detail.AttributeTypes   = attributesTypes.MultiSelect;
                detail.SingleAttributes = attributesTypes.SingleSelect;
            }

            return(detail);
        }
예제 #22
0
        public void addParticipantsToGroup(int groupId, List <ParticipantSignup> participants)
        {
            MpGroup group;

            try
            {
                group = _mpGroupRepository.getGroupDetails(groupId);
            }
            catch (Exception e)
            {
                var message = String.Format("Could not retrieve group details for group {0}: {1}", groupId, e.Message);
                _logger.Error(message, e);
                throw (new ApplicationException(message, e));
            }

            checkSpaceRemaining(participants, group);

            try
            {
                foreach (var participant in participants)
                {
                    var roleId = participant.groupRoleId ?? _groupRoleDefaultId;

                    var participantId = participant.particpantId.Value;

                    int groupParticipantId = _mpGroupRepository.GetParticipantGroupMemberId(Convert.ToInt32(groupId), participantId);

                    if (groupParticipantId < 0)
                    {
                        groupParticipantId = _mpGroupRepository.addParticipantToGroup(participantId,
                                                                                      Convert.ToInt32(groupId),
                                                                                      roleId,
                                                                                      participant.childCareNeeded,
                                                                                      DateTime.Now);

                        var configuration = MpObjectAttributeConfigurationFactory.GroupParticipant();
                        _objectAttributeService.SaveObjectAttributes(groupParticipantId, participant.AttributeTypes, participant.SingleAttributes, configuration);

                        if (participant.capacityNeeded > 0)
                        {
                            DecrementCapacity(participant.capacityNeeded, group);
                        }

                        _logger.Debug("Added user - group/participant id = " + groupParticipantId);
                    }
                    else
                    {
                        _logger.Debug("User " + participantId + " was already a member of group " + groupId);
                    }

                    var events = _mpGroupRepository.getAllEventsForGroup(Convert.ToInt32(groupId), _dateTimeWrapper.Today);
                    _logger.Debug("Scheduled events for this group: " + events);
                    if (events != null && events.Count > 0)
                    {
                        foreach (var e in events.Where(x => x.EventType != (Convert.ToString(_childcareEventTypeId))))
                        {
                            //SafeRegisterParticipant will not register again if they are already registered
                            _eventService.SafeRegisterParticipant(e.EventId, participantId, groupId, groupParticipantId);
                            _logger.Debug("Added participant " + participant + " to group event " + e.EventId);
                        }
                    }

                    if (participant.SendConfirmationEmail)
                    {
                        var waitlist = group.GroupType == _configurationWrapper.GetConfigIntValue("GroupType_Waitlist");
                        _mpGroupRepository.SendCommunityGroupConfirmationEmail(participantId, groupId, waitlist, participant.childCareNeeded);
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error("Could not add user to group", e);
                throw;
            }
        }
예제 #23
0
        public CampReservationDTO SaveCampReservation(CampReservationDTO campReservation, int eventId, string token)
        {
            var nickName  = string.IsNullOrWhiteSpace(campReservation.PreferredName) ? campReservation.FirstName : campReservation.PreferredName;
            var contactId = Convert.ToInt32(campReservation.ContactId);

            var minorContact = new MpContact
            {
                FirstName           = campReservation.FirstName,
                LastName            = campReservation.LastName,
                PreferredName       = $"{campReservation.LastName}, {campReservation.FirstName}",
                MiddleName          = campReservation.MiddleName,
                MobilePhone         = campReservation.MobilePhone,
                BirthDate           = Convert.ToDateTime(campReservation.BirthDate),
                Gender              = campReservation.Gender,
                Nickname            = nickName,
                SchoolAttending     = campReservation.SchoolAttending,
                HouseholdId         = (_contactRepository.GetMyProfile(token)).Household_ID,
                HouseholdPositionId = 2
            };

            MpParticipant participant;

            if (campReservation.ContactId == null || campReservation.ContactId == 0)
            {
                var newMinorContact = _contactRepository.CreateContact(minorContact);
                contactId   = newMinorContact[0].RecordId;
                participant = _participantRepository.GetParticipant(contactId);
                campReservation.ContactId = contactId;
            }
            else
            {
                var updateToDictionary = new Dictionary <String, Object>
                {
                    { "Contact_ID", Convert.ToInt32(campReservation.ContactId) },
                    { "First_Name", minorContact.FirstName },
                    { "Last_Name", minorContact.LastName },
                    { "Middle_Name", minorContact.MiddleName },
                    { "Nickname", nickName },
                    { "Mobile_Phone", minorContact.MobilePhone },
                    { "Gender_ID", campReservation.Gender },
                    { "Date_Of_Birth", minorContact.BirthDate },
                    { "Current_School", minorContact.SchoolAttending },
                    { "Congregation_Name", (_congregationRepository.GetCongregationById(campReservation.CrossroadsSite)).Name }
                };

                _contactRepository.UpdateContact(Convert.ToInt32(campReservation.ContactId), updateToDictionary);
                participant = _participantRepository.GetParticipant(Convert.ToInt32(campReservation.ContactId));
            }

            // Save shirt size if set
            var configuration = MpObjectAttributeConfigurationFactory.Contact();

            _objectAttributeService.SaveObjectAttributes(contactId, campReservation.AttributeTypes, campReservation.SingleAttributes, configuration);

            // Save students in selected grade group
            var group = _groupRepository.GetGradeGroupForContact(contactId, _apiUserRepository.GetToken());

            if (group.Status && group.Value.GroupId != campReservation.CurrentGrade)
            {
                _groupRepository.endDateGroupParticipant(group.Value.GroupParticipantId, group.Value.GroupId, DateTime.Now);
                _groupRepository.addParticipantToGroup(participant.ParticipantId,
                                                       campReservation.CurrentGrade,
                                                       _configurationWrapper.GetConfigIntValue("Group_Role_Default_ID"),
                                                       false,
                                                       DateTime.Now);
            }
            else if (!group.Status)
            {
                _groupRepository.addParticipantToGroup(participant.ParticipantId,
                                                       campReservation.CurrentGrade,
                                                       _configurationWrapper.GetConfigIntValue("Group_Role_Default_ID"),
                                                       false,
                                                       DateTime.Now);
            }

            // Check if this person is already an event participant
            var eventParticipant = _eventParticipantRepository.GetEventParticipantEligibility(eventId, contactId);
            var currentlyActive  = (eventParticipant != null && (eventParticipant.EndDate == null || eventParticipant.EndDate >= DateTime.Now));
            var rulesPass        = true;

            if (!currentlyActive)
            {
                rulesPass = _campRules.VerifyCampRules(eventId, campReservation.Gender);
            }

            // ALL OF THE BELOW CODE SHOULD ONLY HAPPEN IF THE RULES PASS
            if (rulesPass)
            {
                //Create eventParticipant
                int eventParticipantId;

                // This is a new event participant, determine their pending timeout and create their entry in the database
                if (eventParticipant == null)
                {
                    var endDate = DetermineEndDate(eventId);
                    eventParticipantId = _eventRepository.RegisterInterestedParticipantWithEndDate(participant.ParticipantId, eventId, endDate);
                }
                else
                {
                    eventParticipantId = eventParticipant.EventParticipantId;

                    // If the participant had previously started an application which expired, update its End Date now
                    if (eventParticipant.EndDate != null && eventParticipant.EndDate < DateTime.Now)
                    {
                        var endDate = DetermineEndDate(eventId);
                        _eventRepository.UpdateParticipantEndDate(eventParticipantId, endDate);
                    }
                }
                var crossroadsSite = _congregationRepository.GetCongregationById(campReservation.CrossroadsSite);

                //form response
                var answers = new List <MpFormAnswer>
                {
                    new MpFormAnswer
                    {
                        Response           = campReservation.SchoolAttendingNext,
                        FieldId            = _configurationWrapper.GetConfigIntValue("SummerCampForm.SchoolAttendingNextYear"),
                        EventParticipantId = eventParticipantId
                    },
                    new MpFormAnswer
                    {
                        Response           = campReservation.RoomMate,
                        FieldId            = _configurationWrapper.GetConfigIntValue("SummerCampForm.PreferredRoommate"),
                        EventParticipantId = eventParticipantId
                    },
                    new MpFormAnswer
                    {
                        Response           = crossroadsSite.Name,
                        FieldId            = _configurationWrapper.GetConfigIntValue("SummerCampForm.CamperCongregation"),
                        EventParticipantId = eventParticipantId
                    }
                };

                var formId       = _configurationWrapper.GetConfigIntValue("SummerCampFormID");
                var formResponse = new MpFormResponse
                {
                    ContactId   = contactId,
                    FormId      = formId,
                    FormAnswers = answers,
                    EventId     = eventId
                };

                _formSubmissionRepository.SubmitFormResponse(formResponse);
                return(campReservation);
            }
            throw new ApplicationException("Rules do not pass!");
        }