Exemplo n.º 1
0
        protected override void OnData()
        {
            base.OnData();
            this.TimelineEventPage = Self.GET($"/timeline/timeline-item/{this.Key}");

            Event        thisEvent = DbHelper.FromID(DbHelper.Base64DecodeObjectID(this.Key)) as Event;
            List <Event> allEvents = Db.SQL <Event>("SELECT ep.Event FROM Simplified.Ring6.EventParticipation ep").ToList();

            //If an event does not have a relation > attach it to "this user".
            //The only time this will happen is when an event has just been created. = The event will be attached to the correct person
            if (!allEvents.Contains(thisEvent) && !string.IsNullOrEmpty(this.ParentPage.PersonId))
            {
                Person thisPerson = DbHelper.FromID(DbHelper.Base64DecodeObjectID(this.ParentPage.PersonId)) as Person;
                Db.Transact(() =>
                {
                    EventParticipation eventParticipation = new EventParticipation();
                    eventParticipation.Event       = thisEvent;
                    eventParticipation.Participant = thisPerson;
                });
            }
            else if (!allEvents.Contains(thisEvent) && string.IsNullOrEmpty(this.ParentPage.PersonId)) // If an event is created outside of a person scope, it should displayed for every user
            {
                Db.Transact(() =>
                {
                    EventParticipation eventParticipation = new EventParticipation();
                    eventParticipation.Event = thisEvent;
                });
            }
        }
        public void Update(int eventId, int userId, EventParticipateViewModel viewModel)
        {
            var date             = DateTime.Now;
            EventParticipation p = _appDbContext.EventParticipations.Where(x => x.EventId == eventId && x.UserId == userId).FirstOrDefault();

            if (p == null)
            {
                p         = new EventParticipation();
                p.Created = date;
                p.UserId  = userId;
                p.EventId = eventId;
                _appDbContext.EventParticipations.Add(p);
            }

            p.Modified = date;

            p.AnswerYes = viewModel.ParticipationType == ParticipationTypesEnum.yes;
            p.AnswerNo  = viewModel.ParticipationType == ParticipationTypesEnum.no;
            p.Note      = viewModel.Note;
            p.IsPlayer  = viewModel.IsPlayer;
            p.IsCoach   = viewModel.IsCoach;
            p.IsScorer  = viewModel.IsScorer;
            p.IsUmpire  = viewModel.IsUmpire;
            p.Seats     = viewModel.HasSeats;

            CommitChanges();
        }
Exemplo n.º 3
0
        public ActionResult <EventParticipation> CreateEventParticipation([FromBody] EventParticipation eventParticipationItem)
        {
            ntuEventsContext_Db.EventParticipations.Add(eventParticipationItem);
            ntuEventsContext_Db.SaveChanges();

            return(Ok(eventParticipationItem));
        }
Exemplo n.º 4
0
        public async Task <IActionResult> SendChatMessage(SendMessageDto sendMessageDto)
        {
            IDatabaseContext context = _getDatabaseContext();
            int currentUserId        = HttpContext.GetUserId();

            List <EventParticipation> eventParticipations = await context.EventParticipations.Where(e => e.EventId == sendMessageDto.EventId).ToListAsync();

            EventParticipation currentUserParticipation = eventParticipations.FirstOrDefault(e => e.ParticipantId == currentUserId);

            if (currentUserParticipation == null)
            {
                return(BadRequest(RequestStringMessages.UserNotPartOfEvent));
            }

            var message = new ChatMessage
            {
                AuthorId = currentUserId,
                EventId  = sendMessageDto.EventId,
                Content  = sendMessageDto.Content,
                SentDate = DateTime.UtcNow
            };

            context.ChatMessages.Add(message);

            currentUserParticipation.LastReadMessageSentDate = message.SentDate;

            await context.SaveChangesAsync();

            _auditLogger.LogInformation("{0}(): Sent a new chat message (containing {1} characters) to the event {2}", nameof(SendChatMessage), sendMessageDto.Content.Length, sendMessageDto.EventId);

            // TODO Push-Notifications eventParticipations.Where(e => e.ParticipantId != currentUserId).ForEach(p => SendNotification(p));

            return(Ok(new EventChatMessage(message.Id, currentUserId, message.Content, message.SentDate)));
        }
        public void Remove(EventParticipation entity, bool commit = true)
        {
            _appDbContext.EventParticipations.Remove(entity);

            if (commit)
            {
                CommitChanges();
            }
        }
Exemplo n.º 6
0
        public async Task <IActionResult> GetChatMessages(GetChatMessagesDto getChatMessagesDto)
        {
            IDatabaseContext context = _getDatabaseContext();
            int currentUserId        = HttpContext.GetUserId();

            EventParticipation eventParticipation = await context.EventParticipations.FirstOrDefaultAsync(ep => (ep.EventId == getChatMessagesDto.EventId) && (ep.ParticipantId == currentUserId));

            if (eventParticipation == null)
            {
                return(BadRequest(RequestStringMessages.UserNotPartOfEvent));
            }

            IQueryable <ChatMessage> chatMessagesQuery = context.ChatMessages
                                                         .Where(c => c.EventId == getChatMessagesDto.EventId);

            bool providedAlreadyLoadedMessageSentDate = getChatMessagesDto.EarliestLoadedMessageSentDate.HasValue;

            if (providedAlreadyLoadedMessageSentDate)
            {
                DateTime dateValue = getChatMessagesDto.EarliestLoadedMessageSentDate.Value;

                chatMessagesQuery = chatMessagesQuery.Where(c => c.SentDate < dateValue);
            }

            List <EventChatMessage> eventChatMessages = await chatMessagesQuery
                                                        .OrderByDescending(c => c.SentDate)
                                                        .Take(_baseAmountOfChatMessagesPerDetailPage)
                                                        .Select(m => new EventChatMessage(m.Id, m.AuthorId, m.Content, m.SentDate))
                                                        .ToListAsync();

            if (!providedAlreadyLoadedMessageSentDate)
            {
                DateTime?lastReadMessageSentDate = eventChatMessages.FirstOrDefault()?.SentDate;

                if (lastReadMessageSentDate.HasValue && (eventParticipation.LastReadMessageSentDate != lastReadMessageSentDate.Value))
                {
                    _logger.LogDebug("{0}(): Automatically marking loaded messages as read", nameof(GetChatMessages));
                    // The user loaded the latest messages => Assume he also read them
                    eventParticipation.LastReadMessageSentDate = lastReadMessageSentDate.Value;
                    await context.SaveChangesAsync();
                }
            }
            List <int> allAuthorIds = eventChatMessages
                                      .Select(c => c.AuthorId)
                                      .Distinct()
                                      .ToList();

            List <UserInformation> authorInformations = await context.Users
                                                        .Where(u => allAuthorIds.Contains(u.Id))
                                                        .Select(u => new UserInformation(u.Id, u.FullName, u.Email))
                                                        .ToListAsync();


            return(Ok(new EventChatMessages(eventChatMessages, eventChatMessages.Count == _baseAmountOfChatMessagesPerDetailPage, authorInformations)));
        }
Exemplo n.º 7
0
        public ActionResult UpdateEventParticipation(int userId, int eventId, [FromBody] EventParticipation eventParticipationItem)
        {
            if (eventId != eventParticipationItem.EventId || userId != eventParticipationItem.UserId)
            {
                return(BadRequest());
            }

            ntuEventsContext_Db.Entry(eventParticipationItem).State = EntityState.Modified;
            ntuEventsContext_Db.SaveChanges();

            return(NoContent());
        }
        public async Task <IActionResult> AcceptInvitation(AcceptInvitationDto acceptInvitationDto)
        {
            IDatabaseContext context    = _getDatabaseContext();
            EventInvitation? invitation = await context.EventInvitations
                                          .Include(i => i.Event)
                                          .ThenInclude(e => e.EventParticipations)
                                          .FirstOrDefaultAsync(i => i.Token == acceptInvitationDto.InviteToken);

            if (invitation == null)
            {
                return(BadRequest(RequestStringMessages.InvitationInvalid));
            }

            int currentUserId = HttpContext.GetUserId();

            if (invitation.Event.EventParticipations.Select(ep => ep.ParticipantId).Contains(currentUserId))
            {
                // The invite link was used to access the event => Redirect to event
                return(Ok(invitation.EventId));
            }

            if (invitation.Event.IsPrivate)
            {
                // Invitations to private events require to still be valid and not already used

                if (invitation.Used)
                {
                    return(BadRequest(RequestStringMessages.InvitationAlreadyUsed));
                }

                if (invitation.Requested + _inviteTimeout < DateTime.UtcNow)
                {
                    return(BadRequest(RequestStringMessages.InvitationInvalid));
                }
            }

            // Invitations to public events are theoretically pointless as the user could join without the invitation
            // => These invitations are always considered as valid, even if already used

            var participation = new EventParticipation
            {
                Event         = invitation.Event,
                ParticipantId = currentUserId
            };

            invitation.Event.EventParticipations.Add(participation);

            invitation.Used = true;

            await context.SaveChangesAsync();

            return(Ok(invitation.EventId));
        }
Exemplo n.º 9
0
 public HomeViewModel(
     IActivityParticipationService activityParticipationService,
     IActivityManagementService activityManagementService,
     IEventParticipationService eventParticipationService,
     IEventManagementService eventManagementService)
 {
     _activityParticipationService = activityParticipationService;
     _activityManagementService    = activityManagementService;
     _eventParticipationService    = eventParticipationService;
     _eventManagementService       = eventManagementService;;
     NewEventParticipation         = new EventParticipation();
     NewActivityParticipation      = new ActivityParticipation();
 }
Exemplo n.º 10
0
        /// <summary>
        /// Sends email to partner for confirmation.
        /// </summary>
        /// <param name="eventId"></param>
        /// <param name="partnerFirstName"></param>
        /// <param name="partnerEmail"></param>
        /// <param name="partnerEmail"></param>
        /// <param name="userId"></param>
        public async Task <IActionResult> OnPostSendPartnerInvitation(int eventId, string partnerFirstName, string partnerLastName, string partnerEmail, string userId)
        {
            ApplicationUser user = await UserManager.FindByIdAsync(userId);

            if (user == null)
            {
                return(Page());
            }

            DinnerEvent dinnerEvent = DinnerEventsRepository.GetById(eventId);

            if (dinnerEvent == null)
            {
                return(Page());
            }

            Invitation invitation = new Invitation
            {
                Event           = dinnerEvent,
                InvitationEmail = partnerEmail,
                User            = user,
                SentTime        = DateTime.Now
            };

            InvitationsRepository.Insert(invitation);
            InvitationsRepository.SaveChanges();
            EventParticipation participation = EventParticipationsRepository.SearchFor(x => x.User.Id == user.Id && x.Event.Id == eventId).FirstOrDefault();

            if (participation != null)
            {
                if (!participation.RegistrationComplete)
                {
                    TempData["StatusMessage"] = @"Bitte fülle zuerst die Teamdaten aus.";
                    return(Page());
                }

                participation.InvitationMailSent = true;
                EventParticipationsRepository.Update(participation);
                EventParticipationsRepository.SaveChanges();
            }

            var confirmationLink = Url.PartnerConfirmationLink(invitation.Id, partnerEmail);
            var callbackLink     = Url.PartnerConfirmationLinkCallback(invitation.Id, partnerEmail, confirmationLink, Request.Scheme);
            // Send the email
            string apiKey    = Configuration?.GetEmailSettings("apiKey");
            string apiSecret = Configuration?.GetEmailSettings("apiSecret");
            await EmailSender.SendMailjetAsync(apiKey, apiSecret, 1081044, "Du wurdest zum Großstadt Dinner eingeladen", "*****@*****.**", "Das Großstadt Dinner Team", partnerFirstName, partnerEmail, partnerFirstName + " " + partnerLastName, callbackLink, user.FirstName, dinnerEvent.EventName, dinnerEvent.EventDate.ToShortDateString());

            TempData["StatusMessage"] = @"Eine Einladung wurde an " + partnerEmail + " geschickt.";
            return(Page());
        }
        public async Task <IActionResult> GetDetails(int eventId)
        {
            IDatabaseContext context = _getDatabaseContext();
            Event            @event  = await context.Events
                                       .Include(e => e.Organizer)
                                       .Include(e => e.EventParticipations)
                                       .ThenInclude(p => p.Participant)
                                       .FirstOrDefaultAsync(e => e.Id == eventId);

            if (@event == null)
            {
                return(NotFound());
            }

            int currentUserId = HttpContext.GetUserId();

            ViewEventInformation viewEventInformation = ViewEventInformation.FromEvent(@event, currentUserId);

            if (!viewEventInformation.CurrentUserDoesParticipate && @event.IsPrivate && (@event.OrganizerId != currentUserId))
            {
                return(BadRequest(RequestStringMessages.InvitationRequired));
            }

            List <User> allParticipants = @event.EventParticipations.Select(e => e.Participant).ToList();

            List <Appointment> appointments = await context.Appointments
                                              .Include(a => a.AppointmentParticipations)
                                              .ThenInclude(ap => ap.Participant)
                                              .Where(a => a.StartTime >= DateTime.UtcNow)
                                              .OrderBy(a => a.StartTime)
                                              .Take(_maxShownAppointmentsPerEvent)
                                              .ToListAsync();

            List <AppointmentDetails> upcomingAppointments = appointments
                                                             .Select(a => AppointmentDetails.FromAppointment(a, currentUserId, allParticipants))
                                                             .ToList();

            EventParticipation currentEventParticipation = @event.EventParticipations.FirstOrDefault(e => e.ParticipantId == currentUserId);


            NotificationConfigurationResponse notificationConfigurationResponse = null;

            if (currentEventParticipation != null)
            {
                notificationConfigurationResponse = NotificationConfigurationResponse.FromParticipation(currentEventParticipation);
            }

            return(Ok(new EventDetails(viewEventInformation, upcomingAppointments, notificationConfigurationResponse)));
        }
Exemplo n.º 12
0
        public async Task AddParticipation(Event @event)
        {
            var usr = await GetCurrentUser();

            EventParticipation evtPart = new EventParticipation
            {
                Event            = @event,
                SubscriptionTime = DateTime.Now,
                Status           = ParticipationStatus.Confirmed,
                User             = usr
            };

            _db.Participations.Add(evtPart);
            await _db.SaveChangesAsync();
        }
Exemplo n.º 13
0
        /// <summary>
        /// Deletes an event, the events EventInfo, and its relation(EventParticipation)
        /// </summary>
        /// <param name="eventToDelete"></param>
        public static void DeleteEvent(Event eventToDelete)
        {
            List <EventParticipation> participationList = Db.SQL <EventParticipation>($"SELECT ep FROM {typeof(EventParticipation)} ep").ToList();
            EventParticipation        thisParticipation = participationList.Where(x => x.Event == eventToDelete).FirstOrDefault();

            Db.Transact(() =>
            {
                eventToDelete.EventInfo.Delete();
                eventToDelete.Delete();
                if (thisParticipation != null)
                {
                    thisParticipation.Delete();
                }
            });
        }
Exemplo n.º 14
0
        public async Task SaveEvent()
        {
            var selectedEvent = Events.FirstOrDefault(i => i.Id == NewEventParticipation.Event.Id);

            NewEventParticipation.Id           = Guid.NewGuid();
            NewEventParticipation.PointsEarned = selectedEvent.Points;
            NewEventParticipation.UserId       = Id;

            await _eventParticipationService.Create(NewEventParticipation);

            SelectedRelativeIndex = (DateTimeOffset.UtcNow.Month - NewEventParticipation.SubmissionDate.Month);

            await SetEventParticipations();

            //clear out UI
            NewEventParticipation = new EventParticipation();
        }
Exemplo n.º 15
0
        public async Task <IActionResult> JoinEvent(JoinEventDto joinEventDto)
        {
            IDatabaseContext context = _getDatabaseContext();
            {
                Event @event = await context.Events
                               .Include(e => e.EventParticipations)
                               .FirstOrDefaultAsync(e => e.Id == joinEventDto.EventId);

                if (@event == null)
                {
                    return(BadRequest(RequestStringMessages.EventNotFound));
                }

                User currentUser = await HttpContext.GetCurrentUserAsync(context);

                if (@event.EventParticipations.Any(e => e.Participant == currentUser))
                {
                    return(BadRequest(RequestStringMessages.UserAlreadyPartOfEvent));
                }

                if (@event.IsPrivate && (@event.Organizer != currentUser))
                {
                    return(BadRequest(RequestStringMessages.InvitationRequired));
                }

                var eventParticipation = new EventParticipation
                {
                    Event       = @event,
                    Participant = currentUser
                };

                context.EventParticipations.Add(eventParticipation);

                await context.SaveChangesAsync();

                _auditLogger.LogInformation("{0}(): Joined event {1}", nameof(JoinEvent), @event.Id);

                return(Ok());
            }
        }
Exemplo n.º 16
0
        public async Task <IActionResult> ConfigureNotifications(NotificationConfigurationDto notificationConfigurationDto)
        {
            IDatabaseContext context = _getDatabaseContext();
            int currentUserId        = HttpContext.GetUserId();

            EventParticipation participation = await context.EventParticipations.FirstOrDefaultAsync(e => (e.EventId == notificationConfigurationDto.EventId) && (e.ParticipantId == currentUserId));

            if (participation == null)
            {
                return(BadRequest(RequestStringMessages.UserNotPartOfEvent));
            }

            participation.SendReminderEmail          = notificationConfigurationDto.SendReminderEmail;
            participation.SendSummaryEmail           = notificationConfigurationDto.SendSummaryEmail;
            participation.SendLastMinuteChangesEmail = notificationConfigurationDto.SendLastMinuteChangesEmail;

            await context.SaveChangesAsync();

            _logger.LogInformation("{0}(): Updated notification settings", nameof(ConfigureNotifications));

            return(Ok());
        }
        public async Task ConfigureNotifications_GivenParticipatingEvent_NotificationsConfigured()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int eventId;
            int johnId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());
                User  organizer         = ContextUtilities.CreateRichardRoe();
                Event @event            = DummyEvent(organizer);
                context.Events.Add(@event);
                context.EventParticipations.Add(new EventParticipation {
                    Event = @event, Participant = john.Entity, SendLastMinuteChangesEmail = false, SendReminderEmail = false, SendSummaryEmail = false
                });

                await context.SaveChangesAsync();

                eventId = @event.Id;
                johnId  = john.Entity.Id;
            }

            // Act
            (ParticipateEventController participateEventController, _) = CreateController(getContext, johnId);

            IActionResult response = await participateEventController.ConfigureNotifications(new NotificationConfigurationDto { EventId = eventId, SendReminderEmail = true, SendSummaryEmail = true, SendLastMinuteChangesEmail = true });

            // Assert
            Assert.IsType <OkResult>(response);
            using (IDatabaseContext context = getContext())
            {
                EventParticipation eventParticipation = context.EventParticipations.Single();
                Assert.True(eventParticipation.SendSummaryEmail);
                Assert.True(eventParticipation.SendLastMinuteChangesEmail);
                Assert.True(eventParticipation.SendReminderEmail);
            }
        }
Exemplo n.º 18
0
 public Task Create(EventParticipation eventParticipation)
 {
     return(_proxy.Create(eventParticipation));
 }
Exemplo n.º 19
0
 public static NotificationConfigurationResponse FromParticipation(EventParticipation participation)
 {
     return(new NotificationConfigurationResponse(participation.SendReminderEmail, participation.SendSummaryEmail, participation.SendLastMinuteChangesEmail));
 }
Exemplo n.º 20
0
        /// <summary>
        /// Unregister from event method.
        /// </summary>
        /// <returns></returns>
        public async Task <IActionResult> OnGetEventUnregister()
        {
            if (HttpContext.Session.GetString("EventId") == null)
            {
                string returnUrl = HttpContext.Request.Path.ToString();
                return(RedirectToPage("/Account/Login", new { area = "Identity", returnUrl }));
            }

            var eventId     = int.Parse(HttpContext.Session.GetString("EventId"), CultureInfo.CurrentCulture);
            var dinnerEvent = DinnerEventsRepository.GetById(eventId);
            var user        = await UserManager.GetUserAsync(HttpContext.User);

            EventParticipation eventParticipation = EventParticipationsRepository.SearchFor(x => x.User == user && x.Event == dinnerEvent).FirstOrDefault();

            EventParticipationsRepository.Delete(eventParticipation);
            EventParticipationsRepository.SaveChanges();
            Team team = TeamsRepository.SearchFor(x => x.Event.Id == dinnerEvent.Id && (x.Partner1.Id == user.Id || x.Partner2.Id == user.Id)).Include("Partner1").Include("Partner2").FirstOrDefault();

            // Remove team
            if (team != null)
            {
                if (dinnerEvent.RoutesOpen)
                {
                    // Delete from existing routes
                    var routes = RoutesRepository.SearchFor(x => x.Event.Id == eventId && x.RouteForTeam.Id == team.Id)
                                 .Include(a => a.Event)
                                 .Include(a => a.RouteForTeam)
                                 .Include(a => a.FirstCourseHostTeam).ThenInclude(b => b.Partner1)
                                 .Include(a => a.FirstCourseHostTeam).ThenInclude(b => b.Partner2)
                                 .Include(a => a.FirstCourseGuestTeam1).ThenInclude(b => b.Partner1)
                                 .Include(a => a.FirstCourseGuestTeam1).ThenInclude(b => b.Partner2)
                                 .Include(a => a.FirstCourseGuestTeam2).ThenInclude(b => b.Partner1)
                                 .Include(a => a.FirstCourseGuestTeam2).ThenInclude(b => b.Partner2)
                                 .Include(a => a.SecondCourseHostTeam).ThenInclude(b => b.Partner1)
                                 .Include(a => a.SecondCourseHostTeam).ThenInclude(b => b.Partner2)
                                 .Include(a => a.SecondCourseGuestTeam1).ThenInclude(b => b.Partner1)
                                 .Include(a => a.SecondCourseGuestTeam1).ThenInclude(b => b.Partner2)
                                 .Include(a => a.SecondCourseGuestTeam2).ThenInclude(b => b.Partner1)
                                 .Include(a => a.SecondCourseGuestTeam2).ThenInclude(b => b.Partner2)
                                 .Include(a => a.ThirdCourseHostTeam).ThenInclude(b => b.Partner1)
                                 .Include(a => a.ThirdCourseHostTeam).ThenInclude(b => b.Partner2)
                                 .Include(a => a.ThirdCourseGuestTeam1).ThenInclude(b => b.Partner1)
                                 .Include(a => a.ThirdCourseGuestTeam1).ThenInclude(b => b.Partner2)
                                 .Include(a => a.ThirdCourseGuestTeam2).ThenInclude(b => b.Partner1)
                                 .Include(a => a.ThirdCourseGuestTeam2).ThenInclude(b => b.Partner2);
                    foreach (var route in routes)
                    {
                        if (route.RouteForTeam.Id == team.Id)
                        {
                            route.RouteForTeam = null;
                        }

                        if (route.FirstCourseHostTeam.Id == team.Id)
                        {
                            route.FirstCourseHostTeam = null;
                        }

                        if (route.FirstCourseGuestTeam1.Id == team.Id)
                        {
                            route.FirstCourseGuestTeam1 = null;
                        }

                        if (route.FirstCourseGuestTeam2.Id == team.Id)
                        {
                            route.FirstCourseGuestTeam2 = null;
                        }

                        if (route.SecondCourseHostTeam.Id == team.Id)
                        {
                            route.SecondCourseHostTeam = null;
                        }

                        if (route.SecondCourseGuestTeam1.Id == team.Id)
                        {
                            route.SecondCourseGuestTeam1 = null;
                        }

                        if (route.SecondCourseGuestTeam2.Id == team.Id)
                        {
                            route.SecondCourseGuestTeam2 = null;
                        }

                        if (route.ThirdCourseHostTeam.Id == team.Id)
                        {
                            route.ThirdCourseHostTeam = null;
                        }

                        if (route.ThirdCourseGuestTeam1.Id == team.Id)
                        {
                            route.ThirdCourseGuestTeam1 = null;
                        }

                        if (route.ThirdCourseGuestTeam2.Id == team.Id)
                        {
                            route.ThirdCourseGuestTeam2 = null;
                        }

                        RoutesRepository.Update(route);
                    }

                    RoutesRepository.SaveChanges();
                }

                // Remove contact from contact list
                string apiKey    = Configuration?.GetEmailSettings("apiKey");
                string apiSecret = Configuration?.GetEmailSettings("apiSecret");
                if (team.Partner1 != null)
                {
                    await EmailSender.RemoveListRecipientAsync(apiKey, apiSecret, team.Partner1.ListRecipientId);
                }

                if (team.Partner2 != null)
                {
                    await EmailSender.RemoveListRecipientAsync(apiKey, apiSecret, team.Partner2.ListRecipientId);
                }

                TeamsRepository.Delete(team);
                TeamsRepository.SaveChanges();
                TempData["StatusMessage"] = "Du hast dein Team vom Event abgemeldet.";
            }

            else
            {
                TempData["StatusMessage"] = "Du hast dich vom Event abgemeldet.";
            }

            return(RedirectToPage("RegistrationData", new { id = eventId }));
        }
Exemplo n.º 21
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (HttpContext.Session.GetString("EventId") == null)
            {
                string returnUrl = HttpContext.Request.Path.ToString();
                return(RedirectToPage("/Account/Login", new { area = "Identity", returnUrl }));
            }

            ViewData["IsParticipating"] = HttpContext.Session.GetString("IsParticipating");
            int         eventId     = int.Parse(HttpContext.Session.GetString("EventId"), CultureInfo.CurrentCulture);
            DinnerEvent dinnerEvent = DinnerEventsRepository.GetById(eventId);

            if (dinnerEvent != null)
            {
                // Values are passed-through to layout page
                ViewData["EventName"]        = dinnerEvent.EventName;
                ViewData["EventDate"]        = dinnerEvent.EventDate.ToShortDateString();
                ViewData["EventCity"]        = dinnerEvent.City;
                ViewData["EventPictureLink"] = dinnerEvent.EventPictureLink;
            }

            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await UserManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{UserManager.GetUserId(User)}'.");
            }

            // Load Team
            Team team = TeamsRepository.SearchFor(x => x.Event.Id == dinnerEvent.Id && (x.Partner1.Id == user.Id || x.Partner2.Id == user.Id)).Include("Partner1").Include("Partner2").Include("Event").FirstOrDefault();

            if (team != null)
            {
                team.DinnerSaver      = Input.DinnerSaver;
                team.SelectedCourse   = Input.SelectedCourse;
                team.AddressStreet    = Input.AddressStreet;
                team.AddressAdditions = Input.AddressAdditions;
                team.AddressNumber    = Input.AddressNumber;
                team.FullAddress      = Input.AddressStreet + " " + Input.AddressNumber;
                TeamsRepository.Update(team);
                TeamsRepository.SaveChanges();
                TempData["StatusMessage"] = @"Die Einstellungen für dein Team wurden gespeichert.";
            }

            else
            {
                EventParticipation participation = EventParticipationsRepository.SearchFor(x => x.User.Id == user.Id && x.Event.Id == eventId).FirstOrDefault();
                if (participation == null)
                {
                    participation = new EventParticipation
                    {
                        InvitationMailSent = true,
                        User                 = user,
                        Event                = dinnerEvent,
                        PartnerName          = Input.PartnerFirstName,
                        PartnerLastName      = Input.PartnerLastName,
                        PartnerEmail         = Input.PartnerEmail,
                        Address              = Input.AddressStreet,
                        AddressNumber        = Input.AddressNumber,
                        AddressAdditions     = Input.AddressAdditions,
                        Phone                = Input.Phone,
                        Allergies            = Input.Allergies,
                        SelectedCourse       = Input.SelectedCourse,
                        IsWithoutPartner     = Input.IsWithoutPartner,
                        DinnerSaver          = Input.DinnerSaver,
                        RegistrationComplete = true
                    };

                    EventParticipationsRepository.Insert(participation);
                    EventParticipationsRepository.SaveChanges();
                    // Add contact to Mailjet Contacts, save ContactId
                    string apiKey          = Configuration?.GetEmailSettings("apiKey");
                    string apiSecret       = Configuration?.GetEmailSettings("apiSecret");
                    long   listRecipientId = await EmailSender.AddContactToContactListAsync(apiKey, apiSecret, user.ContactId.ToString(CultureInfo.InvariantCulture), dinnerEvent.ContactList.ToString(CultureInfo.InvariantCulture));

                    user.ListRecipientId = listRecipientId;
                    await UserManager.UpdateAsync(user);
                }

                else
                {
                    participation.Phone                = Input.Phone;
                    participation.Allergies            = Input.Allergies;
                    participation.Address              = Input.AddressStreet;
                    participation.AddressNumber        = Input.AddressNumber;
                    participation.AddressAdditions     = Input.AddressAdditions;
                    participation.PartnerName          = Input.PartnerFirstName;
                    participation.PartnerLastName      = Input.PartnerLastName;
                    participation.PartnerEmail         = Input.PartnerEmail;
                    participation.SelectedCourse       = Input.SelectedCourse;
                    participation.IsWithoutPartner     = Input.IsWithoutPartner;
                    participation.DinnerSaver          = Input.DinnerSaver;
                    participation.RegistrationComplete = true;
                    EventParticipationsRepository.Update(participation);
                    EventParticipationsRepository.SaveChanges();
                }

                await OnPostSendPartnerInvitation(eventId, Input.PartnerFirstName, Input.PartnerLastName, Input.PartnerEmail, user.Id);

                TempData["StatusMessage"] = "Deine Anmeldung wurde gespeichert. Eine Einladung wurde an " + Input.PartnerEmail +
                                            " geschickt. Die Anmeldung ist vollständig sobald dein Partner bestätigt hat.";
            }

            return(RedirectToPage("./RegistrationData", eventId));
        }
        public async Task GetChatMessage_GivenInitialDataLoad_SubsetOfChatMessagesReturned()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int         johnDoeId;
            int         eventId;
            ChatMessage veryOldMessage;
            ChatMessage veryRecentMessage;
            int         amountOfChatMessages = _configuration.BaseAmountOfChatMessagesPerDetailPage = 5;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());

                Event dummyEvent = DummyEvent(john.Entity);
                context.Events.Add(dummyEvent);

                context.EventParticipations.Add(new EventParticipation {
                    Participant = john.Entity, Event = dummyEvent
                });

                // Add 2 more chat messages then we'll request to ensure it's based on the sent date
                veryOldMessage = new ChatMessage
                {
                    Event    = dummyEvent,
                    Author   = john.Entity,
                    Content  = "Very old chat message",
                    SentDate = DateTime.UtcNow - TimeSpan.FromDays(50)
                };
                veryRecentMessage = new ChatMessage
                {
                    Event    = dummyEvent,
                    Author   = john.Entity,
                    Content  = "Very recent chat message",
                    SentDate = DateTime.UtcNow
                };
                context.ChatMessages.Add(veryOldMessage);
                context.ChatMessages.Add(veryRecentMessage);

                for (var i = 1; i <= amountOfChatMessages; i++)
                {
                    context.ChatMessages.Add(new ChatMessage
                    {
                        Event    = dummyEvent,
                        Author   = john.Entity,
                        Content  = "Chat message #" + i,
                        SentDate = DateTime.UtcNow - TimeSpan.FromHours(i)
                    });
                }

                await context.SaveChangesAsync();

                johnDoeId = john.Entity.Id;
                eventId   = dummyEvent.Id;
            }

            // Act
            (EventChatController eventChatController, _) = CreateController(getContext, johnDoeId);

            IActionResult response = await eventChatController.GetChatMessages(new GetChatMessagesDto { EventId = eventId });

            // Assert
            Assert.IsType <OkObjectResult>(response);
            var okObjectResult    = (OkObjectResult)response;
            var eventChatMessages = okObjectResult.Value as EventChatMessages;

            Assert.NotNull(eventChatMessages);
            Assert.True(eventChatMessages.PossiblyMoreMessages);
            Assert.Equal(amountOfChatMessages, eventChatMessages.Messages.Count);
            Assert.Contains(eventChatMessages.Messages, m => m.SentDate == veryRecentMessage.SentDate);
            Assert.DoesNotContain(eventChatMessages.Messages, m => m.SentDate == veryOldMessage.SentDate);
            using (IDatabaseContext context = getContext())
            {
                EventParticipation loadedParticipation = await context.EventParticipations.SingleAsync();

                Assert.Equal(veryRecentMessage.SentDate, loadedParticipation.LastReadMessageSentDate);
            }
        }
Exemplo n.º 23
0
        public async Task <IActionResult> RemoveFromEvent(RemoveFromEventDto removeFromEventDto)
        {
            IDatabaseContext context      = _getDatabaseContext();
            User             userToRemove = await context.Users.FindAsync(removeFromEventDto.UserId);

            if (userToRemove == null)
            {
                return(BadRequest(RequestStringMessages.UserNotFound));
            }

            Event @event = await context.Events
                           .Include(e => e.Organizer)
                           .Include(e => e.EventParticipations)
                           .FirstOrDefaultAsync(e => e.Id == removeFromEventDto.EventId);

            if (@event == null)
            {
                return(BadRequest(RequestStringMessages.EventNotFound));
            }

            int currentUserId = HttpContext.GetUserId();

            bool changingOtherUser = currentUserId != userToRemove.Id;

            if (changingOtherUser && (@event.OrganizerId != currentUserId))
            {
                _logger.LogInformation("{0}(): Tried to remove user {1} from then event {2}, which he's not organizing", nameof(RemoveFromEvent), userToRemove.Id, @event.Id);

                return(BadRequest(RequestStringMessages.OrganizerRequired));
            }

            EventParticipation participation = @event.EventParticipations.FirstOrDefault(e => e.ParticipantId == userToRemove.Id);

            if (participation == null)
            {
                return(BadRequest(RequestStringMessages.UserNotPartOfEvent));
            }

            // Remove event participation
            context.EventParticipations.Remove(participation);

            // Remove appointment participations within the event
            List <AppointmentParticipation> appointmentParticipations = await context.AppointmentParticipations
                                                                        .Where(a => (a.ParticipantId == removeFromEventDto.UserId) && (a.Appointment.EventId == removeFromEventDto.EventId))
                                                                        .Include(ap => ap.Appointment)
                                                                        .ToListAsync();

            List <Appointment> appointmentsWithAcceptedResponse = appointmentParticipations
                                                                  .Where(ap => ap.AppointmentParticipationAnswer == AppointmentParticipationAnswer.Accepted)
                                                                  .Select(ap => ap.Appointment)
                                                                  .ToList();

            context.AppointmentParticipations.RemoveRange(appointmentParticipations);

            await context.SaveChangesAsync();

            // Handle notifications
            if (changingOtherUser)
            {
                _auditLogger.LogInformation("{0}(): The organizer removed the user {1} from the event {2}", nameof(RemoveFromEvent), userToRemove.Id, @event.Id);

                await _notificationService.NotifyOrganizerUpdatedUserInfoAsync(@event, userToRemove, "Der Organisator hat Sie vom Event entfernt.");
            }
            else
            {
                _auditLogger.LogInformation("{0}(): Left the event {1}", nameof(RemoveFromEvent), @event.Id);
            }

            foreach (Appointment appointment in appointmentsWithAcceptedResponse)
            {
                await _notificationService.SendLastMinuteChangeIfRequiredAsync(appointment);
            }

            return(Ok());
        }
        public async Task <IActionResult> SetAppointmentResponse(SetAppointmentResponseDto setAppointmentResponseDto)
        {
            IDatabaseContext context     = _getDatabaseContext();
            Appointment?     appointment = await context.Appointments
                                           .Include(a => a.Event)
                                           .ThenInclude(e => e.Organizer)
                                           .Include(a => a.Event)
                                           .ThenInclude(e => e.EventParticipations)
                                           .Include(a => a.AppointmentParticipations)
                                           .ThenInclude(ap => ap.Participant)
                                           .FirstOrDefaultAsync(a => a.Id == setAppointmentResponseDto.AppointmentId);

            if (appointment == null)
            {
                return(BadRequest(RequestStringMessages.AppointmentNotFound));
            }

            User userToSetResponseFor = await context.Users.FindAsync(setAppointmentResponseDto.UserId);

            if (userToSetResponseFor == null)
            {
                return(BadRequest(RequestStringMessages.UserNotFound));
            }

            User currentUser = await HttpContext.GetCurrentUserAsync(context);

            bool changingOtherUser = currentUser != userToSetResponseFor;

            bool userIsPartOfEvent = appointment.Event.EventParticipations.Any(e => e.ParticipantId == userToSetResponseFor.Id);

            if (changingOtherUser)
            {
                if (appointment.Event.Organizer != currentUser)
                {
                    // Only the organizer is allowed to change another user
                    _logger.LogInformation("{0}(): Tried to set response for user {1} for the appointment {2}, which he's not organizing", nameof(SetAppointmentResponse), userToSetResponseFor.Id, appointment.Id);

                    return(BadRequest(RequestStringMessages.OrganizerRequired));
                }

                if (!userIsPartOfEvent)
                {
                    // A organizer shouldn't be able to add a user to the event, unless the user is participating in the event
                    // This should prevent that a user gets added to an event he never had anything to do with
                    return(BadRequest(RequestStringMessages.UserNotPartOfEvent));
                }
            }

            // Ensure a user can't participate in a private event without an invitation
            if (!userIsPartOfEvent && appointment.Event.IsPrivate && (appointment.Event.Organizer != currentUser))
            {
                return(BadRequest(RequestStringMessages.InvitationRequired));
            }

            AppointmentParticipation appointmentParticipation = appointment.AppointmentParticipations.FirstOrDefault(e => e.ParticipantId == userToSetResponseFor.Id);

            if (appointmentParticipation == null)
            {
                // Create a new participation if there isn't an existing one
                appointmentParticipation = new AppointmentParticipation
                {
                    Participant = userToSetResponseFor,
                    Appointment = appointment
                };

                context.AppointmentParticipations.Add(appointmentParticipation);
            }

            bool changeRelevantForSummary =
                (appointmentParticipation.AppointmentParticipationAnswer == AppointmentParticipationAnswer.Accepted) ||
                (setAppointmentResponseDto.Response == AppointmentParticipationAnswer.Accepted);

            appointmentParticipation.AppointmentParticipationAnswer = setAppointmentResponseDto.Response;

            if (!appointment.Event.EventParticipations.Select(e => e.ParticipantId).Contains(currentUser.Id))
            {
                // Automatically add a user to an event if he's not yet part of it
                var eventParticipation = new EventParticipation
                {
                    Event       = appointment.Event,
                    Participant = currentUser
                };

                context.EventParticipations.Add(eventParticipation);

                _auditLogger.LogInformation("{0}(): Joined event {1} automatically after joining appointment {2}", nameof(SetAppointmentResponse), appointment.Event.Id, appointment.Id);
            }

            await context.SaveChangesAsync();

            // Handle notifications
            if (changingOtherUser)
            {
                _auditLogger.LogInformation("{0}(response={1}): The organizer set the response to the appointment {2} for user {3}", nameof(SetAppointmentResponse), setAppointmentResponseDto.Response, appointment.Id, userToSetResponseFor.Id);

                await _notificationService.NotifyOrganizerUpdatedUserInfoAsync(appointment.Event, userToSetResponseFor, "Der Organisator hat Ihre Zusage an einem Termin editiert.");
            }
            else
            {
                _logger.LogDebug("{0}(response={1}): Set own response for appointment {2}", nameof(SetAppointmentResponse), setAppointmentResponseDto.Response, appointment.Id);
            }

            if (changeRelevantForSummary)
            {
                // Don't send a last minute change if the response change is irrelevant
                // E.g. Changing from No Answer to Declined
                await _notificationService.SendLastMinuteChangeIfRequiredAsync(appointment);
            }
            else
            {
                _logger.LogDebug("{0}(response={1}): Intentionally skipped last minute change as the change wasn't relevant for the summary", nameof(SetAppointmentResponse), setAppointmentResponseDto.Response, appointment.Id);
            }

            return(Ok());
        }
 public static EventParticipantInformation FromParticipation(EventParticipation participation)
 {
     return(new EventParticipantInformation(participation.Participant.Id, participation.Participant.FullName, participation.Participant.Email));
 }
        public async Task <IActionResult> OnGet(int invitationId, string email, string returnUrl = null)
        {
            // Return if invitation is already accepted
            Invitation invitation = InvitationsRepository.SearchFor(x => x.Id == invitationId).Include("User").Include("Event").FirstOrDefault();

            if (invitation.InvitationAccepted)
            {
                // Display page?
                return(RedirectToAction("Index", "Home"));
            }

            ApplicationUser invitee = await _userManager.FindByEmailAsync(email);

            if (invitee == null)
            {
                // If user doesn't exist, redirect to Register page
                return(RedirectToPage("/Account/Register", new { area = "Identity", returnUrl }));
            }

            DinnerEvent        dinnerEvent          = DinnerEventsRepository.GetById(invitation.Event.Id);
            EventParticipation inviteeParticipation = EventParticipationsRepository.SearchFor(x => x.User.Id == invitee.Id && x.Event.Id == invitation.Event.Id).FirstOrDefault();

            if (inviteeParticipation == null)
            {
                inviteeParticipation = new EventParticipation {
                    User = invitee, Event = dinnerEvent
                };
                EventParticipationsRepository.Insert(inviteeParticipation);
                EventParticipationsRepository.SaveChanges();
            }

            invitation.InvitationAccepted = true;
            InvitationsRepository.Update(invitation);
            // Check if user has more pending invitations and make them invalid
            var otherInvitations = InvitationsRepository.SearchFor(x => x.User.Id == invitee.Id);

            foreach (var otherInvitation in otherInvitations)
            {
                otherInvitation.InvitationAccepted = true;
                InvitationsRepository.Update(otherInvitation);
            }

            InvitationsRepository.SaveChanges();
            // Add contact to Mailjet Contacts, save ContactId
            string apiKey    = Configuration?.GetEmailSettings("apiKey");
            string apiSecret = Configuration?.GetEmailSettings("apiSecret");
            // Save list recipient id to database
            long listRecipientId = await EmailSender.AddContactToContactListAsync(apiKey, apiSecret, invitee.ContactId.ToString(CultureInfo.InvariantCulture), dinnerEvent.ContactList.ToString(CultureInfo.InvariantCulture));

            invitee.ListRecipientId = listRecipientId;
            await _userManager.UpdateAsync(invitee);

            EventParticipation inviterParticipation = EventParticipationsRepository.SearchFor(x => x.User.Id == invitation.User.Id && x.Event.Id == invitation.Event.Id).FirstOrDefault();
            // Create a new team
            Team newTeam = new Team
            {
                Partner1         = invitation.User,
                Partner2         = invitee,
                SelectedCourse   = inviterParticipation?.SelectedCourse,
                AddressStreet    = inviterParticipation.Address,
                AddressNumber    = inviterParticipation.AddressNumber,
                FullAddress      = inviterParticipation.Address + " " + inviterParticipation.AddressNumber,
                AddressAdditions = inviterParticipation.AddressAdditions,
                Phone            = inviterParticipation.Phone,
                DinnerSaver      = inviterParticipation.DinnerSaver,
                Event            = invitation.Event,
                Allergies        = inviterParticipation.Allergies,
                City             = dinnerEvent.City
            };

            TeamsRepository.Insert(newTeam);
            TeamsRepository.SaveChanges();
            // Send the email
            await EmailSender.SendMailjetAsync(apiKey, apiSecret, 1197519, "Deine Einladung wurde angenommen", "*****@*****.**", "Das Großstadt Dinner Team", invitation.User.FirstName, invitation.User.Email, invitation.User.FirstName + " " + invitation.User.LastName, "", invitee.FirstName, invitation.Event.EventName, invitation.Event.EventDate.ToShortDateString());

            TempData["StatusMessage"] = @"Du hast die Einladung erfolgreich angenommen. Die Teamdaten deines Partners wurden übernommen. Ihr seid nun vollständig angemeldet.";
            return(RedirectToPage("./RegistrationData"));
        }
Exemplo n.º 27
0
        /// <summary>
        /// Returns the RegistrationData page.
        /// </summary>
        /// <param name="eventId"></param>
        /// <returns></returns>
        public async Task <IActionResult> OnGetAsync(int eventId)
        {
            var user = await UserManager.GetUserAsync(HttpContext.User);

            bool isSignedIn = SignInManager.IsSignedIn(User);

            if (!isSignedIn)
            {
                string returnUrl = HttpContext.Request.Path.ToString() + "?eventid=" + eventId;
                return(RedirectToPage("/Account/Login", new { area = "Identity", returnUrl }));
            }

            // Get eventId
            if (eventId == 0)
            {
                if (HttpContext.Session.GetString("EventId") == null)
                {
                    string returnUrl = HttpContext.Request.Path.ToString();
                    return(RedirectToPage("/Account/Login", new { area = "Identity", returnUrl }));
                }

                eventId = int.Parse(HttpContext.Session.GetString("EventId"), CultureInfo.CurrentCulture);
            }

            else
            {
                HttpContext.Session.SetString("EventId", eventId.ToString(CultureInfo.CurrentCulture));
            }

            // Get eventTitle
            DinnerEvent dinnerEvent = DinnerEventsRepository.GetById(eventId);

            if (dinnerEvent != null)
            {
                // Values are passed-through to layout page
                ViewData["EventName"]        = dinnerEvent.EventName;
                ViewData["EventDate"]        = dinnerEvent.EventDate.ToShortDateString();
                ViewData["EventCity"]        = dinnerEvent.City;
                ViewData["EventPictureLink"] = dinnerEvent.EventPictureLink;
                ViewData["EventId"]          = eventId;
            }

            IsParticipating             = IsUserParticipating(eventId, user.Id);
            ViewData["IsParticipating"] = IsParticipating.ToString(CultureInfo.CurrentCulture);
            HttpContext.Session.SetString("IsParticipating", IsParticipating.ToString(CultureInfo.CurrentCulture));
            // Load EventParticipation
            EventParticipation eventParticipation = EventParticipationsRepository.SearchFor(x => x.User.Id == user.Id && x.Event.Id == eventId).FirstOrDefault();

            if (eventParticipation == null)
            {
                eventParticipation = new EventParticipation
                {
                    User  = user,
                    Event = dinnerEvent
                };
            }

            Input = new InputModel();

            // Load Team
            Team team = TeamsRepository.SearchFor(x => x.Event.Id == dinnerEvent.Id && (x.Partner1.Id == user.Id || x.Partner2.Id == user.Id)).Include("Partner1").Include("Partner2").Include("Event").FirstOrDefault();

            if (team != null)
            {
                string partnerFirstName = "";
                string partnerLastName  = "";
                string partnerEmail     = "";
                if (team.Partner1.Id == user.Id)
                {
                    partnerFirstName = team.Partner2.FirstName;
                    partnerLastName  = team.Partner2.LastName;
                    partnerEmail     = team.Partner2.Email;
                }

                else
                {
                    partnerFirstName = team.Partner1.FirstName;
                    partnerLastName  = team.Partner1.LastName;
                    partnerEmail     = team.Partner1.Email;
                }

                Team  = team;
                Event = team.Event;
                Input.SelectedCourse   = team.SelectedCourse;
                Input.FirstName        = user.FirstName;
                Input.LastName         = user.LastName;
                Input.Email            = user.Email;
                Input.Phone            = team.Phone;
                Input.Allergies        = team.Allergies;
                Input.AddressStreet    = team.AddressStreet;
                Input.AddressAdditions = team.AddressAdditions;
                Input.AddressNumber    = team.AddressNumber;
                Input.PartnerFirstName = partnerFirstName;
                Input.PartnerLastName  = partnerLastName;
                Input.PartnerEmail     = partnerEmail;
                Input.DinnerSaver      = team.DinnerSaver;
                Input.IsWithoutPartner = eventParticipation.IsWithoutPartner;
            }

            else
            {
                Team  = null;
                Event = eventParticipation.Event;
                Input.SelectedCourse   = eventParticipation.SelectedCourse;
                Input.FirstName        = user.FirstName;
                Input.LastName         = user.LastName;
                Input.Email            = user.Email;
                Input.Phone            = eventParticipation.Phone;
                Input.Allergies        = eventParticipation.Allergies;
                Input.AddressStreet    = eventParticipation.Address;
                Input.AddressAdditions = eventParticipation.AddressAdditions;
                Input.AddressNumber    = eventParticipation.AddressNumber;
                Input.PartnerFirstName = eventParticipation.PartnerName;
                Input.PartnerLastName  = eventParticipation.PartnerLastName;
                Input.PartnerEmail     = eventParticipation.PartnerEmail;
                Input.DinnerSaver      = eventParticipation.DinnerSaver;
                Input.IsWithoutPartner = eventParticipation.IsWithoutPartner;
            }

            return(Page());
        }