예제 #1
0
        public async Task <bool> AbortLotteryAsync(int lotteryId, UserAndOrganizationDto userOrg)
        {
            var lottery = await _lotteriesDbSet
                          .FirstOrDefaultAsync(x => x.Id == lotteryId && x.OrganizationId == userOrg.OrganizationId);

            if (lottery is null)
            {
                return(false);
            }

            if (lottery.Status == (int)LotteryStatus.Started)
            {
                lottery.Status = (int)LotteryStatus.RefundStarted;
                await _uow.SaveChangesAsync();

                _asyncRunner.Run <ILotteryAbortJob>(async notifier => await notifier.RefundLotteryAsync(lottery.Id, userOrg), _uow.ConnectionName);
            }
            else if (lottery.Status == (int)LotteryStatus.Drafted)
            {
                lottery.Status = (int)LotteryStatus.Deleted;
                await _uow.SaveChangesAsync();
            }

            return(lottery.Status == (int)LotteryStatus.Deleted || lottery.Status == (int)LotteryStatus.RefundStarted);
        }
예제 #2
0
        public void ApproveKudos(int kudosLogId, UserAndOrganizationDTO userOrg)
        {
            var kudosLog = _kudosLogsDbSet
                           .Include(x => x.Employee)
                           .First(x =>
                                  x.Id == kudosLogId &&
                                  x.OrganizationId == userOrg.OrganizationId);

            kudosLog.Approve(userOrg.UserId);

            if (!kudosLog.IsRecipientDeleted())
            {
                if (kudosLog.IsMinus())
                {
                    _asyncRunner.Run <IKudosNotificationService>(n => n.NotifyApprovedKudosDecreaseRecipient(kudosLog), _uow.ConnectionName);
                }
                else
                {
                    _asyncRunner.Run <IKudosNotificationService>(n => n.NotifyApprovedKudosRecipient(kudosLog), _uow.ConnectionName);
                }
            }

            _uow.SaveChanges(false);

            UpdateProfileKudos(kudosLog.Employee, userOrg);
        }
예제 #3
0
        public async Task <IHttpActionResult> CreateEvent(CreateEventViewModel eventViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var createEventDto = _mapper.Map <CreateEventDto>(eventViewModel);
            var offices        = eventViewModel.Offices.Select(p => p.ToString()).ToList();

            createEventDto.Offices = new EventOfficesDto {
                Value = JsonConvert.SerializeObject(offices)
            };
            SetOrganizationAndUser(createEventDto);

            CreateEventDto createdEvent;

            var userHubDto = GetUserAndOrganizationHub();

            try
            {
                createdEvent = await _eventService.CreateEventAsync(createEventDto);

                _asyncRunner.Run <NewEventNotifier>(async notifier => { await notifier.Notify(createdEvent, userHubDto); }, GetOrganizationName());
            }
            catch (EventException e)
            {
                return(BadRequest(e.Message));
            }

            return(Ok(new { createdEvent.Id }));
        }
예제 #4
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);
        }
예제 #5
0
        public async Task PostSuggestionAsync(CommitteeSuggestionPostDto dto, string userId)
        {
            var committee = await _committeeRepository
                            .Get(c => c.Id == dto.CommitteeId, includeProperties : "Suggestions, Members")
                            .FirstOrDefaultAsync();

            if (committee == null)
            {
                throw new ServiceException(Resources.Models.Committee.Committee.SuggestionCommiteNotFound);
            }

            var suggestion = _mapper.Map <CommitteeSuggestion>(dto);

            suggestion.User = await _applicationUserRepository.GetByIdAsync(userId);

            suggestion.Date = DateTime.UtcNow;

            committee.Suggestions.Add(suggestion);

            _committeeRepository.Update(committee);
            await _unitOfWork.SaveAsync();

            var suggestionDto = new CommitteeSuggestionCreatedDto
            {
                CommitteeId  = committee.Id,
                SuggestionId = suggestion.Id
            };

            _asyncRunner.Run <ICommitteeNotificationService>(async notifier => await notifier.NotifyCommitteeMembersAboutNewSuggestionAsync(suggestionDto), _uow.ConnectionName);
        }
예제 #6
0
        public IHttpActionResult CreatePost(CreateWallPostViewModel wallPostViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var postModel = _mapper.Map <CreateWallPostViewModel, NewPostDTO>(wallPostViewModel);

            SetOrganizationAndUser(postModel);
            var userHubDto = GetUserAndOrganizationHub();

            try
            {
                var createdPost = _postService.CreateNewPost(postModel);
                _asyncRunner.Run <NewPostNotifier>(notif =>
                {
                    notif.Notify(createdPost, userHubDto);
                }, GetOrganizationName());

                return(Ok(_mapper.Map <WallPostViewModel>(createdPost)));
            }
            catch (ValidationException e)
            {
                return(BadRequestWithError(e));
            }
        }
예제 #7
0
        public void TakeBook(BookTakeDTO bookDTO)
        {
            MobileBookOfficeLogsDTO officeBookWithLogs;

            lock (takeBookLock)
            {
                officeBookWithLogs = _bookOfficesDbSet
                                     .Include(b => b.Book)
                                     .Include(b => b.BookLogs)
                                     .Where(b => b.OrganizationId == bookDTO.OrganizationId &&
                                            b.Id == bookDTO.BookOfficeId)
                                     .Select(MapOfficebookWithLogsToDTO())
                                     .FirstOrDefault();

                ValidateTakeBook(bookDTO, officeBookWithLogs);

                BorrowBook(officeBookWithLogs, bookDTO);
            }

            var book = new TakenBookDTO
            {
                UserId         = bookDTO.ApplicationUserId,
                OrganizationId = bookDTO.OrganizationId,
                BookOfficeId   = bookDTO.BookOfficeId,
                OfficeId       = officeBookWithLogs.OfficeId,
                Author         = officeBookWithLogs.Author,
                Title          = officeBookWithLogs.Title
            };

            _asyncRunner.Run <IBooksNotificationService>(n => n.SendEmail(book), _uow.ConnectionName);
        }
예제 #8
0
        public IHttpActionResult CreateComment(NewCommentViewModel comment)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var commentDto = _mapper.Map <NewCommentViewModel, NewCommentDTO>(comment);

            SetOrganizationAndUser(commentDto);
            var userHubDto = GetUserAndOrganizationHub();

            try
            {
                var commentCreatedDto = _commentService.CreateComment(commentDto);
                _asyncRunner.Run <NewCommentNotifier>(notif =>
                {
                    notif.Notify(commentCreatedDto, userHubDto);
                }, GetOrganizationName());

                return(Ok(new { commentCreatedDto.CommentId }));
            }
            catch (ValidationException e)
            {
                return(BadRequestWithError(e));
            }
        }
예제 #9
0
        public async Task TakeBookAsync(BookTakeDto bookDto)
        {
            MobileBookOfficeLogsDto officeBookWithLogs;

            await _takeBookLock.WaitAsync();

            try
            {
                officeBookWithLogs = await _bookOfficesDbSet
                                     .Include(b => b.Book)
                                     .Include(b => b.BookLogs)
                                     .Where(b => b.OrganizationId == bookDto.OrganizationId && b.Id == bookDto.BookOfficeId)
                                     .Select(MapOfficeBookWithLogsToDto())
                                     .FirstOrDefaultAsync();

                await ValidateTakeBookAsync(bookDto, officeBookWithLogs);
                await BorrowBookAsync(officeBookWithLogs, bookDto);
            }
            finally
            {
                _takeBookLock.Release();
            }

            var book = new TakenBookDto
            {
                UserId         = bookDto.ApplicationUserId,
                OrganizationId = bookDto.OrganizationId,
                BookOfficeId   = bookDto.BookOfficeId
            };

            if (officeBookWithLogs != null)
            {
                book.OfficeId = officeBookWithLogs.OfficeId;
                book.Author   = officeBookWithLogs.Author;
                book.Title    = officeBookWithLogs.Title;
            }

            _asyncRunner.Run <IBooksNotificationService>(async notifier => await notifier.SendEmailAsync(book), _uow.ConnectionName);
        }
예제 #10
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);
        }
예제 #11
0
        public async Task ResetAttendeesAsync(Guid eventId, UserAndOrganizationDto userOrg)
        {
            var @event = await _eventsDbSet
                         .Include(e => e.EventParticipants)
                         .Include(e => e.EventOptions)
                         .Include(e => e.EventType)
                         .Include(e => e.EventParticipants.Select(participant => participant.ApplicationUser))
                         .Include(e => e.EventParticipants.Select(participant => participant.ApplicationUser.Manager))
                         .SingleOrDefaultAsync(e => e.Id == eventId && e.OrganizationId == userOrg.OrganizationId);

            _eventValidationService.CheckIfEventExists(@event);
            var hasPermission = await _permissionService.UserHasPermissionAsync(userOrg, AdministrationPermissions.Event);

            // ReSharper disable once PossibleNullReferenceException
            _eventValidationService.CheckIfUserHasPermission(userOrg.UserId, @event.ResponsibleUserId, hasPermission);
            _eventValidationService.CheckIfEventEndDateIsExpired(@event.EndDate);

            var users     = @event.EventParticipants.Select(p => p.ApplicationUserId).ToList();
            var timestamp = DateTime.UtcNow;

            foreach (var participant in @event.EventParticipants)
            {
                participant.UpdateMetadata(userOrg.UserId, timestamp);
            }

            await _uow.SaveChangesAsync(false);

            if ([email protected])
            {
                await RemoveParticipantsAsync(@event, userOrg);

                _asyncRunner.Run <IEventNotificationService>(async notifier => await notifier.NotifyRemovedEventParticipantsAsync(@event.Name, @event.Id, userOrg.OrganizationId, users),
                                                             _uow.ConnectionName);

                return;
            }

            var userEventAttendStatusDto = MapEventToUserEventAttendStatusChangeEmailDto(@event).ToList();

            await RemoveParticipantsAsync(@event, userOrg);

            _asyncRunner.Run <IEventNotificationService>(async notifier => await notifier.NotifyRemovedEventParticipantsAsync(@event.Name, @event.Id, userOrg.OrganizationId, users),
                                                         _uow.ConnectionName);

            NotifyManagers(userEventAttendStatusDto);
        }
예제 #12
0
        public async Task <HttpResponseMessage> Search(string token, string team_id, string team_domain, string channel_id, string channel_name, string user_id, string user_name, string command, string text, string response_url)
        {
            Message response = new Services.Models.Slack.Message();

            if (token != ConfigurationManager.AppSettings["SlackSlashToken"].ToString())
            {
                return(new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden));
            }
            else
            {
                await _runner.Run <SlackService>(service => service.Respond(text, response_url));

                response.text   = string.Format("I'm on it! Give me a sec...", text);
                response.mrkdwn = true;
                return(Request.CreateResponse <Message>(System.Net.HttpStatusCode.OK, response));
            }
        }
예제 #13
0
        public async Task RefundLotteryAsync(int lotteryId, UserAndOrganizationDto userOrg)
        {
            var lottery = await _lotteryService.GetLotteryAsync(lotteryId);

            if (lottery == null || lottery.OrganizationId != userOrg.OrganizationId)
            {
                return;
            }

            try
            {
                var refundLogs = await CreateKudosLogsAsync(lottery, userOrg);
                await AddKudosLogsAsync(lottery, refundLogs, userOrg);
                await UpdateUserProfilesAsync(lottery, refundLogs, userOrg);
            }
            catch (Exception e)
            {
                _logger.Error(e);
                _asyncRunner.Run <ILotteryService>(async n => await n.UpdateRefundFailedFlagAsync(lottery.Id, true, userOrg), _uow.ConnectionName);
            }
        }
예제 #14
0
        public async Task <IHttpActionResult> CreatePost(CreateWallPostViewModel wallPostViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var userAndOrg = GetUserAndOrganization();

            if (!await _permissionService.UserHasPermissionAsync(userAndOrg, BasicPermissions.Post))
            {
                var wall = await _wallService.GetWallAsync(wallPostViewModel.WallId, userAndOrg);

                if (wall.Type != WallType.Events)
                {
                    return(Forbidden());
                }
            }

            var postModel = _mapper.Map <CreateWallPostViewModel, NewPostDto>(wallPostViewModel);

            SetOrganizationAndUser(postModel);
            var userHubDto = GetUserAndOrganizationHub();

            try
            {
                var createdPost = await _postService.CreateNewPostAsync(postModel);

                _asyncRunner.Run <NewPostNotifier>(async notifier =>
                {
                    await notifier.NotifyAsync(createdPost, userHubDto);
                }, GetOrganizationName());

                return(Ok(_mapper.Map <WallPostViewModel>(createdPost)));
            }
            catch (ValidationException e)
            {
                return(BadRequestWithError(e));
            }
        }
예제 #15
0
        public async Task <IHttpActionResult> CreateComment(NewCommentViewModel comment)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var userAndOrg = GetUserAndOrganization();

            var wallPost = await _wallService.GetWallPostAsync(userAndOrg, comment.PostId);

            if (!await _permissionService.UserHasPermissionAsync(userAndOrg, BasicPermissions.Comment) && wallPost.WallType != WallType.Events)
            {
                return(Forbidden());
            }

            var commentDto = _mapper.Map <NewCommentViewModel, NewCommentDto>(comment);

            SetOrganizationAndUser(commentDto);
            var userHubDto = GetUserAndOrganizationHub();

            try
            {
                var commentCreatedDto = await _commentService.CreateCommentAsync(commentDto);

                _asyncRunner.Run <NewCommentNotifier>(async notifier =>
                {
                    await notifier.NotifyAsync(commentCreatedDto, userHubDto);
                }, GetOrganizationName());

                return(Ok(new { commentCreatedDto.CommentId }));
            }
            catch (ValidationException e)
            {
                return(BadRequestWithError(e));
            }
        }
예제 #16
0
        public async Task AwardEmployeesWithKudosAsync(string organizationName)
        {
            var awardedEmployees = new List <AwardedKudosEmployeeDto>();

            await _concurrencyLock.WaitAsync();

            try
            {
                if (string.IsNullOrEmpty(organizationName))
                {
                    throw new ArgumentNullException(nameof(organizationName));
                }

                var organization = await _organizationsDbSet
                                   .Where(o => o.ShortName == organizationName)
                                   .Select(o => new
                {
                    o.Id,
                    o.KudosYearlyMultipliers
                })
                                   .SingleAsync();

                var kudosYearlyMultipliers = GetKudosYearlyMultipliersArray(organization.KudosYearlyMultipliers);
                if (kudosYearlyMultipliers == null)
                {
                    return;
                }

                var loyaltyType = await _kudosTypesDbSet.SingleOrDefaultAsync(t => t.Name == LoyaltyKudosTypeName);

                var loyaltyKudosLog = await(from u in _usersDbSet
                                            where u.OrganizationId == organization.Id && u.EmploymentDate.HasValue
                                            join kl in _kudosLogsDbSet
                                            on new { employeeId = u.Id, orgId = organization.Id, Status = KudosStatus.Approved, KudosTypeName = LoyaltyKudosTypeName }
                                            equals new { employeeId = kl.EmployeeId, orgId = kl.OrganizationId, kl.Status, kl.KudosTypeName }
                                            into klx
                                            from kl in klx.DefaultIfEmpty()
                                            select new
                {
                    Employee       = u,
                    KudosAddedDate = kl == null ? (DateTime?)null : kl.Created
                }).ToListAsync();

                var employeesReceivedLoyaltyKudos = await loyaltyKudosLog
                                                    .GroupBy(l => l.Employee)
                                                    .Select(l => new EmployeeLoyaltyKudosDto
                {
                    Employee = l.Key,
                    AwardedEmploymentYears = l
                                             .Where(log => log.Employee.EmploymentDate != null && log.KudosAddedDate != null)
                                             .Select(log => GetLoyaltyKudosEmploymentYear(log.Employee.EmploymentDate, log.KudosAddedDate.Value)),

                    AwardedLoyaltyKudosCount = l.Count(log => log.KudosAddedDate != null)
                })
                                                    .ToListAsync();

                foreach (var employeeLoyaltyKudos in employeesReceivedLoyaltyKudos)
                {
                    try
                    {
                        var loyaltyKudosLogList      = _loyaltyKudosCalculator.GetEmployeeLoyaltyKudosLog(employeeLoyaltyKudos, loyaltyType, organization.Id, kudosYearlyMultipliers);
                        var awardedKudosEmployeeList = _mapper.Map <List <AwardedKudosEmployeeDto> >(loyaltyKudosLogList);
                        awardedEmployees.AddRange(awardedKudosEmployeeList);

                        loyaltyKudosLogList.ForEach(l => _kudosLogsDbSet.Add(l));
                    }
                    catch (ArgumentException e)
                    {
                        _logger.Error(e);
                    }
                }

                await _uow.SaveChangesAsync(false);

                _asyncRunner.Run <IKudosPremiumNotificationService>(async notifier => await notifier.SendLoyaltyBotNotificationAsync(awardedEmployees), _uow.ConnectionName);
            }
            finally
            {
                _concurrencyLock.Release();
            }
        }