Esempio n. 1
0
        public IActionResult SaveActivity([FromBody] EditableActivity activity)
        {
            var myId = User.GetId();

            if (activity.Id > 0 && !_resourceAuthorizationService.IsOwnerOf(activity.Id, myId))
            {
                return(Forbid());
            }

            var activityResult = _turnService.SaveActivity(activity, myId);

            if (activityResult.IsSuccess)
            {
                return(Json(activityResult.Value));
            }

            if (activityResult.Error.Invalid)
            {
                return(BadRequest(activityResult.Error.Message));
            }

            return(StatusCode(500));
        }
Esempio n. 2
0
        public Result <ActivityDetails, ValidityError> SaveActivity(EditableActivity activity, int ownerId)
        {
            try
            {
                if (activity is null)
                {
                    return(ValidityError.ForInvalidObject <ActivityDetails>("no activity provided"));
                }

                if (string.IsNullOrWhiteSpace(activity.Name))
                {
                    return(ValidityError.ForInvalidObject <ActivityDetails>("empty name"));
                }

                TimeSpan?period = null;
                if (!activity.PeriodUnit.HasValue)
                {
                    activity.PeriodCount = null;
                }
                else if (!activity.PeriodCount.HasValue)
                {
                    activity.PeriodUnit = null;
                }
                else if (activity.PeriodCount.Value == 0)
                {
                    return(ValidityError.ForInvalidObject <ActivityDetails>("invalid period count"));
                }
                else
                {
                    switch (activity.PeriodUnit.Value)
                    {
                    case Unit.Hour:
                        period = TimeSpan.FromHours(activity.PeriodCount.Value);
                        break;

                    case Unit.Day:
                        period = TimeSpan.FromDays(activity.PeriodCount.Value);
                        break;

                    case Unit.Week:
                        period = TimeSpan.FromDays(7 * activity.PeriodCount.Value);
                        break;

                    case Unit.Month:
                        period = TimeSpan.FromDays(365.25 / 12 * activity.PeriodCount.Value);
                        break;

                    case Unit.Year:
                        period = TimeSpan.FromDays(365.25 * activity.PeriodCount.Value);
                        break;

                    default:
                        return(ValidityError.ForInvalidObject <ActivityDetails>("invalid period unit"));
                    }
                }

                activity.Participants ??= new List <UserInfo>();

                // sanitize the default notification settings to ensure there's only one per type
                var defaultNotificationSettings =
                    (activity.DefaultNotificationSettings ?? new List <NotificationInfo>())
                    .Where(x => x.AnyActive && x.Type.IsAllowed(activity.TakeTurns))
                    .GroupBy(x => x.Type)
                    .Select(g => g.First())
                    .ToDictionary(x => x.Type);

                if (activity.Id < 0)
                {
                    return(ValidityError.ForInvalidObject <ActivityDetails>("invalid ID"));
                }

                var userIds = activity.Participants.Select(p => p.Id).Append(ownerId).ToHashSet();

                var      add = false;
                Activity activityToUpdate;
                if (activity.Id == 0)
                {
                    add = true;
                    activityToUpdate = new Activity
                    {
                        Participants = _db.Users.Where(user => userIds.Contains(user.Id)).ToList().Select(CreateNewParticipant).ToList(),
                        DefaultNotificationSettings = _mapper.Map <List <DefaultNotificationSetting> >(defaultNotificationSettings.Values),
                        Owner = _db.Users.Find(ownerId),
                        Turns = new List <Turn>(0)
                    };
                    foreach (var participant in activityToUpdate.Participants)
                    {
                        participant.NotificationSettings.AddRange(_mapper.Map <List <NotificationSetting> >(defaultNotificationSettings.Values));
                    }
                }
                else
                {
                    activityToUpdate = GetActivity(activity.Id, false, true, true);
                    if (activityToUpdate is null)
                    {
                        return(ValidityError.ForInvalidObject <ActivityDetails>("invalid ID"));
                    }

                    if (activityToUpdate.IsDisabled)
                    {
                        return(ValidityError.ForInvalidObject <ActivityDetails>("activity is disabled"));
                    }

                    // remove any participants that should no longer be there
                    activityToUpdate.Participants.RemoveAll(x => !userIds.Contains(x.UserId));

                    // remove any existing participants from the list so we're left with only new participants
                    userIds.ExceptWith(activityToUpdate.Participants.Select(x => x.UserId));

                    // add new participants
                    activityToUpdate.Participants.AddRange(_db.Users.Where(user => userIds.Contains(user.Id)).ToList().Select(CreateNewParticipant));

                    // remove any default notifications that should no longer be there
                    activityToUpdate.DefaultNotificationSettings.RemoveAll(x =>
                    {
                        var remove = !defaultNotificationSettings.ContainsKey(x.Type);

                        if (remove)
                        {
                            foreach (var participant in activityToUpdate.Participants)
                            {
                                participant.NotificationSettings.RemoveAll(y => y.Type == x.Type && y.Origin == NotificationOrigin.Default);
                            }
                        }

                        return(remove);
                    });

                    // remove any participant notifications that are no longer valid because the activity no longer has turns needed
                    if (activityToUpdate.TakeTurns && !activity.TakeTurns)
                    {
                        foreach (var participant in activityToUpdate.Participants)
                        {
                            participant.NotificationSettings.RemoveAll(x => !x.Type.IsAllowed(activity.TakeTurns));
                        }
                    }

                    // update any existing default notification and remove it from the new list
                    foreach (var noteToUpdate in activityToUpdate.DefaultNotificationSettings)
                    {
                        if (defaultNotificationSettings.Remove(noteToUpdate.Type, out var updatedNote))
                        {
                            _mapper.Map(updatedNote, noteToUpdate);

                            // update any existing participant notifications that originated from a default notification
                            foreach (var participantNote in activityToUpdate.Participants.SelectMany(x => x.NotificationSettings).Where(x => x.Type == updatedNote.Type && x.Origin == NotificationOrigin.Default))
                            {
                                //make sure we don't clear the participant ID
                                updatedNote.ParticipantId = participantNote.ParticipantId;
                                _mapper.Map(updatedNote, participantNote);
                            }
                        }
                    }

                    // add any remaining notifications
                    foreach (var note in defaultNotificationSettings.Values)
                    {
                        activityToUpdate.DefaultNotificationSettings.Add(_mapper.Map <DefaultNotificationSetting>(note));
                        foreach (var participant in activityToUpdate.Participants.Where(participant =>
                                                                                        participant.NotificationSettings.All(x => x.Type != note.Type)))
                        {
                            participant.NotificationSettings.Add(_mapper.Map <NotificationSetting>(note));
                        }
                    }
                }

                activityToUpdate.OwnerId     = ownerId;
                activityToUpdate.Name        = activity.Name;
                activityToUpdate.Description = string.IsNullOrWhiteSpace(activity.Description)
                    ? null
                    : activity.Description.Trim();
                activityToUpdate.PeriodCount = activity.PeriodCount;
                activityToUpdate.PeriodUnit  = activity.PeriodUnit;
                activityToUpdate.Period      = period;
                activityToUpdate.TakeTurns   = activity.TakeTurns;

                if (add)
                {
                    _db.Activities.Add(activityToUpdate);
                }
                else
                {
                    _db.Activities.Update(activityToUpdate);
                }

                var details = ActivityDetails.Calculate(activityToUpdate, ownerId, _mapper);

                _db.SaveChanges();
                details.Update(activityToUpdate);
                return(Result.Success <ActivityDetails, ValidityError>(details));
            }
            catch (Exception e)
            {
                var message = $"Failed to save activity '{activity?.Id}'";
                _logger.LogError(e, message);
                return(ValidityError.ForInvalidObject <ActivityDetails>(message));
            }

            Participant CreateNewParticipant(User user)
            {
                return(new Participant
                {
                    UserId = user.Id,
                    User = user,
                    DismissUntilTimeOfDay = _appSettings.Value.PushNotifications.DefaultDismissTime,
                    NotificationSettings = new List <NotificationSetting>()
                });
            }
        }