Beispiel #1
0
        public async Task UpdateMonitorAsync(MonitorDto monitorDto, UserAndOrganizationDto userAndOrganizationDto)
        {
            var monitor = await _monitorsDbSet.FirstOrDefaultAsync(x => x.Id == monitorDto.Id &&
                                                                   x.OrganizationId == userAndOrganizationDto.OrganizationId);

            if (monitor == null)
            {
                throw new ValidationException(ErrorCodes.ContentDoesNotExist, "Monitor does not exist");
            }

            var nameAlreadyExist = await _monitorsDbSet.AnyAsync(x => x.Name == monitorDto.Name &&
                                                                 x.OrganizationId == userAndOrganizationDto.OrganizationId);

            if (monitorDto.Name != monitor.Name && nameAlreadyExist)
            {
                throw new ValidationException(ErrorCodes.DuplicatesIntolerable, "Monitor names should be unique");
            }

            monitor.Name       = monitorDto.Name;
            monitor.Modified   = DateTime.UtcNow;
            monitor.ModifiedBy = userAndOrganizationDto.UserId;

            await _uow.SaveChangesAsync(false);
        }
        public async Task Should_Return_Supported_Languages_And_Timezones_With_User_Selected_In_First_Position()
        {
            // Arrange
            var users = new List <ApplicationUser>
            {
                new ApplicationUser {
                    Id = "user1", OrganizationId = 2, CultureCode = "en-US", TimeZone = "Pacific Standard Time"
                }
            };

            _usersDbSet.SetDbSetDataForAsync(users);

            var userOrg = new UserAndOrganizationDto {
                UserId = "user1", OrganizationId = 2
            };

            // Act
            var result = await _userService.GetUserLocalizationSettingsAsync(userOrg);

            // Assert
            Assert.IsInstanceOf <LocalizationSettingsDto>(result);
            Assert.AreEqual(CultureInfo.GetCultureInfo("en-US").DisplayName, result.Languages.First(x => x.IsSelected).DisplayName);
            Assert.AreEqual(TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time").DisplayName, result.TimeZones.First(x => x.IsSelected).DisplayName);
        }
Beispiel #3
0
        public async Task ReportBookAsync(BookReportDto bookReport, UserAndOrganizationDto userAndOrg)
        {
            var reportedOfficeBook = await _bookOfficesDbSet
                                     .Include(p => p.Book)
                                     .FirstAsync(p => p.Id == bookReport.BookOfficeId);

            var user = await _userService.GetApplicationUserAsync(userAndOrg.UserId);

            var receivers = await _roleService.GetAdministrationRoleEmailsAsync(userAndOrg.OrganizationId);

            var organization = await _organizationService.GetOrganizationByIdAsync(userAndOrg.OrganizationId);

            var userNotificationSettingsUrl = _appSettings.UserNotificationSettingsUrl(organization.ShortName);
            var bookUrl = _appSettings.BookUrl(organization.ShortName, bookReport.BookOfficeId, reportedOfficeBook.OfficeId);

            var subject = $"Reported book: {reportedOfficeBook.Book.Title}";
            var bookReportTemplateViewModel = new BookReportEmailTemplateViewModel(reportedOfficeBook.Book.Title, reportedOfficeBook.Book.Author,
                                                                                   bookReport.Report, bookReport.Comment, bookUrl, user.FullName, userNotificationSettingsUrl);

            var content   = _mailTemplate.Generate(bookReportTemplateViewModel, EmailPremiumTemplateCacheKeys.BookReport);
            var emailData = new EmailDto(receivers, subject, content);

            await _mailingService.SendEmailAsync(emailData);
        }
        public async Task Should_Return_Successfully_Updated_Service_Request_As_Request_Creator()
        {
            MockServiceRequestForUpdate();
            MockServiceRequestCategories();
            MockServiceRequestPriorities();
            MockServiceRequestStatuses();
            MockPermissioService();

            var serviceRequestDto = new ServiceRequestDto
            {
                Id          = 1,
                Description = "testDescription",
                PriorityId  = 1,
                ServiceRequestCategoryId = 1,
                Title    = "tetsTitle",
                StatusId = 2
            };

            var userAndOrg = new UserAndOrganizationDto
            {
                OrganizationId = 1,
                UserId         = "UserId"
            };

            await _serviceRequestService.UpdateServiceRequestAsync(serviceRequestDto, userAndOrg);

            var updatedServiceRequest = await _serviceRequestsDbSet.FirstAsync(x => x.Id == serviceRequestDto.Id);

            Assert.AreEqual(null, updatedServiceRequest.CategoryName);
            Assert.AreEqual(null, updatedServiceRequest.Title);
            Assert.AreEqual(serviceRequestDto.PriorityId, updatedServiceRequest.PriorityId);
            Assert.AreEqual(null, updatedServiceRequest.KudosAmmount);
            Assert.AreEqual(1, updatedServiceRequest.StatusId);

            await _uow.Received(1).SaveChangesAsync(false);
        }
        public async Task <IEnumerable <string> > GetWallMembersIdsAsync(int wallId, UserAndOrganizationDto userOrg)
        {
            var wallExists = await _wallsDbSet.AnyAsync(wall =>
                                                        wall.Id == wallId &&
                                                        wall.OrganizationId == userOrg.OrganizationId);

            if (!wallExists)
            {
                throw new ValidationException(ErrorCodes.WallNotFound, "Wall not found");
            }

            var wallMembers = await _wallUsersDbSet
                              .Include(u => u.Wall)
                              .Include(u => u.User)
                              .Where(u =>
                                     u.WallId == wallId &&
                                     u.Wall.OrganizationId == userOrg.OrganizationId)
                              .Where(u => u.UserId != userOrg.UserId)
                              .Select(u => u.UserId)
                              .Distinct()
                              .ToListAsync();

            return(wallMembers);
        }
        public async Task AddModeratorAsync(int wallId, string responsibleUserId, UserAndOrganizationDto userId)
        {
            var wall = await _wallsDbSet
                       .Include(x => x.Moderators)
                       .SingleAsync(x => x.Id == wallId && x.OrganizationId == userId.OrganizationId);

            if (wall.Moderators.Any(x => x.UserId == responsibleUserId))
            {
                return;
            }

            var newModerator = new WallModerator
            {
                WallId = wallId,
                UserId = responsibleUserId
            };

            await AddMemberToWallsAsync(responsibleUserId, new List <int> {
                wallId
            });

            _moderatorsDbSet.Add(newModerator);
            await _uow.SaveChangesAsync(userId.UserId);
        }
Beispiel #7
0
        public async Task ApproveKudosAsync(int kudosLogId, UserAndOrganizationDto userOrg)
        {
            var kudosLog = await _kudosLogsDbSet
                           .Include(x => x.Employee)
                           .FirstAsync(x => x.Id == kudosLogId && x.OrganizationId == userOrg.OrganizationId);

            kudosLog.Approve(userOrg.UserId);

            if (!kudosLog.IsRecipientDeleted())
            {
                if (kudosLog.IsMinus())
                {
                    _asyncRunner.Run <IKudosNotificationService>(async notifier => await notifier.NotifyApprovedKudosDecreaseRecipientAsync(kudosLog), _uow.ConnectionName);
                }
                else
                {
                    _asyncRunner.Run <IKudosNotificationService>(async notifier => await notifier.NotifyApprovedKudosRecipientAsync(kudosLog), _uow.ConnectionName);
                }
            }

            await _uow.SaveChangesAsync(false);

            await UpdateProfileKudosAsync(kudosLog.Employee, userOrg);
        }
Beispiel #8
0
        public async Task ToggleLikeAsync(AddLikeDto addLikeDto, UserAndOrganizationDto userOrg)
        {
            var comment = await _commentsDbSet
                          .Include(x => x.Post.Wall)
                          .FirstOrDefaultAsync(x => x.Id == addLikeDto.Id && x.Post.Wall.OrganizationId == userOrg.OrganizationId);

            if (comment == null)
            {
                throw new ValidationException(ErrorCodes.ContentDoesNotExist, "Comment does not exist");
            }

            var like = comment.Likes.FirstOrDefault(x => x.UserId == userOrg.UserId);

            if (like == null)
            {
                comment.Likes.Add(new Like(userOrg.UserId, addLikeDto.Type));
            }
            else
            {
                comment.Likes.Remove(like);
            }

            await _uow.SaveChangesAsync(userOrg.UserId);
        }
        public async Task <IEnumerable <EventOptionCountDto> > GetEventChosenOptionsAsync(Guid eventId, UserAndOrganizationDto userAndOrg)
        {
            var eventOptions = await _eventOptionsDbSet
                               .Include(e => e.EventParticipants)
                               .Include(e => e.Event)
                               .Where(e => e.EventId == eventId &&
                                      e.Event.OrganizationId == userAndOrg.OrganizationId &&
                                      e.EventParticipants.Any(x => x.EventId == eventId))
                               .Select(e => new EventOptionCountDto
            {
                Option = e.Option,
                Count  = e.EventParticipants.Count(x => x.EventId == eventId)
            })
                               .ToListAsync();

            return(eventOptions);
        }
Beispiel #10
0
        public async Task UpdateServiceRequestAsync(ServiceRequestDto serviceRequestDto, UserAndOrganizationDto userAndOrganizationDto)
        {
            var serviceRequest = await _serviceRequestsDbSet
                                 .Include(x => x.Status)
                                 .FirstOrDefaultAsync(x => x.Id == serviceRequestDto.Id && x.OrganizationId == userAndOrganizationDto.OrganizationId);

            if (serviceRequest == null)
            {
                throw new ValidationException(ErrorCodes.ContentDoesNotExist, "Service request does not exist");
            }

            if (serviceRequest.Status.Title == ServiceRequestStatusDone && serviceRequest.CategoryName == ServiceRequestCategoryKudos)
            {
                throw new ValidationException(PremiumErrorCodes.ServiceRequestIsClosed, "Kudos request status is done");
            }

            await ValidateServiceRequestForCreateAsync(serviceRequestDto);
            await ValidateServiceRequestForUpdateAsync(serviceRequestDto);

            var serviceRequestCategory = await _serviceRequestCategoryDbSet.FirstOrDefaultAsync(x => x.Id == serviceRequestDto.ServiceRequestCategoryId);

            if (serviceRequestCategory == null)
            {
                throw new ValidationException(ErrorCodes.ContentDoesNotExist, "Service request category does not exist");
            }

            var isServiceRequestAdmin = await _permissionService.UserHasPermissionAsync(userAndOrganizationDto, AdministrationPermissions.ServiceRequest);

            var isServiceRequestCreator          = serviceRequest.EmployeeId == userAndOrganizationDto.UserId;
            var isServiceRequestCategoryAssignee = (await GetCategoryAssigneesAsync(serviceRequest.CategoryName)).Contains(userAndOrganizationDto.UserId);

            var statusHasBeenChanged = serviceRequest.StatusId != serviceRequestDto.StatusId && isServiceRequestAdmin;

            if (!isServiceRequestAdmin && !isServiceRequestCreator && !isServiceRequestCategoryAssignee)
            {
                throw new UnauthorizedAccessException();
            }

            if (isServiceRequestAdmin || isServiceRequestCategoryAssignee)
            {
                serviceRequest.Title        = serviceRequestDto.Title;
                serviceRequest.StatusId     = serviceRequestDto.StatusId;
                serviceRequest.CategoryName = serviceRequestCategory.Name;
                serviceRequest.KudosAmmount = serviceRequestDto.KudosAmmount;
            }

            serviceRequest.PriorityId  = serviceRequestDto.PriorityId;
            serviceRequest.Description = serviceRequestDto.Description;
            serviceRequest.PictureId   = serviceRequestDto.PictureId;
            serviceRequest.UpdateMetadata(userAndOrganizationDto.UserId);

            await _uow.SaveChangesAsync(false);

            if (!statusHasBeenChanged)
            {
                return;
            }

            var statusDto = new UpdatedServiceRequestDto
            {
                ServiceRequestId = serviceRequestDto.Id,
                NewStatusId      = serviceRequest.StatusId
            };

            _asyncRunner.Run <IServiceRequestNotificationService>(async notifier => await notifier.NotifyAboutServiceRequestStatusUpdateAsync(statusDto, userAndOrganizationDto), _uow.ConnectionName);
        }
Beispiel #11
0
 private static LotteryParticipant MapNewLotteryParticipant(BuyLotteryTicketDto lotteryTicketDto, UserAndOrganizationDto userOrg)
 {
     return(new LotteryParticipant
     {
         LotteryId = lotteryTicketDto.LotteryId,
         UserId = userOrg.UserId,
         Joined = DateTime.Now,
         CreatedBy = userOrg.UserId,
         ModifiedBy = userOrg.UserId,
         Modified = DateTime.Now,
         Created = DateTime.Now
     });
 }
Beispiel #12
0
 public async Task <IEnumerable <LotteryDetailsDto> > GetFilteredLotteriesAsync(string filter, UserAndOrganizationDto userOrg)
 {
     return(await _lotteriesDbSet
            .Where(x => x.OrganizationId == userOrg.OrganizationId)
            .Where(x => x.Title.Contains(filter))
            .Select(MapLotteriesToListItemDto)
            .OrderByDescending(x => x.RefundFailed)
            .ThenByDescending(x => x.Status == (int)LotteryStatus.Started || x.Status == (int)LotteryStatus.Drafted)
            .ThenByDescending(_byEndDate)
            .ToListAsync());
 }
        public async Task <OrganizationalStructureDto> GetOrganizationalStructureAsync(UserAndOrganizationDto userAndOrg)
        {
            var newUserRole = await _roleService.GetRoleIdByNameAsync(Roles.NewUser);

            var userList = await _applicationUsersDbSet
                           .Where(u => u.OrganizationId == userAndOrg.OrganizationId)
                           .Where(_roleService.ExcludeUsersWithRole(newUserRole))
                           .Select(MapToOrganizationalStructureUserDto())
                           .ToListAsync();

            var head   = userList.First(u => u.IsManagingDirector);
            var result = MapUsersToOrganizationalStructureDto(head, userList);

            return(result);
        }
        public async Task <IEnumerable <WallMemberDto> > GetWallMembersAsync(int wallId, UserAndOrganizationDto userOrg)
        {
            var wallExists = await _wallsDbSet
                             .AnyAsync(wall =>
                                       wall.Id == wallId &&
                                       wall.OrganizationId == userOrg.OrganizationId);

            if (!wallExists)
            {
                throw new ValidationException(ErrorCodes.WallNotFound, "Wall not found");
            }

            var wallMembers = await _wallUsersDbSet
                              .Include(u => u.Wall.Moderators)
                              .Include(u => u.User.JobPosition)
                              .Where(u =>
                                     u.WallId == wallId &&
                                     u.Wall.OrganizationId == userOrg.OrganizationId)
                              .Select(u => new WallMemberDto
            {
                Id             = u.UserId,
                JobTitle       = u.User.JobPosition.Title ?? string.Empty,
                IsModerator    = u.Wall.Moderators.Any(m => m.UserId == u.UserId),
                FullName       = u.User.FirstName + " " + u.User.LastName,
                ProfilePicture = u.User.PictureId,
                IsCurrentUser  = u.UserId == userOrg.UserId
            })
                              .OrderBy(m => m.FullName)
                              .ToListAsync();

            return(wallMembers);
        }
        public async Task <IEnumerable <PostDto> > SearchWallAsync(string searchString, UserAndOrganizationDto userOrg, int pageNumber, int pageSize)
        {
            Expression <Func <Post, bool> > exp = post =>
                                                  post.MessageBody.Contains(searchString) ||
                                                  post.Comments.Any(comment =>
                                                                    comment.MessageBody.Contains(searchString) &&
                                                                    comment.AuthorId != null);

            return(await QueryForPostsAsync(userOrg, pageNumber, pageSize, null, exp, null));
        }
Beispiel #16
0
        private async Task AddKudosLogsAsync(Lottery lottery, IEnumerable <AddKudosLogDto> kudosLogs, UserAndOrganizationDto userOrg)
        {
            if (lottery.Status != (int)LotteryStatus.RefundStarted)
            {
                return;
            }

            await _kudosService.AddRefundKudosLogsAsync(kudosLogs);

            lottery.Status = (int)LotteryStatus.RefundLogsCreated;

            await _uow.SaveChangesAsync(userOrg.UserId);
        }
Beispiel #17
0
        private async Task <IList <AddKudosLogDto> > CreateKudosLogsAsync(Lottery lottery, UserAndOrganizationDto userOrg)
        {
            var kudosTypeId = await _kudosService.GetKudosTypeIdAsync(KudosTypeEnum.Refund);

            var usersToRefund = await _participantService.GetParticipantsCountedAsync(lottery.Id);

            var usersToSendKudos = new List <AddKudosLogDto>();

            foreach (var user in usersToRefund)
            {
                var totalReturn = user.Tickets * lottery.EntryFee;
                var kudosLog    = new AddKudosLogDto
                {
                    ReceivingUserIds = new List <string> {
                        user.UserId
                    },
                    PointsTypeId   = kudosTypeId,
                    MultiplyBy     = totalReturn,
                    Comment        = CreateComment(lottery, totalReturn),
                    UserId         = userOrg.UserId,
                    OrganizationId = userOrg.OrganizationId
                };

                usersToSendKudos.Add(kudosLog);
            }

            return(usersToSendKudos);
        }
Beispiel #18
0
        public async Task <UserNotificationsSettingsDto> GetWallNotificationSettingsAsync(UserAndOrganizationDto userOrg)
        {
            var settings = await _usersDbSet
                           .Where(u => u.Id == userOrg.UserId && u.OrganizationId == userOrg.OrganizationId)
                           .Select(u => u.NotificationsSettings)
                           .FirstOrDefaultAsync();

            var settingsDto = new UserNotificationsSettingsDto
            {
                EventsAppNotifications                = settings?.EventsAppNotifications ?? true,
                EventsEmailNotifications              = settings?.EventsEmailNotifications ?? true,
                EventWeeklyReminderAppNotifications   = settings?.EventWeeklyReminderAppNotifications ?? true,
                EventWeeklyReminderEmailNotifications = settings?.EventWeeklyReminderEmailNotifications ?? true,
                ProjectsAppNotifications              = settings?.ProjectsAppNotifications ?? true,
                ProjectsEmailNotifications            = settings?.ProjectsEmailNotifications ?? true,
                MyPostsAppNotifications               = settings?.MyPostsAppNotifications ?? true,
                MyPostsEmailNotifications             = settings?.MyPostsEmailNotifications ?? true,
                FollowingPostsAppNotifications        = settings?.FollowingPostsAppNotifications ?? true,
                FollowingPostsEmailNotifications      = settings?.FollowingPostsEmailNotifications ?? true,
                MentionEmailNotifications             = settings?.MentionEmailNotifications ?? true,

                Walls = _wallMembersDbSet
                        .Include(x => x.Wall)
                        .Where(x => x.UserId == userOrg.UserId && x.Wall != null && x.Wall.OrganizationId == userOrg.OrganizationId)
                        .Where(x => x.Wall.Type == WallType.UserCreated || x.Wall.Type == WallType.Main)
                        .Select(x => new WallNotificationsDto
                {
                    WallName   = x.Wall.Name,
                    WallId     = x.WallId,
                    IsMainWall = x.Wall.Type == WallType.Main,
                    IsAppNotificationEnabled   = x.AppNotificationsEnabled,
                    IsEmailNotificationEnabled = x.EmailNotificationsEnabled
                })
            };

            return(settingsDto);
        }
Beispiel #19
0
        public async Task <BookDetailsAdministrationDto> GetBookDetailsWithOfficesAsync(int bookOfficeId, UserAndOrganizationDto userOrg)
        {
            var bookDetailsAdmin = new BookDetailsAdministrationDto
            {
                BookDetails = await GetBookDetailsAsync(bookOfficeId, userOrg)
            };

            bookDetailsAdmin.QuantityByOffice = _bookOfficesDbSet
                                                .Include(x => x.Office)
                                                .Where(b =>
                                                       b.BookId == bookDetailsAdmin.BookDetails.Id &&
                                                       b.OrganizationId == userOrg.OrganizationId)
                                                .Select(MapBookOfficeQuantitiesToDto())
                                                .ToList();
            return(bookDetailsAdmin);
        }
Beispiel #20
0
        public async Task ChangeWallNotificationSettingsAsync(UserNotificationsSettingsDto userNotificationsSettingsDto, UserAndOrganizationDto userOrg)
        {
            var wallIdsToUpdate = userNotificationsSettingsDto
                                  .Walls
                                  .Select(x => x.WallId)
                                  .ToList();

            var wallMembers = await _wallMembersDbSet
                              .Include(x => x.Wall)
                              .Where(x => x.UserId == userOrg.UserId &&
                                     x.Wall.OrganizationId == userOrg.OrganizationId &&
                                     wallIdsToUpdate.Contains(x.WallId) &&
                                     x.Wall.Type == WallType.UserCreated)
                              .ToListAsync();

            foreach (var member in wallMembers)
            {
                member.EmailNotificationsEnabled = userNotificationsSettingsDto
                                                   .Walls
                                                   .First(x => x.WallId == member.WallId)
                                                   .IsEmailNotificationEnabled;

                member.AppNotificationsEnabled = userNotificationsSettingsDto
                                                 .Walls
                                                 .First(x => x.WallId == member.WallId)
                                                 .IsAppNotificationEnabled;
            }

            var eventOrProjectMembers = await _wallMembersDbSet
                                        .Include(x => x.Wall)
                                        .Where(x => x.UserId == userOrg.UserId &&
                                               x.Wall.OrganizationId == userOrg.OrganizationId &&
                                               (x.Wall.Type == WallType.Events ||
                                                x.Wall.Type == WallType.Project))
                                        .ToListAsync();

            foreach (var member in eventOrProjectMembers)
            {
                switch (member.Wall.Type)
                {
                case WallType.Events:
                    member.EmailNotificationsEnabled = userNotificationsSettingsDto.EventsEmailNotifications;
                    member.AppNotificationsEnabled   = userNotificationsSettingsDto.EventsAppNotifications;
                    break;

                case WallType.Project:
                    member.EmailNotificationsEnabled = userNotificationsSettingsDto.EventsEmailNotifications;
                    member.AppNotificationsEnabled   = userNotificationsSettingsDto.EventsAppNotifications;
                    break;
                }
            }

            await _uow.SaveChangesAsync(userOrg.UserId);
        }
        public void Should_Delete_User()
        {
            // Arrange
            var users = new List <ApplicationUser>
            {
                new ApplicationUser {
                    OrganizationId = 2, Id = "userToDelete", RemainingKudos = 100, SpentKudos = 100, TotalKudos = 100
                },
                new ApplicationUser {
                    OrganizationId = 2, Id = "otherUser", RemainingKudos = 100, SpentKudos = 100, TotalKudos = 100
                }
            };

            var userWalls = new List <WallMember>
            {
                new WallMember {
                    WallId = 1, UserId = "userToDelete", Wall = new Wall {
                        OrganizationId = 2
                    }
                },
                new WallMember {
                    WallId = 2, UserId = "userToDelete", Wall = new Wall {
                        OrganizationId = 2
                    }
                },
                new WallMember {
                    WallId = 3, UserId = "userToDelete2", Wall = new Wall {
                        OrganizationId = 2
                    }
                }
            };

            var moderators = new List <WallModerator>
            {
                new WallModerator {
                    Id = 1, WallId = 1, UserId = "userToDelete", Wall = new Wall {
                        OrganizationId = 2
                    }
                }
            };

            var taskSource = new TaskCompletionSource <ApplicationUser>();

            taskSource.SetResult(users.First());
            _userManager.FindByIdAsync("userToDelete").Returns(taskSource.Task);
            _usersDbSet.SetDbSetDataForAsync(users);
            _wallUsersDbSet.SetDbSetDataForAsync(userWalls);
            _wallModeratorsDbSet.SetDbSetDataForAsync(moderators);

            var userOrg = new UserAndOrganizationDto
            {
                UserId         = "admin",
                OrganizationId = 2
            };

            // Act
            _userService.DeleteAsync("userToDelete", userOrg);

            var deletedUser = _usersDbSet.First(x => x.Id == "userToDelete");

            // Assert
            Assert.AreEqual(deletedUser.RemainingKudos, 0);
            Assert.AreEqual(deletedUser.SpentKudos, 0);
            Assert.AreEqual(deletedUser.TotalKudos, 0);
            _usersDbSet.Received(1).Remove(Arg.Any <ApplicationUser>());
            _wallModeratorsDbSet.Received(1).Remove(Arg.Is <WallModerator>(m => m.UserId == "userToDelete"));
            _wallUsersDbSet.Received(2).Remove(Arg.Is <WallMember>(m => m.UserId == "userToDelete"));
        }
Beispiel #22
0
        public async Task ChangeUserNotificationSettingsAsync(UserNotificationsSettingsDto settingsDto, UserAndOrganizationDto userOrg)
        {
            var settings = await _usersDbSet
                           .Where(u => u.Id == userOrg.UserId && u.OrganizationId == userOrg.OrganizationId)
                           .Select(u => u.NotificationsSettings)
                           .FirstOrDefaultAsync();

            if (settings == null)
            {
                settings = new NotificationsSettings
                {
                    OrganizationId = userOrg.OrganizationId
                };
                var user = await _usersDbSet.FirstAsync(u => u.Id == userOrg.UserId && u.OrganizationId == userOrg.OrganizationId);

                user.NotificationsSettings = settings;
            }

            settings.ModifiedBy                            = userOrg.UserId;
            settings.EventsAppNotifications                = settingsDto.EventsAppNotifications;
            settings.EventsEmailNotifications              = settingsDto.EventsEmailNotifications;
            settings.EventWeeklyReminderAppNotifications   = settingsDto.EventWeeklyReminderAppNotifications;
            settings.EventWeeklyReminderEmailNotifications = settingsDto.EventWeeklyReminderEmailNotifications;
            settings.ProjectsAppNotifications              = settingsDto.ProjectsAppNotifications;
            settings.ProjectsEmailNotifications            = settingsDto.ProjectsEmailNotifications;
            settings.MyPostsAppNotifications               = settingsDto.MyPostsAppNotifications;
            settings.MyPostsEmailNotifications             = settingsDto.MyPostsEmailNotifications;
            settings.FollowingPostsAppNotifications        = settingsDto.FollowingPostsAppNotifications;
            settings.FollowingPostsEmailNotifications      = settingsDto.FollowingPostsEmailNotifications;
            settings.MentionEmailNotifications             = settingsDto.MentionEmailNotifications;

            await _uow.SaveChangesAsync(userOrg.UserId);
        }
Beispiel #23
0
        public async Task BuyLotteryTicketAsync(BuyLotteryTicketDto lotteryTicketDto, UserAndOrganizationDto userOrg)
        {
            var applicationUser = await _userService.GetApplicationUserAsync(userOrg.UserId);

            var lotteryDetails = await GetLotteryDetailsAsync(lotteryTicketDto.LotteryId, userOrg);

            if (lotteryDetails is null || applicationUser is null)
            {
                return;
            }

            if (lotteryTicketDto.Tickets <= 0)
            {
                await AddKudosLogForCheatingAsync(userOrg, lotteryDetails.EntryFee, applicationUser);

                throw new LotteryException("Thanks for trying - you were charged double Kudos for this without getting a ticket.");
            }

            if (applicationUser.RemainingKudos < lotteryDetails.EntryFee * lotteryTicketDto.Tickets)
            {
                throw new LotteryException("User does not have enough kudos for the purchase.");
            }

            if (DateTime.UtcNow > lotteryDetails.EndDate)
            {
                throw new LotteryException("Lottery has already ended.");
            }

            var kudosLog = new AddKudosLogDto
            {
                ReceivingUserIds = new List <string> {
                    userOrg.UserId
                },
                PointsTypeId   = await _kudosService.GetKudosTypeIdAsync(KudosTypeEnum.Minus),
                MultiplyBy     = lotteryTicketDto.Tickets * lotteryDetails.EntryFee,
                Comment        = $"{lotteryTicketDto.Tickets} ticket(s) for lottery {lotteryDetails.Title}",
                UserId         = userOrg.UserId,
                OrganizationId = userOrg.OrganizationId
            };

            await _kudosService.AddLotteryKudosLogAsync(kudosLog, userOrg);

            if (applicationUser.RemainingKudos < 0)
            {
                kudosLog.PointsTypeId = await _kudosService.GetKudosTypeIdAsync(KudosTypeEnum.Refund);

                await _kudosService.AddRefundKudosLogsAsync(new List <AddKudosLogDto> {
                    kudosLog
                });
            }
            else
            {
                for (var i = 0; i < lotteryTicketDto.Tickets; i++)
                {
                    _participantsDbSet.Add(MapNewLotteryParticipant(lotteryTicketDto, userOrg));
                }
            }

            await _uow.SaveChangesAsync(applicationUser.Id);

            await _kudosService.UpdateProfileKudosAsync(applicationUser, userOrg);
        }
Beispiel #24
0
 public async Task <IEnumerable <RoleDto> > GetRolesForAutocompleteAsync(string search, UserAndOrganizationDto userOrg)
 {
     return(await _roleDbSet
            .Where(x => x.OrganizationId == userOrg.OrganizationId && x.Name.Contains(search))
            .Select(x => new RoleDto {
         Id = x.Id, Name = x.Name
     })
            .ToListAsync());
 }
 private async Task <bool> HasPermissionAsync(UserAndOrganizationDto userOrg, string permission)
 {
     return(await _permissionService.UserHasPermissionAsync(userOrg, permission));
 }
Beispiel #26
0
 public async Task <RoleDetailsDto> GetRoleByIdAsync(UserAndOrganizationDto userAndOrganizationDto, string roleId)
 {
     return(await GetRoleAsync(role => role.Id == roleId, userAndOrganizationDto.OrganizationId));
 }
Beispiel #27
0
        public async Task CreateNewServiceRequestAsync(ServiceRequestDto newServiceRequestDto, UserAndOrganizationDto userAndOrganizationDto)
        {
            await ValidateServiceRequestForCreateAsync(newServiceRequestDto);

            var serviceRequestStatusId = await _serviceRequestStatusDbSet
                                         .Where(x => x.Title.Equals("Open"))
                                         .Select(x => x.Id)
                                         .FirstAsync();

            var serviceRequestCategory = await _serviceRequestCategoryDbSet
                                         .FirstOrDefaultAsync(x => x.Id == newServiceRequestDto.ServiceRequestCategoryId);

            if (serviceRequestCategory == null)
            {
                throw new ValidationException(ErrorCodes.ContentDoesNotExist, "Service request category does not exist");
            }

            var timestamp = DateTime.UtcNow;

            var serviceRequest = new ServiceRequest
            {
                Description    = newServiceRequestDto.Description,
                Title          = newServiceRequestDto.Title,
                CreatedBy      = userAndOrganizationDto.UserId,
                ModifiedBy     = userAndOrganizationDto.UserId,
                EmployeeId     = userAndOrganizationDto.UserId,
                KudosAmmount   = newServiceRequestDto.KudosAmmount,
                OrganizationId = userAndOrganizationDto.OrganizationId,
                CategoryName   = serviceRequestCategory.Name,
                StatusId       = serviceRequestStatusId,
                PriorityId     = newServiceRequestDto.PriorityId,
                Created        = timestamp,
                Modified       = timestamp,
                PictureId      = newServiceRequestDto.PictureId
            };

            if (newServiceRequestDto.KudosShopItemId != null)
            {
                serviceRequest.KudosShopItemId = newServiceRequestDto.KudosShopItemId;
            }

            _serviceRequestsDbSet.Add(serviceRequest);
            await _uow.SaveChangesAsync(false);

            var srqDto = new CreatedServiceRequestDto {
                ServiceRequestId = serviceRequest.Id
            };

            _asyncRunner.Run <IServiceRequestNotificationService>(async notifier => await notifier.NotifyAboutNewServiceRequestAsync(srqDto), _uow.ConnectionName);
        }
Beispiel #28
0
 public async Task <bool> ItemsExistAsync(UserAndOrganizationDto userOrg)
 {
     return(await _kudosShopItemsDbSet.AnyAsync(t => t.OrganizationId == userOrg.OrganizationId));
 }
        public async Task DeleteCommitteeSuggestionAsync(int committeeId, int suggestionId, UserAndOrganizationDto userAndOrg)
        {
            var committee = await _committeeDbSet
                            .Include(u => u.Suggestions)
                            .FirstOrDefaultAsync(u => u.Id == committeeId);

            if (committee == null)
            {
                throw new ValidationException(ErrorCodes.ContentDoesNotExist, "Committee does not exist");
            }

            var suggestion = committee.Suggestions.FirstOrDefault(x => x.Id == suggestionId);

            committee.Suggestions.Remove(suggestion);

            await _uow.SaveChangesAsync(userAndOrg.UserId);
        }
Beispiel #30
0
        private async Task UpdateUserProfilesAsync(Lottery lottery, IEnumerable <AddKudosLogDto> kudosLogs, UserAndOrganizationDto userOrg)
        {
            if (lottery.Status != (int)LotteryStatus.RefundLogsCreated)
            {
                return;
            }

            var userIds = kudosLogs.Select(x => x.ReceivingUserIds.First());

            await _kudosService.UpdateProfilesFromUserIdsAsync(userIds, userOrg);

            lottery.Status = (int)LotteryStatus.Refunded;

            await _uow.SaveChangesAsync(userOrg.UserId);
        }