Esempio n. 1
0
        private void SendPendingInquiryReminderEmail(MpGroup group, IReadOnlyCollection <MpInquiry> inquiries)
        {
            var leaders         = ((List <MpGroupParticipant>)group.Participants).FindAll(p => p.GroupRoleId == _groupRoleLeaderId).ToList();
            var allLeaders      = string.Join(", ", leaders.Select(leader => $"{leader.NickName} {leader.LastName} ({leader.Email})").ToArray());
            var pendingRequests = string.Join("<br>", inquiries.Select(inquiry => $"{inquiry.FirstName} {inquiry.LastName} ({inquiry.EmailAddress})").ToArray());

            // ReSharper disable once LoopCanBePartlyConvertedToQuery
            foreach (var leader in leaders)
            {
                var mergeData = new Dictionary <string, object>
                {
                    { "Nick_Name", leader.NickName },
                    { "Last_Name", leader.LastName },
                    { "All_Leaders", allLeaders },
                    { "Pending_Requests", pendingRequests },
                    { "Group_Name", group.Name },
                    { "Group_Description", group.GroupDescription },
                    { "Group_ID", group.GroupId },
                    { "Pending_Requests_Count", inquiries.Count }
                };

                var email = new EmailCommunicationDTO
                {
                    groupId     = group.GroupId,
                    TemplateId  = _groupRequestPendingReminderEmailTemplateId,
                    ToContactId = leader.ContactId,
                    MergeData   = mergeData
                };
                _emailCommunicationService.SendEmail(email);
            }
        }
Esempio n. 2
0
        public void UpdateGroupRemainingCapacity(MpGroup group)
        {
            logger.Debug("Updating group: " + group.GroupId + " : " + group.Name);

            var values = new Dictionary <string, object>
            {
                { "Group_ID", group.GroupId },
                { "Remaining_Capacity", group.RemainingCapacity },
            };

            var retValue = WithApiLogin <int>(token =>
            {
                try
                {
                    ministryPlatformService.UpdateRecord(GroupsPageId, values, token);
                    return(1);
                }
                catch (Exception e)
                {
                    throw new ApplicationException("Error updating group: " + e.Message);
                }
            });

            logger.Debug("updated group: " + group.GroupId);
        }
Esempio n. 3
0
        public List <MpGroup> GetAllGroupNamesLeadByParticipant(int participantId, int?groupType)
        {
            const string COLUMNS =
                "Group_ID_Table.Group_Name, Group_Participants.group_participant_id, Group_Participants.participant_id,  Group_Participants.group_id, Group_Participants.group_role_id";
            string search = $"Group_Participants.participant_id = {participantId}" +
                            $" AND Group_Role_ID = {_groupRoleLeader}" +
                            $" AND (Group_ID_Table.End_Date > '{DateTime.Now:yyyy-MM-dd H:mm:ss}' OR Group_ID_Table.End_Date Is Null)" +
                            $" AND (Group_Participants.End_Date > '{DateTime.Now:yyyy-MM-dd H:mm:ss}' OR Group_Participants.End_Date Is Null)";

            if (groupType != null)
            {
                search += $" AND Group_ID_Table.Group_Type_ID = {groupType}";
            }

            var groupParticipantRecords = _ministryPlatformRest.UsingAuthenticationToken(_apiUserService.GetToken()).Search <MpGroupParticipant>(search, COLUMNS);

            List <MpGroup> groups = new List <MpGroup>();

            foreach (var groupParticipant in groupParticipantRecords)
            {
                var group = new MpGroup()
                {
                    GroupId = groupParticipant.GroupId,
                    Name    = groupParticipant.GroupName,
                };

                groups.Add(group);
            }
            return(groups);
        }
Esempio n. 4
0
        private void UpdateGroup(GroupDTO group)
        {
            //translate the dto to the mp object
            var mpgroup = new MpGroup
            {
                GroupId             = @group.GroupId,
                Name                = @group.GroupName,
                GroupType           = @group.GroupTypeId,
                Full                = @group.GroupFullInd,
                WaitList            = @group.WaitListInd,
                WaitListGroupId     = @group.WaitListGroupId,
                PrimaryContactName  = @group.PrimaryContactName,
                PrimaryContactEmail = @group.PrimaryContactEmail,
                ChildCareAvailable  = @group.ChildCareAvailable,
                MinimumAge          = @group.MaximumAge,
                GroupDescription    = @group.GroupDescription,
                MinistryId          = @group.MinistryId,
                MeetingTime         = @group.MeetingTime,
                MeetingDayId        = @group.MeetingDayId,
                CongregationId      = @group.CongregationId,
                StartDate           = @group.StartDate,
                EndDate             = @group.EndDate,
                AvailableOnline     = @group.AvailableOnline,
                RemainingCapacity   = @group.RemainingCapacity,
                ContactId           = @group.ContactId,
                GroupRoleId         = @group.GroupRoleId,
                MaximumAge          = @group.MaximumAge,
                MinimumParticipants = @group.MinimumParticipants,
                TargetSize          = @group.TargetSize
            };

            _groupService.UpdateGroup(mpgroup);
        }
Esempio n. 5
0
        private void checkSpaceRemaining(List <ParticipantSignup> participants, MpGroup group)
        {
            var numParticipantsToAdd = participants.Count;
            var spaceRemaining       = group.TargetSize - group.Participants.Count;

            if (((group.TargetSize > 0) && (numParticipantsToAdd > spaceRemaining)) || (group.Full))
            {
                throw (new GroupFullException(group));
            }
        }
Esempio n. 6
0
        public int UpdateGroup(MpGroup group)
        {
            logger.Debug("Updating group");

            var addressId = (group.Address != null) ? group.Address.Address_ID : null;
            var endDate   = group.EndDate.HasValue ? (object)group.EndDate.Value : null;

            var values = new Dictionary <string, object>
            {
                { "Group_Name", group.Name },
                { "Group_ID", group.GroupId },
                { "Group_Type_ID", group.GroupType },
                { "Ministry_ID", group.MinistryId },
                { "Congregation_ID", group.CongregationId },
                { "Primary_Contact", group.ContactId },
                { "Description", group.GroupDescription },
                { "Start_Date", group.StartDate },
                { "End_Date", endDate },
                { "Target_Size", group.TargetSize },
                { "Offsite_Meeting_Address", addressId },
                { "Group_Is_Full", group.Full },
                { "Available_Online", group.AvailableOnline },
                { "Meeting_Time", group.MeetingTime },
                { "Meeting_Day_Id", group.MeetingDayId },
                { "Domain_ID", 1 },
                { "Child_Care_Available", group.ChildCareAvailable },
                { "Remaining_Capacity", group.RemainingCapacity },
                { "Enable_Waiting_List", group.WaitList },
                { "Online_RSVP_Minimum_Age", group.MinimumAge },
                { "Maximum_Age", group.MaximumAge },
                { "Minimum_Participants", group.MinimumParticipants },
                { "Kids_Welcome", group.KidsWelcome ?? true },
                { "Meeting_Frequency_ID", group.MeetingFrequencyID }
            };

            var retValue = WithApiLogin <int>(token =>
            {
                try
                {
                    ministryPlatformService.UpdateRecord(GroupsPageId, values, token);
                    return(1);
                }
                catch (Exception e)
                {
                    throw new ApplicationException("Error updating group: " + e.Message);
                }
            });

            logger.Debug("Updated group " + retValue);
            return(retValue);
        }
        public void TestGetGroupDetails()
        {
            int groupId   = 333;
            int contactId = 777;

            MpGroup g = new MpGroup();

            g.GroupId           = 333;
            g.GroupType         = 8;
            g.GroupRole         = "Member";
            g.Name              = "Test Me";
            g.GroupId           = 123456;
            g.TargetSize        = 5;
            g.WaitList          = true;
            g.WaitListGroupId   = 888;
            g.RemainingCapacity = 10;

            MpParticipant participant = new MpParticipant();

            participant.ParticipantId = 90210;
            _participantServiceMock.Setup(
                mocked => mocked.GetParticipantRecord(_fixture.Request.Headers.Authorization.ToString()))
            .Returns(participant);

            _authenticationServiceMock.Setup(mocked => mocked.GetContactId(_fixture.Request.Headers.Authorization.ToString())).Returns(contactId);

            var relationRecord = new MpGroupSignupRelationships
            {
                RelationshipId     = 1,
                RelationshipMinAge = 00,
                RelationshipMaxAge = 100
            };

            var groupDto = new GroupDTO
            {
            };

            _groupServiceMock.Setup(mocked => mocked.getGroupDetails(groupId, contactId, participant, _fixture.Request.Headers.Authorization.ToString())).Returns(groupDto);


            IHttpActionResult result = _fixture.Get(groupId);

            Assert.IsNotNull(result);
            Assert.IsInstanceOf(typeof(OkNegotiatedContentResult <GroupDTO>), result);
            _groupServiceMock.VerifyAll();

            var groupDtoResponse = ((OkNegotiatedContentResult <GroupDTO>)result).Content;

            Assert.NotNull(result);
            Assert.AreSame(groupDto, groupDtoResponse);
        }
        public void TestAddParticipantToCommunityGroupWhenGroupFull()
        {
            int     groupId = 333;
            MpGroup g       = new MpGroup();

            g.GroupId    = 333;
            g.GroupType  = 8;
            g.GroupRole  = "Member";
            g.Name       = "Test Me";
            g.TargetSize = 5;
            g.WaitList   = false;
            g.Full       = true;

            var particpantIdToAdd = new List <ParticipantSignup>
            {
                new ParticipantSignup()
                {
                    particpantId          = 90210,
                    childCareNeeded       = false,
                    SendConfirmationEmail = true
                },
                new ParticipantSignup()
                {
                    particpantId          = 41001,
                    childCareNeeded       = false,
                    SendConfirmationEmail = true
                }
            };
            var groupFull = new GroupFullException(g);

            _groupServiceMock.Setup(mocked => mocked.addParticipantsToGroup(groupId, particpantIdToAdd)).Throws(groupFull);

            try
            {
                _fixture.Post(333, particpantIdToAdd);
                Assert.Fail("Expected exception was not thrown");
            }
            catch (Exception e)
            {
                Assert.AreEqual(typeof(HttpResponseException), e.GetType());
                var ex = (HttpResponseException)e;
                Assert.IsNotNull(ex.Response);
                Assert.AreEqual((HttpStatusCode)422, ex.Response.StatusCode);
            }
        }
Esempio n. 9
0
        public void TestUpdateGroup()
        {
            var       start   = DateTime.Now;
            var       end     = DateTime.Now.AddYears(2);
            const int groupId = 854725;

            var existingGroup = new MpGroup()
            {
                Name                = "New Testing Group",
                GroupDescription    = "The best group ever created for testing stuff and things",
                GroupId             = groupId,
                GroupType           = 1,
                MinistryId          = 8,
                ContactId           = 74657,
                CongregationId      = 1,
                StartDate           = start,
                EndDate             = end,
                Full                = false,
                TargetSize          = 0,
                AvailableOnline     = true,
                RemainingCapacity   = 8,
                WaitList            = false,
                ChildCareAvailable  = false,
                MeetingDayId        = 2,
                MeetingTime         = "15:15:00",
                GroupRoleId         = 16,
                MinimumAge          = 0,
                MinimumParticipants = 8,
                MaximumAge          = 99,
                KidsWelcome         = false,
                MeetingFrequencyID  = 1,
                Address             = new MpAddress()
                {
                    Address_ID = 43567
                }
            };

            _ministryPlatformService.Setup(mock => mock.UpdateRecord(_groupsPageId, It.IsAny <Dictionary <string, object> >(), It.IsAny <string>())).Verifiable();

            var result = _fixture.UpdateGroup(existingGroup);

            Assert.AreEqual(1, result);
        }
        public MpGroup GetGroupParticipantsForOpportunity(int opportunityId, string token)
        {
            var opp          = _ministryPlatformService.GetRecordDict(_opportunityPage, opportunityId, token);
            var groupId      = opp.ToInt("Add_to_Group");
            var groupName    = opp.ToString("Add_to_Group_Text");
            var searchString = ",,,," + opp.ToString("Group_Role_ID");
            var eventTypeId  = opp.ToInt("Event_Type_ID");
            var apiToken     = ApiLogin();
            var group        = _ministryPlatformService.GetSubpageViewRecords(_groupParticpantsSubPageView,
                                                                              groupId,
                                                                              apiToken,
                                                                              searchString);
            var participants = new List <MpGroupParticipant>();

            foreach (var groupParticipant in group)
            {
                participants.Add(new MpGroupParticipant
                {
                    ContactId      = groupParticipant.ToInt("Contact_ID"),
                    GroupRoleId    = groupParticipant.ToInt("Group_Role_ID"),
                    GroupRoleTitle = groupParticipant.ToString("Role_Title"),
                    LastName       = groupParticipant.ToString("Last_Name"),
                    NickName       = groupParticipant.ToString("Nickname"),
                    ParticipantId  = groupParticipant.ToInt("dp_RecordID")
                });
            }
            var retGroup = new MpGroup
            {
                GroupId      = groupId,
                Name         = groupName,
                Participants = participants,
                EventTypeId  = eventTypeId
            };

            return(retGroup);
        }
Esempio n. 11
0
        public void RequestToBeHostShouldThrow()
        {
            var token          = "faketoken";
            var hostRequestDto = new HostRequestDto
            {
                ContactId        = 123,
                GroupDescription = "fake group description",
                IsHomeAddress    = false,
                ContactNumber    = "555-123-4567",
                Address          = new AddressDTO
                {
                    AddressLine1 = "123 Main St",
                    City         = "Cincinnati",
                    State        = "OH",
                    PostalCode   = "45249"
                }
            };

            var searchResult1 = new MpGroup
            {
                ContactId      = 456,
                PrimaryContact = "456",
                Address        = new MpAddress()
                {
                    Address_ID     = 1,
                    Address_Line_1 = "42 Elm St",
                    City           = "Florence",
                    State          = "KY",
                    Postal_Code    = "45202"
                }
            };
            var searchResult2 = new MpGroup
            {
                ContactId      = 123,
                PrimaryContact = "123",
                Address        = new MpAddress()
                {
                    Address_ID     = 2,
                    Address_Line_1 = "123 Main St",
                    City           = "Cincinnati",
                    State          = "OH",
                    Postal_Code    = "45249"
                }
            };

            var searchResult3 = new MpGroup
            {
                ContactId      = 123,
                PrimaryContact = "123",
                Address        = new MpAddress()
                {
                    Address_ID     = 2,
                    Address_Line_1 = "99 SomewhereElse Ave",
                    City           = "Cincinnati",
                    State          = "OH",
                    Postal_Code    = "45249"
                }
            };
            var searchResults = new List <MpGroup> {
                searchResult1, searchResult2, searchResult3
            };

            _mpGroupRepository.Setup(m => m.GetGroupsByGroupType(It.IsAny <int>())).Returns(searchResults);

            Assert.That(() => _fixture.RequestToBeHost(token, hostRequestDto),
                        Throws.Exception
                        .TypeOf <GatheringException>());
        }
Esempio n. 12
0
        public void TestCreateGroup()
        {
            var       start   = DateTime.Now;
            var       end     = DateTime.Now.AddYears(2);
            const int groupId = 854725;

            var newGroup = new MpGroup()
            {
                Name                = "New Testing Group",
                GroupDescription    = "The best group ever created for testing stuff and things",
                GroupType           = 19,
                MinistryId          = 8,
                ContactId           = 74657,
                CongregationId      = 1,
                StartDate           = start,
                EndDate             = end,
                Full                = false,
                AvailableOnline     = true,
                RemainingCapacity   = 8,
                WaitList            = false,
                ChildCareAvailable  = false,
                MeetingDayId        = 2,
                MeetingTime         = "15:15:00",
                GroupRoleId         = 16,
                MinimumAge          = 0,
                MinimumParticipants = 8,
                MaximumAge          = 99,
                KidsWelcome         = false,
                MeetingFrequencyID  = null,
                Address             = new MpAddress()
                {
                    Address_ID = 43567
                }
            };

            var values = new Dictionary <string, object>
            {
                { "Group_Name", "New Testing Group" },
                { "Group_Type_ID", 19 },
                { "Ministry_ID", 8 },
                { "Congregation_ID", 1 },
                { "Primary_Contact", 74657 },
                { "Description", "The best group ever created for testing stuff and things" },
                { "Start_Date", start },
                { "End_Date", end },
                { "Target_Size", 0 },
                { "Offsite_Meeting_Address", 43567 },
                { "Group_Is_Full", false },
                { "Available_Online", true },
                { "Meeting_Time", "15:15:00" },
                { "Meeting_Day_Id", 2 },
                { "Domain_ID", 1 },
                { "Child_Care_Available", false },
                { "Remaining_Capacity", 8 },
                { "Enable_Waiting_List", false },
                { "Online_RSVP_Minimum_Age", 0 },
                { "Maximum_Age", 99 },
                { "Minimum_Participants", 8 },
                { "Kids_Welcome", false },
                { "Meeting_Frequency_ID", null }
            };

            _ministryPlatformService.Setup(mocked => mocked.CreateRecord(322, It.IsAny <Dictionary <string, object> >(), "ABC", true)).Returns(groupId);

            int resp = _fixture.CreateGroup(newGroup);

            _ministryPlatformService.Verify(mocked => mocked.CreateRecord(322, values, "ABC", true));

            Assert.IsNotNull(resp);
            Assert.AreEqual(groupId, resp);
        }
Esempio n. 13
0
 public GroupFullException(MpGroup group)
     : base("Group is full: " + group.Participants.Count + " > " + group.TargetSize)
 {
     this.group = group;
 }
Esempio n. 14
0
        private void SendEmail(MpInvitation invitation, MpParticipant leader, MpGroup group)
        {
            var leaderContact = _contactRepository.GetContactById(leader.ContactId);

            // basic merge data here
            var mergeData = new Dictionary <string, object>
            {
                { "Invitation_GUID", invitation.InvitationGuid },
                { "Recipient_Name", invitation.RecipientName },
            };

            int emailTemplateId;

            if (invitation.InvitationType == _groupInvitationType)
            {
                if (invitation.CustomMessage != null)
                {
                    emailTemplateId = _groupInvitationEmailTemplateCustom;
                    mergeData.Add("Leader_Message", invitation.CustomMessage);
                }
                else
                {
                    emailTemplateId = _groupInvitationEmailTemplate;
                }
                mergeData.Add("Leader_Name", leaderContact.Nickname + " " + leaderContact.Last_Name);
                mergeData.Add("Group_Name", group.Name);
            }
            else if (invitation.InvitationType == _tripInvitationType)
            {
                emailTemplateId = _tripInvitationEmailTemplate;
            }
            else if (invitation.InvitationType == _anywhereGatheringInvitationTypeId)
            {
                mergeData["Recipient_Name"] = invitation.RecipientName.Substring(0, 1).ToUpper() + invitation.RecipientName.Substring(1).ToLower();
                mergeData.Add("Leader_Name", leaderContact.Nickname.Substring(0, 1).ToUpper() + leaderContact.Nickname.Substring(1).ToLower() + " " + leaderContact.Last_Name.Substring(0, 1).ToUpper() + ".");
                mergeData.Add("City", group.Address.City);
                mergeData.Add("State", group.Address.State);
                mergeData.Add("Description", group.GroupDescription);
                mergeData.Add("Group_ID", group.GroupId);
                emailTemplateId = _anywhereGatheringInvitationEmailTemplate;
            }
            else
            {
                emailTemplateId = _defaultInvitationEmailTemplate;
            }
            var emailTemplate = _communicationService.GetTemplate(emailTemplateId);
            var fromContact   = new MpContact
            {
                ContactId    = emailTemplate.FromContactId,
                EmailAddress = emailTemplate.FromEmailAddress
            };
            var replyTo = new MpContact
            {
                ContactId    = leader.ContactId,
                EmailAddress = leader.EmailAddress
            };

            var to = new List <MpContact>
            {
                new MpContact
                {
                    // Just need a contact ID here, doesn't have to be for the recipient
                    ContactId    = emailTemplate.FromContactId,
                    EmailAddress = invitation.EmailAddress
                }
            };



            var confirmation = new MpCommunication
            {
                EmailBody      = emailTemplate.Body,
                EmailSubject   = emailTemplate.Subject,
                AuthorUserId   = 5,
                DomainId       = _domainId,
                FromContact    = fromContact,
                ReplyToContact = replyTo,
                TemplateId     = emailTemplateId,
                ToContacts     = to,
                MergeData      = mergeData
            };

            _communicationService.SendMessage(confirmation);
        }
Esempio n. 15
0
        public MpGroup getGroupDetails(int groupId)
        {
            return(WithApiLogin <MpGroup>(apiToken =>
            {
                logger.Debug("Getting group details for group " + groupId);
                var groupDetails = ministryPlatformService.GetRecordDict(GroupsPageId, groupId, apiToken, false);
                if (groupDetails == null)
                {
                    logger.Debug("No group found for group id " + groupId);
                    return (null);
                }
                var g = new MpGroup();
                g.GroupId = groupId;

                object con = null;
                groupDetails.TryGetValue("Congregation_ID", out con);
                if (con != null)
                {
                    g.CongregationId = (int)con;
                }

                object kw = null;
                groupDetails.TryGetValue("Kids_Welcome", out kw);
                if (kw != null)
                {
                    g.KidsWelcome = (Boolean)kw;
                }


                object ao = null;
                groupDetails.TryGetValue("Available_Online", out ao);
                if (ao != null)
                {
                    g.AvailableOnline = (Boolean)ao;
                }

                object mt = null;
                groupDetails.TryGetValue("Meeting_Time", out mt);
                if (mt != null)
                {
                    g.MeetingTime = (string)mt.ToString();
                }

                object md = null;
                groupDetails.TryGetValue("Meeting_Day_ID", out md);
                if (md != null)
                {
                    g.MeetingDayId = (int)md;
                }

                object oma = null;
                groupDetails.TryGetValue("Offsite_Meeting_Address", out oma);
                if (oma != null)
                {
                    g.Address = _addressRepository.GetAddressById(apiToken, (int)oma);
                }

                object c = null;
                groupDetails.TryGetValue("Primary_Contact", out c);
                if (c != null)
                {
                    g.ContactId = (int)c;
                }

                object mf = null;
                groupDetails.TryGetValue("Meeting_Frequency_ID", out mf);
                if (mf != null)
                {
                    g.MeetingFrequencyID = (int)mf;
                }

                object gid = null;
                groupDetails.TryGetValue("Group_ID", out gid);
                if (gid != null)
                {
                    g.GroupId = (int)gid;
                }

                object gg = null;
                groupDetails.TryGetValue("Description", out gg);
                if (gg != null)
                {
                    g.GroupDescription = (string)gg;
                }

                object gn = null;
                groupDetails.TryGetValue("Group_Name", out gn);
                if (gn != null)
                {
                    g.Name = (string)gn;
                }

                object gt = null;
                groupDetails.TryGetValue("Group_Type_ID", out gt);
                if (gt != null)
                {
                    g.GroupType = (int)gt;
                }

                object gsz = null;
                groupDetails.TryGetValue("Target_Size", out gsz);
                if (gsz != null)
                {
                    g.TargetSize = (short)gsz;
                }

                object gf = null;
                groupDetails.TryGetValue("Group_Is_Full", out gf);
                if (gf != null)
                {
                    g.Full = (Boolean)gf;
                }

                object gwl = null;
                groupDetails.TryGetValue("Enable_Waiting_List", out gwl);
                if (gwl != null)
                {
                    g.WaitList = (Boolean)gwl;
                }

                object gcc = null;
                groupDetails.TryGetValue("Child_Care_Available", out gcc);
                if (gcc != null)
                {
                    g.ChildCareAvailable = (Boolean)gcc;
                }

                object gc = null;
                groupDetails.TryGetValue("Congregation_ID_Text", out gc);
                if (gc != null)
                {
                    g.Congregation = (string)gc;
                }

                object ma = null;
                groupDetails.TryGetValue("Online_RSVP_Minimum_Age", out ma);
                if (ma != null)
                {
                    g.MinimumAge = (int)ma;
                }

                object rc = null;
                groupDetails.TryGetValue("Remaining_Capacity", out rc);
                if (rc != null)
                {
                    g.RemainingCapacity = (short)rc;
                }

                object mx = null;
                groupDetails.TryGetValue("Maximum_Age", out mx);
                if (mx != null)
                {
                    g.MaximumAge = (int)mx;
                }

                object mp = null;
                groupDetails.TryGetValue("Minimum_Participants", out mp);
                if (mp != null)
                {
                    g.MinimumParticipants = (int)mp;
                }

                object sd = null;
                groupDetails.TryGetValue("Start_Date", out sd);
                if (sd != null)
                {
                    g.StartDate = (DateTime)sd;
                }

                object mid = null;
                groupDetails.TryGetValue("Ministry_ID", out mid);
                if (mid != null)
                {
                    g.MinistryId = (int)mid;
                }

                if (g.WaitList)
                {
                    var subGroups = ministryPlatformService.GetSubPageRecords(GroupsSubgroupsPageId,
                                                                              groupId,
                                                                              apiToken);
                    if (subGroups != null)
                    {
                        foreach (var i in subGroups)
                        {
                            if (i.ContainsValue("Wait List"))
                            {
                                object gd = null;
                                i.TryGetValue("dp_RecordID", out gd);
                                g.WaitListGroupId = (int)gd;
                                break;
                            }
                        }
                    }
                    else
                    {
                        logger.Debug("No wait list found for group id " + groupId);
                    }
                }

                g.Participants = LoadGroupParticipants(groupId, apiToken);

                logger.Debug("Group details: " + g);
                return (g);
            }));
        }
        /// <summary>
        /// 订阅(关注)事件
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnEvent_SubscribeRequest(RequestMessageEvent_Subscribe requestMessage)
        {
            var rs     = CacheHelper.Get(string.Format("SubscribeRequest_{0}", account.AppID));
            var rstype = CacheHelper.Get(string.Format("SubscribeRequest_{0}_Type", account.AppID));
            var opid   = requestMessage.FromUserName;

            #region 记录日志
            try
            {
                var entityevent = new MpEventScanLog();
                entityevent.ID           = Formula.FormulaHelper.CreateGuid();
                entityevent.MpID         = account.ID;
                entityevent.OpenID       = opid;
                entityevent.EventContent = requestMessage.EventKey.StartsWith("qrscene_") ? requestMessage.EventKey.Substring(8) : requestMessage.EventKey;;
                entityevent.EventType    = "未关注";
                entityevent.MsgID        = requestMessage.MsgId.ToString();
                entityevent.CreateDate   = System.DateTime.Now;
                entities.Set <MpEventScanLog>().Add(entityevent);
                entities.SaveChanges();
            }
            catch (Exception ex)
            {
                LogWriter.Info(string.Format("MPID{0}记录扫码事件出错:原因{1}", account.ID, ex.Message));
            }
            #endregion

            #region 更新粉丝
            WxFO wxfo = new WxFO();
            try
            {
                UserInfoJson wxinfo = null;
                try
                {
                    wxinfo = UserApi.Info(wxfo.GetAccessToken(account.ID), opid);
                }
                catch (Exception ex)
                {
                    LogWriter.Error(ex, string.Format("获取MpID为{0},openid为{1}的用户信息报错", account.ID, opid));
                    wxinfo = UserApi.Info(wxfo.GetAccessToken(account.ID, true), opid);
                }
                if (wxinfo.errcode != ReturnCode.请求成功)
                {
                    throw new Exception(string.Format("获取MpID为{0},openid为{1}的用户信息报错,错误编号:{2},错误消息:{3}", account.ID, opid, wxinfo.errcode, wxinfo.errmsg));
                }

                var group      = entities.Set <MpGroup>().Where(c => c.MpID == account.ID && c.WxGroupID == wxinfo.groupid).FirstOrDefault();
                var entityfans = entities.Set <MpFans>().Where(c => c.MpID == account.ID && c.OpenID == opid).FirstOrDefault();

                #region 保存分组
                if (group == null)
                {
                    var rootgroup = entities.Set <MpGroup>().Where(c => c.MpID == account.ID && c.Length == 1).FirstOrDefault();
                    if (rootgroup == null)
                    {
                        rootgroup            = new MpGroup();
                        rootgroup.ID         = Formula.FormulaHelper.CreateGuid();
                        rootgroup.MpID       = account.ID;
                        rootgroup.Name       = "全部";
                        rootgroup.ParentID   = "-1";
                        rootgroup.FullPath   = rootgroup.ID;
                        rootgroup.Length     = 1;
                        rootgroup.ChildCount = 0;
                        entities.Set <MpGroup>().Add(rootgroup);
                    }
                    var g = new MpGroup();
                    g.ID         = Formula.FormulaHelper.CreateGuid();
                    g.MpID       = account.ID;
                    g.ParentID   = rootgroup.ID;
                    g.FullPath   = string.Format("{0}.{1}", rootgroup.ID, g.ID);
                    g.Length     = 2;
                    g.ChildCount = 0;
                    g.WxGroupID  = wxinfo.groupid;

                    GroupsJson groups = null;
                    try
                    {
                        groups = GroupsApi.Get(wxfo.GetAccessToken(account.ID));
                    }
                    catch (Exception ex)
                    {
                        LogWriter.Error(ex, string.Format("获取MpID为{0}的分组报错", account.ID));
                        groups = GroupsApi.Get(wxfo.GetAccessToken(account.ID, true));
                    }
                    if (groups.errcode != ReturnCode.请求成功)
                    {
                        throw new Exception(string.Format("获取MpID为{0}的分组报错,错误编号:{1},错误消息:{2}", account.ID, groups.errcode, groups.errmsg));
                    }

                    var wg = groups.groups.Where(c => c.id == wxinfo.groupid).FirstOrDefault();
                    if (wg != null)
                    {
                        g.Name      = wg.name;
                        g.FansCount = wg.count;
                    }
                    entities.Set <MpGroup>().Add(g);
                }
                #endregion

                #region 保存粉丝
                if (entityfans == null)
                {
                    entityfans               = new MpFans();
                    entityfans.ID            = Formula.FormulaHelper.CreateGuid();
                    entityfans.City          = wxinfo.city;
                    entityfans.Country       = wxinfo.country;
                    entityfans.HeadImgUrl    = wxinfo.headimgurl;
                    entityfans.IsFans        = "1";
                    entityfans.Language      = wxinfo.language;
                    entityfans.MpID          = account.ID;
                    entityfans.NickName      = wxinfo.nickname;
                    entityfans.OpenID        = wxinfo.openid;
                    entityfans.Province      = wxinfo.province;
                    entityfans.Remark        = wxinfo.remark;
                    entityfans.Sex           = wxinfo.sex.ToString();
                    entityfans.SubscribeTime = DateTimeHelper.GetDateTimeFromXml(wxinfo.subscribe_time);
                    entityfans.UniionID      = wxinfo.unionid;
                    entityfans.WxGroupID     = wxinfo.groupid;
                    entityfans.GroupID       = group.ID;
                    entityfans.UpdateTime    = DateTime.Now;
                    entities.Set <MpFans>().Add(entityfans);
                }
                else
                {
                    entityfans.City          = wxinfo.city;
                    entityfans.Country       = wxinfo.country;
                    entityfans.HeadImgUrl    = wxinfo.headimgurl;
                    entityfans.IsFans        = "1";
                    entityfans.Language      = wxinfo.language;
                    entityfans.MpID          = account.ID;
                    entityfans.NickName      = wxinfo.nickname;
                    entityfans.OpenID        = wxinfo.openid;
                    entityfans.Province      = wxinfo.province;
                    entityfans.Remark        = wxinfo.remark;
                    entityfans.Sex           = wxinfo.sex.ToString();
                    entityfans.SubscribeTime = DateTimeHelper.GetDateTimeFromXml(wxinfo.subscribe_time);
                    entityfans.UniionID      = wxinfo.unionid;
                    entityfans.WxGroupID     = wxinfo.groupid;
                    entityfans.GroupID       = group.ID;
                    entityfans.UpdateTime    = DateTime.Now;
                }
                #endregion

                entities.SaveChanges();
            }
            catch (Exception ex)
            {
                LogWriter.Error(string.Format("粉丝订阅更新数据库失败,原因:{0}", ex.Message));
            }
            #endregion

            #region 推送消息
            if (rs == null || rstype == null)
            {
                var eventtype = MpEventType.Subscribe.ToString();
                var entity    = entities.Set <MpEvent>().Where(c => c.MpID == account.ID && c.IsDelete == 0 && c.EventType == eventtype).FirstOrDefault();
                if (entity != null)
                {
                    CacheHelper.Set(string.Format("SubscribeRequest_{0}_Type", account.AppID), entity.ReplyType, cachesecond);
                    if (entity.ReplyType == MpMessageType.none.ToString())
                    {
                        return(null);
                    }
                    else if (entity.ReplyType == MpMessageType.image.ToString())
                    {
                        var responseMessage = base.CreateResponseMessage <ResponseMessageImage>();
                        responseMessage.Image.MediaId = entity.ImageMediaID;
                        CacheHelper.Set(string.Format("SubscribeRequest_{0}", account.AppID), responseMessage, cachesecond);
                        return(responseMessage);
                    }
                    else if (entity.ReplyType == MpMessageType.text.ToString())
                    {
                        var responseMessage = base.CreateResponseMessage <ResponseMessageText>();
                        responseMessage.Content = entity.Content;
                        CacheHelper.Set(string.Format("SubscribeRequest_{0}", account.AppID), responseMessage, cachesecond);
                        return(responseMessage);
                    }
                    else if (entity.ReplyType == MpMessageType.voice.ToString())
                    {
                        var responseMessage = base.CreateResponseMessage <ResponseMessageVoice>();
                        responseMessage.Voice.MediaId = entity.VoiceMediaID;
                        CacheHelper.Set(string.Format("SubscribeRequest_{0}", account.AppID), responseMessage, cachesecond);
                        return(responseMessage);
                    }
                    else if (entity.ReplyType == MpMessageType.video.ToString())
                    {
                        var responseMessage = base.CreateResponseMessage <ResponseMessageVideo>();
                        var video           = entities.Set <MpMediaVideo>().Where(c => c.MpID == account.ID && c.IsDelete == 0 && c.ID == entity.VideoID).FirstOrDefault();
                        if (video == null)
                        {
                            return(null);
                        }
                        responseMessage.Video.MediaId     = video.MediaID;
                        responseMessage.Video.Title       = video.Title;
                        responseMessage.Video.Description = video.Description;
                        CacheHelper.Set(string.Format("SubscribeRequest_{0}", account.AppID), responseMessage, cachesecond);
                        return(responseMessage);
                    }
                    else if (entity.ReplyType == MpMessageType.mpnews.ToString())
                    {
                        var responseMessage = base.CreateResponseMessage <ResponseMessageNews>();
                        var article         = entities.Set <MpSelfArticle>().Where(c => c.MpID == account.ID && c.IsDelete == 0 && c.ID == entity.ArticleID).FirstOrDefault();
                        if (article == null)
                        {
                            return(null);
                        }
                        responseMessage.Articles.Add(new Article()
                        {
                            Title       = article.Title,
                            Description = article.Description,
                            Url         = article.Url,
                            PicUrl      = string.Format("http://{0}/wechatservice/api/Image/Get/{1}", domain, article.PicFileID),
                        });
                        CacheHelper.Set(string.Format("SubscribeRequest_{0}", account.AppID), responseMessage, cachesecond);
                        return(responseMessage);
                    }
                    else if (entity.ReplyType == MpMessageType.mpmultinews.ToString())
                    {
                        var responseMessage = base.CreateResponseMessage <ResponseMessageNews>();
                        var article         = entities.Set <MpSelfArticleGroup>().Where(c => c.MpID == account.ID && c.IsDelete == 0 && c.ID == entity.ArticleGroupID).FirstOrDefault();
                        if (article == null || article.MpSelfArticleGroupItem == null || article.MpSelfArticleGroupItem.Count(c => c.MpSelfArticle != null) < 2)
                        {
                            return(null);
                        }
                        foreach (var item in article.MpSelfArticleGroupItem.Where(c => c.MpSelfArticle != null))
                        {
                            responseMessage.Articles.Add(new Article()
                            {
                                Title       = item.MpSelfArticle.Title,
                                Description = item.MpSelfArticle.Description,
                                Url         = item.MpSelfArticle.Url,
                                PicUrl      = string.Format("http://{0}/wechatservice/api/Image/Get/{1}", domain, item.MpSelfArticle.PicFileID),
                            });
                        }
                        CacheHelper.Set(string.Format("SubscribeRequest_{0}", account.AppID), responseMessage, cachesecond);
                        return(responseMessage);
                    }
                    else
                    {
                        return(null);
                    }
                }
                //其他回复
                else
                {
                    return(null);
                }
            }
            else
            {
                var rstp = rstype.ToString();
                if (rstp == MpMessageType.image.ToString())
                {
                    return(rs as ResponseMessageImage);
                }
                else if (rstp == MpMessageType.mpmultinews.ToString())
                {
                    return(rs as ResponseMessageNews);
                }
                else if (rstp == MpMessageType.mpnews.ToString())
                {
                    return(rs as ResponseMessageNews);
                }
                else if (rstp == MpMessageType.text.ToString())
                {
                    return(rs as ResponseMessageText);
                }
                else if (rstp == MpMessageType.video.ToString())
                {
                    return(rs as ResponseMessageVideo);
                }
                else if (rstp == MpMessageType.voice.ToString())
                {
                    return(rs as ResponseMessageVoice);
                }
                return(rs as IResponseMessageBase);
            }
            #endregion
        }
Esempio n. 17
0
 private void DecrementCapacity(int capacityNeeded, MpGroup group)
 {
     group.RemainingCapacity = group.RemainingCapacity - capacityNeeded;
     _logger.Debug("Remaining Capacity After decrement: " + capacityNeeded + " : " + group.RemainingCapacity);
     _mpGroupRepository.UpdateGroupRemainingCapacity(group);
 }
Esempio n. 18
0
        public void CanCreateInvitationsForGroups()
        {
            const string token = "dude";

            var invitation = new Invitation()
            {
                EmailAddress   = "*****@*****.**",
                GroupRoleId    = GroupRoleLeader,
                InvitationType = GroupInvitationType,
                RecipientName  = "Dudley Doright",
                RequestDate    = new DateTime(2016, 7, 6),
                SourceId       = 33
            };

            var mpInvitation = new MpInvitation
            {
                InvitationType = invitation.InvitationType,
                EmailAddress   = invitation.EmailAddress,
                GroupRoleId    = invitation.GroupRoleId,
                RecipientName  = invitation.RecipientName,
                RequestDate    = invitation.RequestDate,
                SourceId       = invitation.SourceId,
                InvitationGuid = "guid123",
                InvitationId   = 11
            };

            _invitationRepository.Setup(
                m =>
                m.CreateInvitation(
                    It.Is <MpInvitation>(
                        i =>
                        i.InvitationType == invitation.InvitationType && i.EmailAddress.Equals(invitation.EmailAddress) && i.GroupRoleId == invitation.GroupRoleId &&
                        i.RecipientName.Equals(invitation.RecipientName) && i.RequestDate.Equals(invitation.RequestDate) && i.SourceId == invitation.SourceId))).Returns(mpInvitation);

            var testGroup = new MpGroup
            {
                GroupId = 33,
                Name    = "TestGroup"
            };

            _groupRepository.Setup(mocked => mocked.getGroupDetails(invitation.SourceId)).Returns(testGroup);

            var testLeaderParticipant = new MpParticipant
            {
                DisplayName  = "TestLeaderName",
                ContactId    = 123,
                EmailAddress = "*****@*****.**"
            };

            var leaderContact = new MpMyContact
            {
                Last_Name = "TestLast",
                Nickname  = "TestNick"
            };

            _contactRespository.Setup(mocked => mocked.GetContactById(testLeaderParticipant.ContactId)).Returns(leaderContact);

            _participantRepository.Setup(mocked => mocked.GetParticipantRecord(token)).Returns(testLeaderParticipant);

            var template = new MpMessageTemplate
            {
                Body                = "body",
                FromContactId       = 12,
                FromEmailAddress    = "*****@*****.**",
                ReplyToContactId    = 34,
                ReplyToEmailAddress = "*****@*****.**",
                Subject             = "subject"
            };

            _communicationService.Setup(mocked => mocked.GetTemplate(GroupInvitationEmailTemplate)).Returns(template);

            //_communicationService.Setup(
            //    mocked =>
            //        mocked.SendMessage(
            //            It.Is<MpCommunication>(
            //                c =>
            //                    c.AuthorUserId == 5 && c.DomainId == DomainId && c.EmailBody.Equals(template.Body) && c.EmailSubject.Equals(template.Subject) &&
            //                    c.FromContact.ContactId == template.FromContactId && c.FromContact.EmailAddress.Equals(template.FromEmailAddress) &&
            //                    c.ReplyToContact.ContactId == template.ReplyToContactId && c.ReplyToContact.EmailAddress.Equals(template.ReplyToEmailAddress) &&
            //                    c.ToContacts.Count == 1 && c.ToContacts[0].EmailAddress.Equals(invitation.EmailAddress) &&
            //                    c.MergeData["Invitation_GUID"].ToString().Equals(mpInvitation.InvitationGuid) &&
            //                    c.MergeData["Recipient_Name"].ToString().Equals(mpInvitation.RecipientName) &&
            //                    c.MergeData["Leader_Name"].ToString().Equals(testLeaderParticipant.DisplayName) &&
            //                    c.MergeData["Group_Name"].ToString().Equals(testGroup.Name)),
            //            false)).Returns(77);

            _communicationService.Setup(
                mocked =>
                mocked.SendMessage(
                    It.Is <MpCommunication>(
                        c =>
                        c.AuthorUserId == 5 && c.DomainId == DomainId && c.EmailBody.Equals(template.Body) && c.EmailSubject.Equals(template.Subject) &&
                        c.FromContact.ContactId == template.FromContactId && c.FromContact.EmailAddress.Equals(template.FromEmailAddress) &&
                        c.ReplyToContact.ContactId == testLeaderParticipant.ContactId && c.ReplyToContact.EmailAddress.Equals(template.ReplyToEmailAddress) &&
                        c.ToContacts.Count == 1 && c.ToContacts[0].EmailAddress.Equals(invitation.EmailAddress) &&
                        c.MergeData["Invitation_GUID"].ToString().Equals(mpInvitation.InvitationGuid) &&
                        c.MergeData["Recipient_Name"].ToString().Equals(mpInvitation.RecipientName) &&
                        c.MergeData["Leader_Name"].ToString().Equals(leaderContact.Nickname + " " + leaderContact.Last_Name) &&
                        c.MergeData["Group_Name"].ToString().Equals(testGroup.Name)),
                    false)).Returns(77);

            var created = _fixture.CreateInvitation(invitation, token);

            _invitationRepository.VerifyAll();
            _communicationService.VerifyAll();
            Assert.AreSame(invitation, created);
            Assert.AreEqual(mpInvitation.InvitationId, created.InvitationId);
            Assert.AreEqual(mpInvitation.InvitationGuid, created.InvitationGuid);
        }
Esempio n. 19
0
        public void CanCreateInvitationsForAnywhereGroups()
        {
            const string token = "dude";

            string groupName              = "Dougs Anywhere Gathering";
            string recipientName          = "doug";
            string formattedRecipientName = "Doug";
            string leaderFName            = "xavier";
            string leaderLName            = "johnson";
            string formattedLeaderName    = "Xavier J.";

            string city        = "Lima";
            string state       = "Ohio";
            string description = "descriptive description";
            int    sourceId    = 12345;
            int    groupRoleId = 16;

            var invitation = new Invitation()
            {
                RecipientName  = recipientName,
                EmailAddress   = "*****@*****.**",
                SourceId       = sourceId,
                GroupRoleId    = groupRoleId,
                InvitationType = AnywhereGatheringInvitationTypeID
            };

            var mpInvitation = new MpInvitation
            {
                InvitationType = invitation.InvitationType,
                EmailAddress   = invitation.EmailAddress,
                GroupRoleId    = invitation.GroupRoleId,
                RecipientName  = invitation.RecipientName,
                RequestDate    = invitation.RequestDate,
                SourceId       = invitation.SourceId,
                InvitationGuid = "guid123",
                InvitationId   = 11
            };

            _invitationRepository.Setup(
                m =>
                m.CreateInvitation(
                    It.Is <MpInvitation>(
                        i =>
                        i.InvitationType == invitation.InvitationType && i.EmailAddress.Equals(invitation.EmailAddress) && i.GroupRoleId == invitation.GroupRoleId &&
                        i.RecipientName.Equals(invitation.RecipientName) && i.SourceId == invitation.SourceId))).Returns(mpInvitation);

            var testGroup = new MpGroup
            {
                GroupId = 33,
                Name    = groupName,
                Address = new MpAddress()
                {
                    City  = city,
                    State = state
                },
                GroupDescription = description
            };

            _groupRepository.Setup(mocked => mocked.getGroupDetails(invitation.SourceId)).Returns(testGroup);


            MpParticipant leader = new MpParticipant()
            {
                ContactId = 123456789
            };

            MpMessageTemplate template = new MpMessageTemplate()
            {
                Body                = "this is the template!",
                FromContactId       = 1,
                FromEmailAddress    = "*****@*****.**",
                ReplyToContactId    = leader.ContactId,
                ReplyToEmailAddress = "*****@*****.**",
                Subject             = "TheSubject!"
            };
            MpMyContact leaderContact = new MpMyContact()
            {
                Nickname  = leaderFName,
                Last_Name = leaderLName
            };

            _participantRepository.Setup(mocked => mocked.GetParticipantRecord(token)).Returns(leader);
            _contactRespository.Setup((c) => c.GetContactById(It.Is <int>((i) => i == leader.ContactId))).Returns(leaderContact);
            _communicationService.Setup((c) => c.GetTemplate(It.Is <int>((i) => i == AnywhereGatheringEmailTemplateID))).Returns(template);
            _communicationService.Setup((c) => c.SendMessage(It.Is <MpCommunication>(
                                                                 (confirmation) => confirmation.EmailBody == template.Body &&
                                                                 confirmation.EmailSubject == template.Subject &&
                                                                 confirmation.AuthorUserId == 5 &&
                                                                 confirmation.DomainId == DomainId &&
                                                                 confirmation.FromContact.ContactId == template.FromContactId &&
                                                                 confirmation.ReplyToContact.ContactId == template.ReplyToContactId &&
                                                                 confirmation.TemplateId == AnywhereGatheringEmailTemplateID &&
                                                                 confirmation.ToContacts[0].EmailAddress == invitation.EmailAddress &&
                                                                 (string)confirmation.MergeData["Invitation_GUID"] == mpInvitation.InvitationGuid &&
                                                                 (string)confirmation.MergeData["Recipient_Name"] == formattedRecipientName &&
                                                                 (string)confirmation.MergeData["Leader_Name"] == formattedLeaderName
                                                                 ),
                                                             false));


            var created = _fixture.CreateInvitation(invitation, token);

            _invitationRepository.VerifyAll();
            _communicationService.VerifyAll();
            Assert.AreSame(invitation, created);
            Assert.AreEqual(mpInvitation.InvitationId, created.InvitationId);
            Assert.AreEqual(mpInvitation.InvitationGuid, created.InvitationGuid);
        }
Esempio n. 20
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);
        }
Esempio n. 21
0
        public void UpdateEventReservationStaysChildCare()
        {
            var newReservation = GetEventToolTestObjectWithRooms();

            newReservation.EventTypeId = 98765;
            var oldEventData = Mapper.Map <MpEvent>(newReservation);

            newReservation.Group = new GroupDTO()
            {
                CongregationId = 1
            };

            var roomReservationReturn = new List <MpRoomReservationDto>()
            {
                new MpRoomReservationDto()
                {
                    Name         = "Room1",
                    Cancelled    = false,
                    RoomId       = 1,
                    EventId      = 1,
                    EventRoomId  = 1,
                    RoomLayoutId = 1,
                },
                new MpRoomReservationDto()
                {
                    Name         = "Room2",
                    Cancelled    = false,
                    RoomId       = 2,
                    EventId      = 1,
                    EventRoomId  = 2,
                    RoomLayoutId = 1
                }
            };

            var equipmentForRoom1 = new List <MpEquipmentReservationDto>()
            {
                new MpEquipmentReservationDto()
                {
                    Cancelled         = false,
                    RoomId            = 1,
                    EventId           = 1,
                    QuantityRequested = 10,
                    EquipmentId       = 1,
                    EventEquipmentId  = 1,
                    EventRoomId       = 1
                },
                new MpEquipmentReservationDto()
                {
                    Cancelled         = false,
                    RoomId            = 1,
                    EventId           = 1,
                    QuantityRequested = 42,
                    EquipmentId       = 2,
                    EventEquipmentId  = 2,
                    EventRoomId       = 2
                }
            };

            var mpEventGroupData = new List <MpEventGroup>()
            {
                new MpEventGroup()
                {
                    EventId      = 1,
                    Closed       = false,
                    RoomId       = 1,
                    EventRoomId  = 2,
                    DomainId     = 1,
                    GroupId      = 42,
                    GroupName    = "_childCare",
                    GroupTypeId  = 23,
                    Created      = true,
                    EventGroupId = 1
                }
            };

            var mpGroup = new MpGroup()
            {
                Name               = "ChildCareGroup",
                GroupId            = 42,
                ChildCareAvailable = true,
                CongregationId     = 1,
                KidsWelcome        = true,
                TargetSize         = 42
            };

            _eventService.Setup(mock => mock.GetEvent(1)).Returns(oldEventData);
            _roomService.Setup(mockyMock => mockyMock.GetRoomReservations(1)).Returns(roomReservationReturn);
            _equipmentService.Setup(mock => mock.GetEquipmentReservations(1, 1)).Returns(equipmentForRoom1);
            _equipmentService.Setup(mock => mock.GetEquipmentReservations(1, 2)).Returns(new List <MpEquipmentReservationDto>());
            _eventService.Setup(mock => mock.GetEventGroupsForEventAPILogin(1)).Returns(mpEventGroupData);
            _eventService.Setup(mock => mock.UpdateEvent(It.IsAny <MpEventReservationDto>()));
            _roomService.Setup(mock => mock.UpdateRoomReservation(It.IsAny <MpRoomReservationDto>()));
            _equipmentService.Setup(mock => mock.UpdateEquipmentReservation(It.IsAny <MpEquipmentReservationDto>()));
            _groupService.Setup(mock => mock.getGroupDetails(42)).Returns(mpGroup);
            _groupService.Setup(mock => mock.UpdateGroup(It.IsAny <MpGroup>())).Returns(42);

            var result = _fixture.UpdateEventReservation(newReservation, 1, "ABC");

            Assert.IsTrue(result);
            _equipmentService.Verify(m => m.UpdateEquipmentReservation(It.IsAny <MpEquipmentReservationDto>()), Times.Exactly(2));
            _roomService.Verify(m => m.UpdateRoomReservation(It.IsAny <MpRoomReservationDto>()), Times.Exactly(2));
            _eventService.Verify(m => m.UpdateEvent(It.IsAny <MpEventReservationDto>()), Times.Once);
            _groupService.Verify(m => m.getGroupDetails(42), Times.Once);
            _groupService.Verify(m => m.UpdateGroup(It.IsAny <MpGroup>()), Times.Once);
            _eventService.Verify(m => m.GetEventGroupsForEventAPILogin(1), Times.Exactly(2));
        }