예제 #1
0
        public ConfirmationOfScrutinyQuery(string examinationId, MeUser user)
        {
            if (string.IsNullOrEmpty(examinationId))
            {
                throw new ArgumentNullException(nameof(examinationId));
            }

            ExaminationId = examinationId;
            User          = user ?? throw new ArgumentException(nameof(user));
        }
        public void TestPostUserResponse()
        {
            var expectedUserId = "expectedUserId";

            var examination = new MeUser
            {
                UserId = expectedUserId
            };

            var response = _mapper.Map <PostUserResponse>(examination);

            response.UserId.Should().Be(expectedUserId);
        }
예제 #3
0
        public async Task TestCreateUserOkResponse()
        {
            // Arrange
            const string expectedUserId = "expectedUserId";
            const string expectedEmail  = "*****@*****.**";
            const string oktaFirstName  = "oktaFirstName";
            const string oktaLastName   = "oktaLastName";
            const string oktaId         = "oktaId";
            const string oktaEmail      = "oktaEmail";

            var request = new PostUserRequest
            {
                Email = expectedEmail,
            };

            var user = new MeUser
            {
                UserId = expectedUserId,
                Email  = expectedEmail,
            };

            var oktaUser = new Mock <IUser>(MockBehavior.Strict);

            oktaUser.Setup(u => u.Id).Returns(oktaId);
            oktaUser.Setup(u => u.Profile.FirstName).Returns(oktaFirstName);
            oktaUser.Setup(u => u.Profile.LastName).Returns(oktaLastName);
            oktaUser.Setup(u => u.Profile.Email).Returns(oktaEmail);

            _mockOktaClient
            .Setup(s => s.Users.GetUserAsync(It.IsAny <string>(), default(CancellationToken)))
            .Returns(Task.FromResult(oktaUser.Object));

            _createUserService
            .Setup(cus => cus.Handle(It.IsAny <CreateUserQuery>()))
            .Returns(Task.FromResult(user));
            Controller.ControllerContext = GetControllerContext();

            // Act
            var response = await Controller.CreateUser(request);

            // Assert
            response.Result.Should().BeAssignableTo <OkObjectResult>();
            var result = (OkObjectResult)response.Result;

            result.Value.Should().BeAssignableTo <PostUserResponse>();
            var model = (PostUserResponse)result.Value;

            model.Errors.Count.Should().Be(0);
            model.Success.Should().BeTrue();
            model.UserId.Should().Be(expectedUserId);
        }
        public void PatientDetailsUpdateOnExaminationWithAllUrgencyIndicatorsSuccessReturnsExaminationWithIsUrgentTrue()
        {
            // Arrange
            var examination = new MedicalExaminer.Models.Examination()
            {
                ChildPriority    = true,
                CoronerPriority  = true,
                CulturalPriority = true,
                FaithPriority    = true,
                OtherPriority    = true,
                CreatedAt        = DateTime.Now.AddDays(-3)
            };
            var patientDetails = new MedicalExaminer.Models.PatientDetails()
            {
                ChildPriority    = true,
                CoronerPriority  = true,
                CulturalPriority = true,
                FaithPriority    = true,
                OtherPriority    = true,
            };

            const string userId = "userId";
            var          user   = new MeUser()
            {
                UserId = userId,
            };

            var connectionSettings = new Mock <IExaminationConnectionSettings>();

            var query    = new PatientDetailsUpdateQuery("a", patientDetails, user, _locationPath);
            var dbAccess = new Mock <IDatabaseAccess>();
            var locationConnectionSettings = new Mock <ILocationConnectionSettings>();
            var location        = new MedicalExaminer.Models.Location();
            var locationService = new Mock <LocationIdService>(dbAccess.Object, locationConnectionSettings.Object);

            locationService.Setup(x => x.Handle(It.IsAny <LocationRetrievalByIdQuery>())).Returns(Task.FromResult(location));
            dbAccess.Setup(db => db.GetItemAsync(connectionSettings.Object,
                                                 It.IsAny <Expression <Func <MedicalExaminer.Models.Examination, bool> > >()))
            .Returns(Task.FromResult(examination)).Verifiable();
            dbAccess.Setup(db => db.UpdateItemAsync(connectionSettings.Object,
                                                    It.IsAny <MedicalExaminer.Models.Examination>())).Returns(Task.FromResult(examination)).Verifiable();
            var sut = new PatientDetailsUpdateService(dbAccess.Object, connectionSettings.Object, Mapper, locationService.Object, _urgencySettingsMock.Object);

            // Act
            var result = sut.Handle(query);

            // Assert
            result.Result.IsUrgent().Should().BeTrue();
            result.Result.LastModifiedBy.Should().Be(userId);
        }
        public async void ValidateSession_ReturnsBadRequest_WhenNoCurrentUser()
        {
            const MeUser user = null;

            _mockUserRetrievalByOktaIdService
            .Setup(s => s.Handle(It.IsAny <UserRetrievalByOktaIdQuery>()))
            .Returns(Task.FromResult(user));

            var response = await Controller.ValidateSession();

            var taskResult       = response.Should().BeOfType <ActionResult <PostValidateSessionResponse> >().Subject;
            var badRequestResult = taskResult.Result.Should().BeAssignableTo <BadRequestObjectResult>().Subject;

            badRequestResult.Value.Should().BeAssignableTo <PostValidateSessionResponse>();
        }
        public void LocationIdsWithPermission_ReturnsLocations()
        {
            // Arrange
            var expectedRole       = UserRoles.MedicalExaminer;
            var unexpectedRole     = UserRoles.MedicalExaminerOfficer;
            var expectedPermission = Common.Authorization.Permission.AddEventToExamination;
            var expectedLocation   = "expectedLocation";
            var unexpectedLocation = "unexpectedLocation";
            var meUser             = new MeUser()
            {
                Permissions = new List <MEUserPermission>()
                {
                    new MEUserPermission()
                    {
                        PermissionId = string.Empty,
                        LocationId   = expectedLocation,
                        UserRole     = expectedRole,
                    },
                    new MEUserPermission()
                    {
                        PermissionId = string.Empty,
                        LocationId   = unexpectedLocation,
                        UserRole     = unexpectedRole,
                    }
                }
            };

            _rolePermissionsMock
            .Setup(rp => rp.Can(expectedRole, expectedPermission))
            .Returns(true);

            _rolePermissionsMock
            .Setup(rp => rp.Can(unexpectedRole, expectedPermission))
            .Returns(false);

            _userRetrievalServiceMock
            .Setup(urs => urs.Handle(It.IsAny <UserRetrievalByOktaIdQuery>()))
            .Returns(Task.FromResult(meUser));

            // Act
            var actualLocations = _sut.LocationIdsWithPermission(meUser, expectedPermission).ToList();

            // Assert
            actualLocations.Contains(expectedLocation).Should().BeTrue();
            actualLocations.Contains(unexpectedLocation).Should().BeFalse();
        }
        /// <summary>
        /// 开始考试.
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="examinationID"></param>
        /// <returns></returns>
        public long StartExamination(long userID, long examinationID)
        {
            try
            {
                using (MyExaminationContext context = new MyExaminationContext())
                {
                    // 用户检查.
                    MeUser user = context.Users.Find(userID);
                    if (user == null)
                    {
                        // 用户不存在.
                        return(-1);
                    }

                    // 考试主表检查.
                    MeExamination examination = context.Examinations.Find(examinationID);
                    if (examination == null)
                    {
                        // 考试主表不存在.
                        return(-1);
                    }


                    MeUserExamination userExamination = new MeUserExamination()
                    {
                        // 用户
                        UserID = userID,
                        // 考试.
                        ExaminationID = examinationID,

                        // 开始时间.
                        ExaminationStartTime = DateTime.Now,
                    };

                    context.UserExaminations.Add(userExamination);
                    context.SaveChanges();

                    return(userExamination.UserExaminationID);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                return(-1);
            }
        }
예제 #8
0
        public async Task valid_token_returns_user(MeUser user)
        {
            mockOrderCloudClient.Me.GetAsync().ReturnsForAnyArgs(user);
            var functionToken = new OrderCloudIntegrationsFunctionToken(Substitute.For <AppSettings>());
            var verifiedUser  = await functionToken.Authorize(mockHttpRequest, new[] { ApiRole.OrderAdmin }, mockOrderCloudClient);

            Assert.IsTrue(user.ID == verifiedUser.ID);
            if (user.Supplier != null)
            {
                Assert.IsTrue(user.Supplier.ID == verifiedUser.Supplier.ID);
            }
            if (user.Buyer != null)
            {
                Assert.IsTrue(user.Buyer.ID == verifiedUser.Buyer.ID);
            }
            Assert.IsTrue(user.Email == verifiedUser.Email);
            Assert.IsTrue(user.Username == verifiedUser.Username);
        }
예제 #9
0
        public void CreateExaminationQueryWithNoUrgencyIndicatorsSuccessReturnsExaminationWithIsUrgentFalse()
        {
            // Arrange
            var examination = new MedicalExaminer.Models.Examination()
            {
                ChildPriority    = false,
                CoronerPriority  = false,
                CulturalPriority = false,
                FaithPriority    = false,
                OtherPriority    = false,
                CreatedAt        = DateTime.Now.AddDays(-3)
            };

            var userId = "userId";
            var user   = new MeUser()
            {
                UserId = userId
            };
            var connectionSettings       = new Mock <IExaminationConnectionSettings>();
            CreateExaminationQuery query = new CreateExaminationQuery(examination, user);
            var dbAccess = new Mock <IDatabaseAccess>();
            var locationConnectionSettings = new Mock <ILocationConnectionSettings>();
            var location        = new MedicalExaminer.Models.Location();
            var locationService = new Mock <LocationIdService>(dbAccess.Object, locationConnectionSettings.Object);

            locationService.Setup(x => x.Handle(It.IsAny <LocationRetrievalByIdQuery>())).Returns(Task.FromResult(location));

            dbAccess.Setup(db => db.CreateItemAsync(
                               connectionSettings.Object,
                               examination,
                               false)).Returns(Task.FromResult(examination)).Verifiable();
            var sut = new CreateExaminationService(dbAccess.Object, connectionSettings.Object, locationService.Object, _urgencySettingsMock.Object);

            // Act
            var result = sut.Handle(query);

            // Assert
            result.Result.Should().NotBeNull();
            result.Result.IsUrgent().Should().BeFalse();
            result.Result.LastModifiedBy.Should().Be(user.UserId);
        }
예제 #10
0
        public async void ValidateSession_ReturnsSession_WhenSessionValid()
        {
            var firstName = "firstName";
            var gmcNumber = "gmcNumber";
            var user      = new MeUser()
            {
                FirstName   = firstName,
                GmcNumber   = gmcNumber,
                Permissions = new List <MEUserPermission>()
                {
                    new MEUserPermission()
                    {
                        UserRole = UserRoles.MedicalExaminer
                    }
                }
            };

            var permissions = new Dictionary <Permission, bool>();

            _mockRolePermissions
            .Setup(rp => rp.PermissionsForRoles(It.IsAny <IEnumerable <UserRoles> >()))
            .Returns(permissions)
            .Verifiable();

            _mockUserRetrievalByOktaIdService
            .Setup(s => s.Handle(It.IsAny <UserRetrievalByOktaIdQuery>()))
            .Returns(Task.FromResult(user));

            var response = await Controller.ValidateSession();

            var taskResult      = response.Should().BeOfType <ActionResult <PostValidateSessionResponse> >().Subject;
            var okRequestResult = taskResult.Result.Should().BeAssignableTo <OkObjectResult>().Subject;
            var result          = okRequestResult.Value.Should().BeAssignableTo <PostValidateSessionResponse>().Subject;

            result.Role.Contains(UserRoles.MedicalExaminer).Should().BeTrue();
            result.FirstName.Should().Be(firstName);
            result.GmcNumber.Should().Be(gmcNumber);

            _mockRolePermissions
            .Verify(rp => rp.PermissionsForRoles(It.IsAny <IEnumerable <UserRoles> >()));
        }
예제 #11
0
        public async Task <ActionResult <PostUserResponse> > CreateUser([FromBody] PostUserRequest postUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new PostUserResponse()));
            }

            try
            {
                var oktaUser = await _oktaClient.Users.GetUserAsync(postUser.Email);

                if (oktaUser == null)
                {
                    var response = new PostUserResponse();
                    response.AddError(nameof(PostUserRequest.Email), "Okta User doesn't exist for email");
                    return(BadRequest(response));
                }

                var userToCreate = new MeUser
                {
                    OktaId    = oktaUser.Id,
                    FirstName = oktaUser.Profile.FirstName,
                    LastName  = oktaUser.Profile.LastName,
                    Email     = oktaUser.Profile.Email,
                };

                var currentUser = await CurrentUser();

                var createdUser = await _userCreationService.Handle(new CreateUserQuery(userToCreate, currentUser));

                return(Ok(Mapper.Map <PostUserResponse>(createdUser)));
            }
            catch (DocumentClientException)
            {
                return(NotFound(new PostUserResponse()));
            }
            catch (ArgumentException)
            {
                return(NotFound(new PostUserResponse()));
            }
        }
예제 #12
0
        public async void HasPermission_ForDocument_ReturnsFalse_WhenRolePermissionReturnsFalse()
        {
            // Arrange
            var expectedEmail              = "expectedEmail";
            var expectedRole               = UserRoles.MedicalExaminer;
            var expectedPermission         = Common.Authorization.Permission.AddEventToExamination;
            var expectedNationalLocationId = "expectedNationalLocationId";

            var meUser = new MeUser()
            {
                Permissions = new List <MEUserPermission>()
                {
                    new MEUserPermission()
                    {
                        PermissionId = "",
                        LocationId   = expectedNationalLocationId,
                        UserRole     = expectedRole,
                    }
                }
            };

            var document = new Mock <ILocationPath>();

            document.Setup(d => d.NationalLocationId).Returns(expectedNationalLocationId);

            _rolePermissionsMock
            .Setup(rp => rp.Can(expectedRole, expectedPermission))
            .Returns(false);

            _userRetrievalServiceMock
            .Setup(urs => urs.Handle(It.IsAny <UserRetrievalByOktaIdQuery>()))
            .Returns(Task.FromResult(meUser));

            // Act
            var result = await _sut.HasPermission(expectedEmail, document.Object, expectedPermission);

            // Assert
            result.Should().BeFalse();
        }
예제 #13
0
        public async void HasPermission_ReturnsFalse_WhenUserHasNoPermissions()
        {
            // Arrange
            var expectedEmail      = "expectedEmail";
            var expectedRole       = UserRoles.MedicalExaminer;
            var expectedPermission = Common.Authorization.Permission.AddEventToExamination;

            var meUser = new MeUser()
            {
                Permissions = new List <MEUserPermission>()
            };

            _userRetrievalServiceMock
            .Setup(urs => urs.Handle(It.IsAny <UserRetrievalByOktaIdQuery>()))
            .Returns(Task.FromResult(meUser));

            // Act
            var result = await _sut.HasPermission(expectedEmail, expectedPermission);

            // Assert
            result.Should().BeFalse();
        }
        public void ExaminationIdNull_ThrowsException()
        {
            // Arrange
            var connectionSettings = new Mock <IExaminationConnectionSettings>();
            var dbAccess           = new Mock <IDatabaseAccess>();

            dbAccess.Setup(db =>
                           db.GetItemAsync(
                               connectionSettings.Object,
                               It.IsAny <Expression <Func <MedicalExaminer.Models.Examination, bool> > >()))
            .Returns(Task.FromResult <MedicalExaminer.Models.Examination>(null));
            var user = new MeUser();
            var userRetrievalByIdService = new Mock <IAsyncQueryHandler <UserRetrievalByIdQuery, MeUser> >();

            userRetrievalByIdService.Setup(x => x.Handle(It.IsAny <UserRetrievalByIdQuery>())).Returns(Task.FromResult(user));
            var sut = new MedicalTeamUpdateService(dbAccess.Object, connectionSettings.Object, userRetrievalByIdService.Object, _urgencySettingsMock.Object);

            // Assert
            Action act = () => sut.Handle(null, "a").GetAwaiter().GetResult();

            act.Should().Throw <ArgumentNullException>();
        }
예제 #15
0
        public AuthorizedControllerTestsBase(bool setupAuthorize = true)
        {
            UsersRetrievalByOktaIdServiceMock = new Mock <IAsyncQueryHandler <UserRetrievalByOktaIdQuery, MeUser> >();

            AuthorizationServiceMock = new Mock <IAuthorizationService>();

            PermissionServiceMock = new Mock <IPermissionService>();

            AuthorizedUser = new MeUser()
            {
                UserId = "authorizedUserId",
            };

            if (setupAuthorize)
            {
                AuthorizationServiceMock
                .Setup(aus => aus.AuthorizeAsync(
                           It.IsAny <ClaimsPrincipal>(),
                           It.IsAny <ILocationPath>(),
                           It.IsAny <IEnumerable <IAuthorizationRequirement> >()))
                .Returns(Task.FromResult(AuthorizationResult.Success()));
            }
        }
예제 #16
0
        public async void GetCoronerReferralDownload_ReturnsResultNotFound_WhenNoExaminationFound()
        {
            // Arrange
            SetupAuthorize(AuthorizationResult.Failed());

            var mockMeUser = new MeUser()
            {
                UserId = "abcd"
            };

            var parentLocations = new List <Location>();

            UsersRetrievalByOktaIdServiceMock.Setup(service => service.Handle(It.IsAny <UserRetrievalByOktaIdQuery>()))
            .Returns(Task.FromResult(mockMeUser));

            _examinationRetrievalQueryServiceMock.Setup(service => service.Handle(It.IsAny <ExaminationRetrievalQuery>())).Returns(Task.FromResult(default(Examination)));

            // Act
            var response = await Controller.GetCoronerReferralDownload("examinationId");

            // Assert
            response.Result.Should().BeAssignableTo <NotFoundResult>();
        }
예제 #17
0
        public async void CreateExamination_ValidModelStateReturnsOkResponse()
        {
            // Arrange
            SetupAuthorize(AuthorizationResult.Success());
            var examination = CreateValidExamination();

            _createExaminationServiceMock
            .Setup(ecs => ecs.Handle(It.IsAny <CreateExaminationQuery>()))
            .Returns(Task.FromResult(examination));

            var mockMeUser = new MeUser
            {
                UserId = "abcd"
            };

            var parentLocations = new List <Location>();

            UsersRetrievalByOktaIdServiceMock.Setup(service => service.Handle(It.IsAny <UserRetrievalByOktaIdQuery>()))
            .Returns(Task.FromResult(mockMeUser));

            _locationParentsServiceMock.Setup(lps => lps.Handle(It.IsAny <LocationParentsQuery>()))
            .Returns(Task.FromResult(parentLocations.AsEnumerable()));

            // Act
            var response = await Controller.CreateExamination(CreateValidNewCaseRequest());

            // Assert
            response.Result.Should().BeAssignableTo <OkObjectResult>();
            var result = (OkObjectResult)response.Result;

            result.Value.Should().BeAssignableTo <PutExaminationResponse>();
            var model = (PutExaminationResponse)result.Value;

            model.Errors.Count.Should().Be(0);
            model.Success.Should().BeTrue();
        }
예제 #18
0
        public async Task UpdateProfile_ReturnsNotFound_WhenArgumentExceptionThrown()
        {
            // Arrange
            const string userId = "userId";

            var user = new MeUser
            {
                UserId      = userId,
                Permissions = new MEUserPermission[0]
            };
            var request = new PutProfileRequest()
            {
                GmcNumber = "gmcNumber"
            };

            _userUpdateService
            .Setup(up => up.Handle(It.IsAny <UserUpdateQuery>()))
            .Throws <InvalidOperationException>();

            Controller.ControllerContext = GetControllerContext();

            // Act
            var response = await Controller.UpdateUserProfile(userId, request);

            // Assert
            response.Result.Should().BeAssignableTo <NotFoundObjectResult>();
            var result = (NotFoundObjectResult)response.Result;

            result.Value.Should().BeAssignableTo <PutProfileResponse>();
            var model = (PutProfileResponse)result.Value;

            model.Errors.Count.Should().Be(0);
            model.Success.Should().BeTrue();

            model.UserId.Should().Be(null);
        }
예제 #19
0
 public async Task <CosmosListPage <RMA> > ListRMAsByOrderID(string orderID, CommerceRole commerceRole, MeUser me, bool accessAllRMAsOnOrder = false)
 {
     return(await _rmaCommand.ListRMAsByOrderID(orderID, commerceRole, me, accessAllRMAsOnOrder));
 }
예제 #20
0
 public CoronerReferralQuery(string examinationId, MeUser user)
 {
     ExaminationId = examinationId;
     User          = user;
 }
 public ExaminationRetrievalQuery(string examinationId, MeUser user)
 {
     ExaminationId = examinationId;
     User          = user;
 }
 private void SetupUserRetrievalByIdMock(string userId, MeUser expectedUser)
 {
     _userRetrievalByIdServiceMock
     .Setup(urbis => urbis.Handle(It.Is <UserRetrievalByIdQuery>(query => query.UserId == userId)))
     .Returns(Task.FromResult(expectedUser));
 }
예제 #23
0
        public virtual async Task <CosmosListPage <RMA> > ListRMAsByOrderID(string orderID, CommerceRole commerceRole, MeUser me, bool accessAllRMAsOnOrder = false)
        {
            string sourceOrderID = orderID.Split("-")[0];

            CosmosListOptions listOptions = new CosmosListOptions()
            {
                PageSize = 100
            };

            IQueryable <RMA> queryable = _rmaRepo.GetQueryable()
                                         .Where(rma =>
                                                rma.PartitionKey == "PartitionValue" &&
                                                rma.SourceOrderID == sourceOrderID);

            if (commerceRole == CommerceRole.Supplier && !accessAllRMAsOnOrder)
            {
                queryable = QueryOnlySupplierRMAs(queryable, me.Supplier.ID);
            }

            CosmosListPage <RMA> rmas = await GenerateRMAList(queryable, listOptions);

            return(rmas);
        }
예제 #24
0
        public void Close_Case_When_Outstanding_Case_Items_Completed_Marks_Examination_Completed_And_Returns_ExaminationID()
        {
            // Arrange
            var examinationId = Guid.NewGuid().ToString();
            var caseOutcome   = new MedicalExaminer.Models.CaseOutcome
            {
                CaseMedicalExaminerFullName       = "ME Full Name",
                ScrutinyConfirmedOn               = new DateTime(2019, 6, 20),
                OutcomeQapDiscussion              = QapDiscussionOutcome.MccdCauseOfDeathProvidedByQAP,
                OutcomeOfPrescrutiny              = OverallOutcomeOfPreScrutiny.IssueAnMccd,
                OutcomeOfRepresentativeDiscussion = BereavedDiscussionOutcome.CauseOfDeathAccepted,
                CaseCompleted       = false,
                CaseOutcomeSummary  = CaseOutcomeSummary.IssueMCCD,
                MccdIssued          = true,
                CremationFormStatus = CremationFormStatus.Yes,
                GpNotifiedStatus    = GPNotified.GPNotified,
                CoronerReferralSent = false
            };
            var examination = new MedicalExaminer.Models.Examination
            {
                ExaminationId                 = examinationId,
                ScrutinyConfirmed             = false,
                OutstandingCaseItemsCompleted = true,
                CaseOutcome = caseOutcome
            };
            var user = new MeUser
            {
                UserId    = "UserId",
                FirstName = "FirstName",
                LastName  = "LastName",
                GmcNumber = "GmcNumber"
            };
            var connectionSettings = new Mock <IExaminationConnectionSettings>();
            var query    = new CloseCaseQuery(examinationId, user);
            var dbAccess = new Mock <IDatabaseAccess>();

            dbAccess.Setup(db => db.GetItemByIdAsync <MedicalExaminer.Models.Examination>(
                               connectionSettings.Object,
                               It.IsAny <string>()))
            .Returns(Task.FromResult(examination)).Verifiable();

            dbAccess.Setup(db => db.UpdateItemAsync(
                               connectionSettings.Object,
                               It.IsAny <MedicalExaminer.Models.Examination>())).Returns(Task.FromResult(examination)).Verifiable();

            var sut = new CloseCaseService(dbAccess.Object, connectionSettings.Object, _urgencySettingsMock.Object);

            // Act
            var result = sut.Handle(query);

            // Assert
            Assert.NotNull(result.Result);
            Assert.True(examination.CaseCompleted);
            Assert.Equal(examinationId, result.Result);
            Assert.NotNull(examination.DateCaseClosed);
            Assert.Equal(DateTime.Now.Date, examination.DateCaseClosed.Value.Date);
            Assert.NotNull(examination.CaseBreakdown.CaseClosedEvent);
            Assert.Equal(user.FullName(), examination.CaseBreakdown.CaseClosedEvent.UserFullName);
            Assert.Equal(user.UserId, examination.CaseBreakdown.CaseClosedEvent.UserId);
            Assert.Equal(user.GmcNumber, examination.CaseBreakdown.CaseClosedEvent.GmcNumber);
        }
        public void ValidateToken_ShouldThrowException_WhenValidTokenAndNoUserOrSessionExists_AndUserExistsWithSameEmail_ButEmailIsAlreadyBound()
        {
            // Arrange
            var userId                    = "userId";
            var oktaId                    = "oktaId";
            var token                     = "expectedToken";
            var validatedToken            = new Mock <SecurityToken>().Object;
            var tokenValidationParameters = new TokenValidationParameters();
            var introspectResponse        = new IntrospectResponse
            {
                Active = true
            };
            var mockExpectedClaims = new Mock <ClaimsPrincipal>();
            var claims             = new List <Claim>();
            var claim = new Claim(MEClaimTypes.OktaUserId, oktaId);

            claims.Add(claim);
            mockExpectedClaims.Setup(cp => cp.Claims).Returns(claims);
            var identities = new List <ClaimsIdentity>();
            var identity   = new ClaimsIdentity();

            identities.Add(identity);
            mockExpectedClaims.Setup(cp => cp.Identities).Returns(identities);

            _mockTokenService
            .Setup(ts => ts.IntrospectToken(token, It.IsAny <HttpClient>()))
            .Returns(Task.FromResult(introspectResponse));

            var user = new MeUser
            {
                UserId = userId,
                OktaId = oktaId,
                Email  = "oktaEmail",
            };

            var oktaUser = new Mock <IUser>(MockBehavior.Strict);

            oktaUser.Setup(o => o.Id).Returns(oktaId);
            oktaUser.Setup(o => o.Profile.FirstName).Returns("oktaFirstName");
            oktaUser.Setup(o => o.Profile.LastName).Returns("oktaLastName");
            oktaUser.Setup(o => o.Profile.Email).Returns("oktaEmail");

            var mockUsersClient = new Mock <IUsersClient>(MockBehavior.Strict);

            mockUsersClient
            .Setup(service => service.GetUserAsync(It.IsAny <string>(), default(CancellationToken)))
            .Returns(Task.FromResult(oktaUser.Object));

            _mockOktaClient
            .Setup(service => service.Users)
            .Returns(mockUsersClient.Object);

            _mockUserSessionRetrievalByOktaIdService
            .Setup(service => service.Handle(It.IsAny <UserSessionRetrievalByOktaIdQuery>()))
            .Returns(Task.FromResult((MeUserSession)null))
            .Verifiable();

            _mockUserRetrievalByOktaId
            .Setup(service => service.Handle(It.IsAny <UserRetrievalByOktaIdQuery>()))
            .Returns(Task.FromResult((MeUser)null));

            _mockUserRetrievalByEmailService
            .Setup(service => service.Handle(It.IsAny <UserRetrievalByEmailQuery>()))
            .Returns(Task.FromResult(user));

            var createUserResponse = new MeUser
            {
                UserId = "createUserId"
            };

            _mockUserCreationService
            .Setup(service => service.Handle(It.IsAny <CreateUserQuery>()))
            .Returns((CreateUserQuery query) => Task.FromResult(createUserResponse))
            .Verifiable();

            _mockTokenValidator.Setup(stv =>
                                      stv.ValidateToken(
                                          token,
                                          tokenValidationParameters,
                                          out validatedToken))
            .Returns(mockExpectedClaims.Object);

            _mockUserSessionUpdateOktaTokenService
            .Setup(service => service.Handle(It.IsAny <UserSessionUpdateOktaTokenQuery>()))
            .Returns((UserSessionUpdateOktaTokenQuery param) => Task.FromResult(new MeUserSession()
            {
                UserId          = param.UserId,
                OktaId          = oktaId,
                OktaToken       = param.OktaToken,
                OktaTokenExpiry = param.OktaTokenExpiry,
            }))
            .Verifiable();

            // Act
            Action action = () => _sut
                            .ValidateToken(token, tokenValidationParameters, out validatedToken)
                            .Should().Be(mockExpectedClaims.Object);

            // Assert
            action.Should().Throw <Exception>();
        }
        public void ValidateToken_ShouldReturnClaimsPrincipalAndNotUpdateUserInfo_WhenValidTokenChangedButUserInfoAlreadyUpToDate()
        {
            // Arrange
            var userId                    = "userId";
            var oktaId                    = "oktaId";
            var token                     = "expectedToken";
            var originalToken             = "expectedOriginalToken";
            var validatedToken            = new Mock <SecurityToken>().Object;
            var tokenValidationParameters = new TokenValidationParameters();
            var introspectResponse        = new IntrospectResponse
            {
                Active = true
            };
            var mockExpectedClaims = new Mock <ClaimsPrincipal>();
            var claims             = new List <Claim>();
            var claim = new Claim(MEClaimTypes.OktaUserId, oktaId);

            claims.Add(claim);
            mockExpectedClaims.Setup(cp => cp.Claims).Returns(claims);
            var identities = new List <ClaimsIdentity>();
            var identity   = new ClaimsIdentity();

            identities.Add(identity);
            mockExpectedClaims.Setup(cp => cp.Identities).Returns(identities);

            _mockTokenService
            .Setup(ts => ts.IntrospectToken(token, It.IsAny <HttpClient>()))
            .Returns(Task.FromResult(introspectResponse));

            var session = new MeUserSession
            {
                UserId          = userId,
                OktaId          = oktaId,
                OktaToken       = originalToken,
                OktaTokenExpiry = DateTimeOffset.Now.AddDays(-1),
            };

            var user = new MeUser
            {
                UserId    = userId,
                FirstName = "oktaFirstName",
                LastName  = "oktaLastName",
                Email     = "oktaEmail",
            };

            var oktaUser = new Mock <IUser>(MockBehavior.Strict);

            oktaUser.Setup(o => o.Profile.FirstName).Returns("oktaFirstName");
            oktaUser.Setup(o => o.Profile.LastName).Returns("oktaLastName");
            oktaUser.Setup(o => o.Profile.Email).Returns("oktaEmail");

            var mockUsersClient = new Mock <IUsersClient>(MockBehavior.Strict);

            mockUsersClient
            .Setup(service => service.GetUserAsync(It.IsAny <string>(), default(CancellationToken)))
            .Returns(Task.FromResult(oktaUser.Object));

            _mockOktaClient
            .Setup(service => service.Users)
            .Returns(mockUsersClient.Object);

            _mockUserSessionRetrievalByOktaIdService
            .Setup(service => service.Handle(It.IsAny <UserSessionRetrievalByOktaIdQuery>()))
            .Returns(Task.FromResult(session))
            .Verifiable();

            _mockTokenValidator.Setup(stv =>
                                      stv.ValidateToken(
                                          token,
                                          tokenValidationParameters,
                                          out validatedToken))
            .Returns(mockExpectedClaims.Object);

            _mockUserSessionUpdateOktaTokenService
            .Setup(service => service.Handle(It.IsAny <UserSessionUpdateOktaTokenQuery>()))
            .Returns((UserSessionUpdateOktaTokenQuery param) => Task.FromResult(new MeUserSession()
            {
                UserId          = param.UserId,
                OktaId          = session.OktaId,
                OktaToken       = param.OktaToken,
                OktaTokenExpiry = param.OktaTokenExpiry,
            }))
            .Verifiable();

            _mockUserRetrievalById
            .Setup(service => service.Handle(It.IsAny <UserRetrievalByIdQuery>()))
            .Returns(Task.FromResult(user));

            _mockUserUpdateService
            .Setup(service => service.Handle(It.IsAny <UserUpdateQuery>()))
            .Verifiable();

            // Act
            _sut.ValidateToken(token, tokenValidationParameters, out validatedToken)
            .Should().Be(mockExpectedClaims.Object);

            // Assert
            _mockTokenService
            .Verify(ts => ts.IntrospectToken(token, It.IsAny <HttpClient>()));

            _mockUserSessionUpdateOktaTokenService
            .Verify(service => service.Handle(It.IsAny <UserSessionUpdateOktaTokenQuery>()));

            _mockUserUpdateService
            .Verify(service => service.Handle(It.IsAny <UserUpdateQuery>()), Times.Never);
        }
        public void UserDraftsReturned()
        {
            var myUser = new MeUser()
            {
                UserId = "123"
            };

            var otherUser = new MeUser()
            {
                UserId = "456"
            };

            var myUserDraft = new OtherEvent()
            {
                EventId = "2",
                IsFinal = false,
                Text    = "draft user one",
                UserId  = "123",
                Created = DateTime.Now
            };

            var otherUserDraft = new OtherEvent()
            {
                EventId = "3",
                IsFinal = false,
                Text    = "draft user other",
                UserId  = "456",
                Created = DateTime.Now
            };

            var latest = new OtherEvent()
            {
                EventId = "1",
                IsFinal = true,
                Text    = "The others",
                UserId  = "123",
                Created = DateTime.Now
            };
            var drafts  = new[] { otherUserDraft };
            var history = new[] { latest };

            var caseBreakdown = new CaseBreakDown()
            {
                OtherEvents = new OtherEventContainer()
                {
                    Drafts  = drafts,
                    Latest  = latest,
                    History = history
                }
            };

            var examination = new Examination()
            {
                CaseBreakdown = caseBreakdown
            };

            var result = _mapper.Map <CaseBreakDownItem>(examination, opt => opt.Items["user"] = myUser);

            Assert.Equal(latest.EventId, result.OtherEvents.Latest.EventId);
            result.OtherEvents.History.Should().BeEquivalentTo(history);
            Assert.Null(result.OtherEvents.UsersDraft);

            var otherResult = _mapper.Map <CaseBreakDownItem>(examination, opt => opt.Items["user"] = otherUser);

            Assert.Equal(latest.EventId, result.OtherEvents.Latest.EventId);
            otherResult.OtherEvents.History.Should().BeEquivalentTo(history);
            Assert.Equal(otherUserDraft.EventId, otherResult.OtherEvents.UsersDraft.EventId);
        }
 public PatientDetailsUpdateQuery(string caseId, Models.PatientDetails patientDetails, MeUser user, IEnumerable <Models.Location> locations)
 {
     CaseId         = caseId;
     PatientDetails = patientDetails;
     User           = user;
     Locations      = locations;
 }
        /// <summary>
        /// 结束考试.
        /// </summary>
        /// <param name="userID"></param>
        /// <param name="examinationID"></param>
        /// <returns></returns>
        public bool FinishExamination(long userID, long examinationID, long userExaminationID)
        {
            try
            {
                using (MyExaminationContext context = new MyExaminationContext())
                {
                    // 用户检查.
                    MeUser user = context.Users.Find(userID);
                    if (user == null)
                    {
                        // 用户不存在.
                        return(false);
                    }

                    // 考试主表检查.
                    MeExamination examination = context.Examinations.Find(examinationID);
                    if (examination == null)
                    {
                        // 考试主表不存在.
                        return(false);
                    }

                    // 用户考试数据检查.
                    MeUserExamination userExamination = context.UserExaminations.Find(userExaminationID);
                    if (userExamination == null)
                    {
                        // 用户考试数据不存在.
                        return(false);
                    }
                    if (userExamination.UserID != userID)
                    {
                        // 参数不正确, 当前用户尝试结束别人的考试.
                        return(false);
                    }
                    if (userExamination.ExaminationID != examinationID)
                    {
                        // 参数不正确, 当前用户尝试结束另外一个考试代码不匹配的考试.
                        return(false);
                    }

                    if (userExamination.ExaminationFinishTime != null)
                    {
                        // 考试已经结束.
                        return(false);
                    }



                    // #####  计算成绩. #####

                    // 先获取用户回答数据.
                    var userAnswerQuery =
                        from data in context.UserAnswers
                        where
                        data.UserExaminationID == userExaminationID
                        select
                        data;
                    List <MeUserAnswer> userAnswerList = userAnswerQuery.ToList();


                    // 获取试题与选项.
                    var query =
                        from data in context.Questions.Include("QuestionOptionList")
                        where
                        data.ExaminationID == examinationID
                        select
                        data;
                    List <MeQuestion> questionList = query.ToList();


                    // 总成绩.
                    int totalPoint = 0;


                    // 遍历每一题.
                    foreach (var questionData in questionList)
                    {
                        // 正确答案.
                        List <string> rightAnswerList = new List <string>();

                        switch (questionData.QuestionType)
                        {
                        case MeQuestionType.OneOption:
                            // 单选.
                            var rigthData = questionData.QuestionOptionList.SingleOrDefault(p => p.IsRightOption);
                            if (rigthData == null)
                            {
                                logger.WarnFormat("题目答案出现异常, 第 {0} 题, 不存在正确的选择项目", questionData.QuestionID);
                            }
                            else
                            {
                                rightAnswerList.Add(rigthData.QuestionOptionID.ToString());
                            }
                            break;

                        case MeQuestionType.MulOption:
                            // 多选.
                            List <string> answerList = questionData.QuestionOptionList.Where(p => p.IsRightOption).Select(p => p.QuestionOptionID.ToString()).ToList();
                            rightAnswerList.AddRange(answerList);
                            break;

                        default:
                            // 未知.
                            break;
                        }


                        // 获取用户输入.
                        MeUserAnswer userAnswer = userAnswerList.SingleOrDefault(p => p.UserExaminationID == userExaminationID && p.QuestionID == questionData.QuestionID);

                        if (userAnswer == null)
                        {
                            logger.WarnFormat("回答出现一些问题, 第 {0} 题, 用户 {1} 没有做回答。", questionData.QuestionID, userID);
                            // 用户未回答当前题目.
                            continue;
                        }

                        if (CompareUserAnswer(rightAnswerList, userAnswer.UserAnswer))
                        {
                            // 回答正确时, 获得分数.
                            userAnswer.AnswerPoint = questionData.QuestionPoint;

                            // 累加总成绩.
                            totalPoint += questionData.QuestionPoint;
                        }
                    }

                    // 设置结束时间.
                    userExamination.ExaminationFinishTime = DateTime.Now;

                    // 设置总成绩.
                    userExamination.ExaminationPoint = totalPoint;

                    context.SaveChanges();

                    return(true);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                return(false);
            }
        }
        public bool BatchSubmitUserAnswer(BatchSubmitUserAnswerInput data)
        {
            try
            {
                using (MyExaminationContext context = new MyExaminationContext())
                {
                    // 用户检查.
                    MeUser user = context.Users.Find(data.UserID);
                    if (user == null)
                    {
                        // 用户不存在.
                        return(false);
                    }

                    // 用户考试数据检查.
                    MeUserExamination userExamination = context.UserExaminations.Find(data.UserExaminationID);
                    if (userExamination == null)
                    {
                        // 用户考试数据不存在.
                        return(false);
                    }
                    if (userExamination.UserID != data.UserID)
                    {
                        // 参数不正确, 当前用户对别人的考试进行回答.
                        return(false);
                    }
                    if (userExamination.ExaminationFinishTime != null)
                    {
                        // 考试已经结束.
                        return(false);
                    }



                    foreach (QuestionAnswer item in data.QuestionAnswers)
                    {
                        // 获取具体的问题.
                        MeQuestion question = context.Questions.Find(item.QuestionID);
                        if (question == null)
                        {
                            // 问题不存在.
                            return(false);
                        }


                        // 单选的情况下,检查 提交的答案, 是否是 可选答案.
                        if (question.QuestionType == MeQuestionType.OneOption)
                        {
                            long questionOptionID = 0;
                            if (!Int64.TryParse(item.OneOptionAnswer, out questionOptionID))
                            {
                                // 对于 单选/多选, 提交的数据, 无法解析为 long 值.
                                return(false);
                            }

                            MeQuestionOption questionOption = context.QuestionOptions.Find(questionOptionID);
                            if (questionOption == null)
                            {
                                // 不存在的 答案选项.
                                return(false);
                            }
                            if (questionOption.QuestionID != item.QuestionID)
                            {
                                // 答案选项, 与 问题不匹配.
                                return(false);
                            }
                        }
                        // 多选的情况下,检查 提交的答案, 是否是 可选答案.
                        if (question.QuestionType == MeQuestionType.MulOption)
                        {
                            foreach (string answerString in item.MulOptionAnswer)
                            {
                                long questionOptionID = 0;
                                if (!Int64.TryParse(answerString, out questionOptionID))
                                {
                                    // 对于 单选/多选, 提交的数据, 无法解析为 long 值.
                                    return(false);
                                }
                                MeQuestionOption questionOption = context.QuestionOptions.Find(questionOptionID);
                                if (questionOption == null)
                                {
                                    // 不存在的 答案选项.
                                    return(false);
                                }
                                if (questionOption.QuestionID != item.QuestionID)
                                {
                                    // 答案选项, 与 问题不匹配.
                                    return(false);
                                }
                            }
                        }

                        var answerQuery =
                            from answerData in context.UserAnswers
                            where
                            answerData.UserExaminationID == data.UserExaminationID &&
                            answerData.UserID == data.UserID &&
                            answerData.QuestionID == item.QuestionID
                            select
                            answerData;

                        MeUserAnswer userAnswerData = answerQuery.SingleOrDefault();

                        if (userAnswerData == null)
                        {
                            // 是首次回答.
                            userAnswerData = new MeUserAnswer()
                            {
                                // 用户考试ID.
                                UserExaminationID = data.UserExaminationID,
                                // 用户ID.
                                UserID = data.UserID,
                                // 问题ID.
                                QuestionID = item.QuestionID,
                                // 回答.
                                UserAnswer = item.ResultAnswer,
                            };
                            context.UserAnswers.Add(userAnswerData);
                        }
                        else
                        {
                            // 是修改之前的回答.
                            userAnswerData.UserAnswer = item.ResultAnswer;
                        }
                    }



                    context.SaveChanges();
                }

                return(true);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message, ex);
                return(false);
            }
        }