public async Task <InProductTrainingViewResponse> CreateInProductTrainingViewAsync(InProductTrainingViewRequest inProductTrainingViewRequest, Guid userId)
        {
            var validationResult = _validatorLocator.Validate <InProductTrainingViewRequestValidator>(inProductTrainingViewRequest);

            if (!validationResult.IsValid)
            {
                _logger.Error("Validation failed while attempting to create an InProductTrainingView resource.");
                throw new ValidationFailedException(validationResult.Errors);
            }

            var returnPayload    = new InProductTrainingViewResponse();
            var returnMessage    = "";
            var returnResultCode = ResultCode.Failed;

            var userApiResult = await _userApi.GetUserAsync(userId);

            string createdByUserName;

            if (userApiResult != null)
            {
                createdByUserName = !userApiResult.Payload.Username.IsNullOrEmpty() ? userApiResult.Payload.Username : userApiResult.Payload.Email;
            }
            else
            {
                createdByUserName = "******";
            }

            try
            {
                var key         = KeyResolver.InProductTrainingViews(userId, inProductTrainingViewRequest.ClientApplicationId);
                var dtoForTrace = _serializer.SerializeToString(inProductTrainingViewRequest);

                var cachedData = await _cache.SetMembersAsync <InProductTrainingViewResponse>(key);

                // ReSharper disable once UseNullPropagation
                if (cachedData != null)
                {
                    var trainingOfType = cachedData?.Where(t =>
                                                           t.InProductTrainingSubjectId == inProductTrainingViewRequest.InProductTrainingSubjectId &&
                                                           t.Title == inProductTrainingViewRequest.Title &&
                                                           t.UserId == userId)
                                         .FirstOrDefault();

                    if (trainingOfType != null)
                    {
                        returnPayload    = trainingOfType;
                        returnMessage    = CreateInProductTrainingViewReturnCode.RecordAlreadyExists.BuildResponseMessage(inProductTrainingViewRequest, userId);
                        returnResultCode = ResultCode.RecordAlreadyExists;

                        _logger.Info($"Record not created because it already exists in cache. {dtoForTrace}");
                    }
                }

                var populateCache = false;
                InProductTrainingViewResponse queryResult = null;
                if (returnResultCode != ResultCode.RecordAlreadyExists)
                {
                    var returnCode = CreateInProductTrainingViewReturnCode.CreateFailed;
                    queryResult = _dbService.CreateInProductTrainingView(
                        inProductTrainingViewRequest.InProductTrainingSubjectId, userId,
                        inProductTrainingViewRequest.Title, inProductTrainingViewRequest.UserTypeId, createdByUserName, ref returnCode);

                    returnPayload    = queryResult;
                    returnMessage    = returnCode.BuildResponseMessage(inProductTrainingViewRequest, userId);
                    returnResultCode = returnCode.ToResultCode();

                    if (returnCode == CreateInProductTrainingViewReturnCode.CreateSucceeded)
                    {
                        populateCache = true;
                        _logger.Info($"Created InProductTrainingView record. {dtoForTrace}");
                    }
                    else
                    {
                        if (returnCode == CreateInProductTrainingViewReturnCode.RecordAlreadyExists)
                        {
                            populateCache = true;
                            _logger.Info($"Record not created because it already exists in dB. {dtoForTrace}");
                        }
                        else if (returnCode == CreateInProductTrainingViewReturnCode.CreateFailed)
                        {
                            _logger.Error($"{returnMessage} {dtoForTrace}");
                        }
                        else
                        {
                            _logger.Warning($"{returnMessage} {dtoForTrace}");
                        }
                    }
                }

                if (populateCache && queryResult != null)
                {
                    var queryResultAsList = new List <InProductTrainingViewResponse> {
                        queryResult
                    };
                    if (await _cache.SetAddAsync(key, queryResultAsList) > 0 || await _cache.KeyExistsAsync(key))
                    {
                        _logger.Info($"Succesfully cached an item in the set for key '{key}' {dtoForTrace}");
                        if (!await _cache.KeyExpireAsync(key, _expirationTime, CacheCommandOptions.None))
                        {
                            _logger.Error($"Could not set cache expiration for the key '{key}' or the key does not exist. {dtoForTrace}");
                        }
                    }
                    else
                    {
                        _logger.Error($"Could not cache an item in the set for '{key}'. {dtoForTrace}");
                    }
                }
            }
            catch (Exception ex)
            {
                returnPayload.ResultCode    = ResultCode.Failed;
                returnPayload.ReturnMessage = ex.ToString();

                _logger.Error("Create InProductTrainingView failed due to an unknown exception", ex);
            }

            returnPayload.ReturnMessage = returnMessage;
            returnPayload.ResultCode    = returnResultCode;
            return(returnPayload);
        }
示例#2
0
        public async Task <GuestInvite> CreateGuestInviteAsync(GuestInvite model)
        {
            var validationResult = _validatorLocator.Validate <GuestInviteValidator>(model);

            if (!validationResult.IsValid)
            {
                throw new ValidationFailedException(validationResult.Errors);
            }

            // Get dependent resources
            var projectTask       = GetProjectAsync(model.ProjectId);
            var invitedByUserTask = GetUserAsync(model.InvitedBy);
            await Task.WhenAll(projectTask, invitedByUserTask);

            var project       = projectTask.Result;
            var invitedByUser = invitedByUserTask.Result;

            var accessCode = await GetGuestAccessCodeAsync(project);

            model.Id = model.Id == Guid.Empty ? Guid.NewGuid() : model.Id;
            model.CreatedDateTime   = DateTime.UtcNow;
            model.ProjectAccessCode = accessCode;
            model.ProjectTenantId   = project.TenantId;

            var result = await _guestInviteRepository.CreateItemAsync(model);

            // Delete all prior guest invites with the same email and ProjectId as the session just created.
            await _guestInviteRepository.DeleteItemsAsync(x => x.ProjectId == model.ProjectId &&
                                                          x.GuestEmail == model.GuestEmail &&
                                                          x.Id != result.Id);

            _eventService.Publish(EventNames.GuestInviteCreated, result);

            // Send an invite email to the guest
            var emailResult = await _emailSendingService.SendGuestInviteEmailAsync(project.Name, project.ProjectUri, model.GuestEmail, invitedByUser.FirstName);

            if (!emailResult.IsSuccess())
            {
                _logger.Error($"Sending guest invite email failed. Reason={emailResult.ReasonPhrase} Error={_serializer.SerializeToString(emailResult.ErrorResponse)}");
                await _guestInviteRepository.DeleteItemAsync(result.Id);
            }

            return(result);
        }
        public async Task <IEnumerable <GuestSession> > GetMostRecentValidGuestSessionsByProjectIdAsync(Guid projectId)
        {
            var validationResult = _validatorLocator.Validate <ProjectIdValidator>(projectId);

            if (!validationResult.IsValid)
            {
                throw new ValidationFailedException(validationResult.Errors);
            }

            var projectResult = await _serviceToServiceProjectApi.GetProjectByIdAsync(projectId);

            if (!projectResult.IsSuccess() || projectResult.Payload == null)
            {
                throw new NotFoundException($"Failed to retrieve project: {projectId}. Message: {projectResult.ReasonPhrase}, StatusCode: {projectResult.ResponseCode}, ErrorResponse: {_synthesisObjectSerializer.SerializeToString(projectResult.ErrorResponse)}");
            }

            var project = projectResult.Payload;

            var validGuestSessions = await _guestSessionRepository.CreateItemQuery()
                                     .Where(x => x.ProjectId == projectId &&
                                            x.ProjectAccessCode == project.GuestAccessCode &&
                                            x.GuestSessionState != GuestState.PromotedToProjectMember)
                                     .ToListAsync();

            if (!validGuestSessions.Any())
            {
                return(new List <GuestSession>());
            }

            var currentValidProjectGuestSessions = validGuestSessions.GroupBy(s => s.UserId)
                                                   .OrderBy(gs => gs.Key)
                                                   .Select(gs => gs.OrderByDescending(x => x.CreatedDateTime).FirstOrDefault());

            return(currentValidProjectGuestSessions);
        }