src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
ProjectFinanceServiceImpl extends AbstractFinanceService<ProjectFinance, ProjectFinanceResource> implements ProjectFinanceService { @Override public ServiceResult<ProjectFinanceResource> financeChecksDetails(long projectId, long organisationId) { return getProjectFinanceForOrganisation(new ProjectFinanceResourceId(projectId, organisationId)); } @Override ServiceResult<ProjectFinanceResource> financeChecksDetails(long projectId, long organisationId); @Override ServiceResult<List<ProjectFinanceResource>> financeChecksTotals(long projectId); @Override ServiceResult<Void> createProjectFinance(long projectId, long organisationId); @Override ServiceResult<Void> updateProjectFinance(ProjectFinanceResource projectFinanceResource); @Override ServiceResult<Boolean> hasAnyProjectOrganisationSizeChangedFromApplication(long projectId); @Override ServiceResult<Double> getResearchParticipationPercentageFromProject(long projectId); } | @Test public void financeCheckDetailsSuccessful() { ProjectFinanceResourceId projectFinanceResourceId = new ProjectFinanceResourceId(project.getId(), organisation.getId()); ProjectFinanceResource expected = newProjectFinanceResource().build(); when(projectFinanceHandlerMock.getProjectOrganisationFinances(projectFinanceResourceId)).thenReturn(serviceSuccess(expected)); ServiceResult<ProjectFinanceResource> result = service.financeChecksDetails(project.getId(), organisation.getId()); assertTrue(result.isSuccess()); assertEquals(result.getSuccess(), expected); }
@Test public void financeCheckDetailsUnsuccessful() { ProjectFinanceResourceId projectFinanceResourceId = new ProjectFinanceResourceId(project.getId(), organisation.getId()); when(projectFinanceHandlerMock.getProjectOrganisationFinances(projectFinanceResourceId)).thenReturn(serviceFailure(notFoundError(ProjectFinanceResource.class))); ServiceResult<ProjectFinanceResource> result = service.financeChecksDetails(project.getId(), organisation.getId()); assertTrue(result.isFailure()); assertTrue(result.getErrors().contains(notFoundError(ProjectFinanceResource.class))); } |
ApplicationFinance extends Finance { @Override public Application getApplication() { return application; } ApplicationFinance(); ApplicationFinance(Application application, Organisation organisation); @Override Application getApplication(); FileEntry getFinanceFileEntry(); void setFinanceFileEntry(FileEntry financeFileEntry); void setApplication(Application application); String getWorkPostcode(); void setWorkPostcode(String workPostcode); String getInternationalLocation(); void setInternationalLocation(String internationalLocation); String getJustification(); void setJustification(String justification); } | @Test public void applicationFinanceShouldReturnCorrectAttributeValues() { assertEquals(applicationFinance.getOrganisation(), organisation); assertEquals(applicationFinance.getApplication(), application); } |
CategoryServiceImpl extends BaseTransactionalService implements CategoryService { @Override @Cacheable(cacheNames="getInnovationAreas", key = "#root.methodName", unless = "#result.isFailure()") public ServiceResult<List<InnovationAreaResource>> getInnovationAreas() { return find(innovationAreaRepository.findAllByOrderByNameAsc(), notFoundError(InnovationArea.class)) .andOnSuccessReturn(innovationAreaMapper::mapToResource); } @Override @Cacheable(cacheNames="getInnovationAreas", key = "#root.methodName", unless = "#result.isFailure()") ServiceResult<List<InnovationAreaResource>> getInnovationAreas(); @Override @Cacheable(cacheNames="getInnovationSectors", key = "#root.methodName", unless = "#result.isFailure()") ServiceResult<List<InnovationSectorResource>> getInnovationSectors(); @Override @Cacheable(cacheNames="getResearchCategories", key = "#root.methodName", unless = "#result.isFailure()") ServiceResult<List<ResearchCategoryResource>> getResearchCategories(); @Override ServiceResult<List<InnovationAreaResource>> getInnovationAreasBySector(long sectorId); } | @Test public void getInnovationAreas() { List<InnovationArea> innovationAreas = newInnovationArea().build(2); List<InnovationAreaResource> expectedInnovationAreaResources = newInnovationAreaResource().build(2); when(innovationAreaRepository.findAllByOrderByNameAsc()).thenReturn(innovationAreas); when(innovationAreaMapper.mapToResource(refEq(innovationAreas))).thenReturn(expectedInnovationAreaResources); List<InnovationAreaResource> actualInnovationAreaResources = categoryService.getInnovationAreas().getSuccess(); assertEquals(expectedInnovationAreaResources, actualInnovationAreaResources); InOrder inOrder = inOrder(innovationAreaRepository, innovationAreaMapper, questionMapper); inOrder.verify(innovationAreaRepository).findAllByOrderByNameAsc(); inOrder.verify(innovationAreaMapper).mapToResource(innovationAreas); inOrder.verifyNoMoreInteractions(); } |
CategoryServiceImpl extends BaseTransactionalService implements CategoryService { @Override @Cacheable(cacheNames="getInnovationSectors", key = "#root.methodName", unless = "#result.isFailure()") public ServiceResult<List<InnovationSectorResource>> getInnovationSectors() { return find(innovationSectorRepository.findAllByOrderByPriorityAsc(), notFoundError(InnovationSector.class)) .andOnSuccessReturn(innovationSectorMapper::mapToResource); } @Override @Cacheable(cacheNames="getInnovationAreas", key = "#root.methodName", unless = "#result.isFailure()") ServiceResult<List<InnovationAreaResource>> getInnovationAreas(); @Override @Cacheable(cacheNames="getInnovationSectors", key = "#root.methodName", unless = "#result.isFailure()") ServiceResult<List<InnovationSectorResource>> getInnovationSectors(); @Override @Cacheable(cacheNames="getResearchCategories", key = "#root.methodName", unless = "#result.isFailure()") ServiceResult<List<ResearchCategoryResource>> getResearchCategories(); @Override ServiceResult<List<InnovationAreaResource>> getInnovationAreasBySector(long sectorId); } | @Test public void getInnovationSectors() { List<InnovationSector> innovationSectors = newInnovationSector().build(2); List<InnovationSectorResource> expectedInnovationSectorResources = newInnovationSectorResource().build(2); when(innovationSectorRepository.findAllByOrderByPriorityAsc()).thenReturn(innovationSectors); when(innovationSectorMapper.mapToResource(refEq(innovationSectors))).thenReturn(expectedInnovationSectorResources); List<InnovationSectorResource> actualInnovationSectorResources = categoryService.getInnovationSectors().getSuccess(); assertEquals(expectedInnovationSectorResources, actualInnovationSectorResources); InOrder inOrder = inOrder(innovationSectorRepository, innovationSectorMapper); inOrder.verify(innovationSectorRepository).findAllByOrderByPriorityAsc(); inOrder.verify(innovationSectorMapper).mapToResource(innovationSectors); inOrder.verifyNoMoreInteractions(); } |
CategoryServiceImpl extends BaseTransactionalService implements CategoryService { @Override @Cacheable(cacheNames="getResearchCategories", key = "#root.methodName", unless = "#result.isFailure()") public ServiceResult<List<ResearchCategoryResource>> getResearchCategories() { return find(researchCategoryRepository.findAllByOrderByPriorityAsc(), notFoundError(ResearchCategory.class)) .andOnSuccessReturn(researchCategoryMapper::mapToResource); } @Override @Cacheable(cacheNames="getInnovationAreas", key = "#root.methodName", unless = "#result.isFailure()") ServiceResult<List<InnovationAreaResource>> getInnovationAreas(); @Override @Cacheable(cacheNames="getInnovationSectors", key = "#root.methodName", unless = "#result.isFailure()") ServiceResult<List<InnovationSectorResource>> getInnovationSectors(); @Override @Cacheable(cacheNames="getResearchCategories", key = "#root.methodName", unless = "#result.isFailure()") ServiceResult<List<ResearchCategoryResource>> getResearchCategories(); @Override ServiceResult<List<InnovationAreaResource>> getInnovationAreasBySector(long sectorId); } | @Test public void getResearchCategories() { List<ResearchCategory> researchCategories = newResearchCategory().build(2); List<ResearchCategoryResource> expectedResearchCategoryResources = newResearchCategoryResource().build(2); when(researchCategoryRepository.findAllByOrderByPriorityAsc()).thenReturn(researchCategories); when(researchCategoryMapper.mapToResource(refEq(researchCategories))).thenReturn(expectedResearchCategoryResources); List<ResearchCategoryResource> actualResearchCategoryResources = categoryService.getResearchCategories().getSuccess(); assertEquals(expectedResearchCategoryResources, actualResearchCategoryResources); InOrder inOrder = inOrder(researchCategoryRepository, researchCategoryMapper); inOrder.verify(researchCategoryRepository).findAllByOrderByPriorityAsc(); inOrder.verify(researchCategoryMapper).mapToResource(researchCategories); inOrder.verifyNoMoreInteractions(); } |
CategoryServiceImpl extends BaseTransactionalService implements CategoryService { @Override public ServiceResult<List<InnovationAreaResource>> getInnovationAreasBySector(long sectorId) { return find(innovationSectorRepository.findById(sectorId), notFoundError(InnovationSector.class, sectorId)) .andOnSuccess(this::getInnovationAreasFromParent); } @Override @Cacheable(cacheNames="getInnovationAreas", key = "#root.methodName", unless = "#result.isFailure()") ServiceResult<List<InnovationAreaResource>> getInnovationAreas(); @Override @Cacheable(cacheNames="getInnovationSectors", key = "#root.methodName", unless = "#result.isFailure()") ServiceResult<List<InnovationSectorResource>> getInnovationSectors(); @Override @Cacheable(cacheNames="getResearchCategories", key = "#root.methodName", unless = "#result.isFailure()") ServiceResult<List<ResearchCategoryResource>> getResearchCategories(); @Override ServiceResult<List<InnovationAreaResource>> getInnovationAreasBySector(long sectorId); } | @Test public void getInnovationAreasBySector() { List<InnovationArea> innovationAreas = newInnovationArea().build(2); InnovationSector innovationSector = newInnovationSector() .withChildren(innovationAreas) .build(); long sectorId = 1L; List<InnovationAreaResource> expectedInnovationAreaResources = newInnovationAreaResource().build(2); when(innovationSectorRepository.findById(sectorId)).thenReturn(Optional.of(innovationSector)); when(innovationAreaMapper.mapToResource(refEq(innovationAreas))).thenReturn(expectedInnovationAreaResources); List<InnovationAreaResource> actualInnovationAreaResources = categoryService.getInnovationAreasBySector(sectorId).getSuccess(); assertEquals(expectedInnovationAreaResources, actualInnovationAreaResources); verify(innovationSectorRepository, times(1)).findById(sectorId); InOrder inOrder = inOrder(innovationSectorRepository, innovationAreaMapper); inOrder.verify(innovationSectorRepository).findById(sectorId); inOrder.verify(innovationAreaMapper).mapToResource(innovationAreas); inOrder.verifyNoMoreInteractions(); }
@Test public void getInnovationAreasByOpenSector() { List<InnovationArea> innovationAreas = EMPTY_LIST; InnovationSector innovationSector = newInnovationSector() .withChildren(innovationAreas) .build(); long sectorId = 1L; List<InnovationArea> allInnovationAreas = newInnovationArea().build(2); List<InnovationAreaResource> expectedInnovationAreaResources = newInnovationAreaResource().build(2); when(innovationSectorRepository.findById(sectorId)).thenReturn(Optional.of(innovationSector)); when(innovationAreaMapper.mapToResource(refEq(innovationAreas))).thenReturn(EMPTY_LIST); when(innovationAreaRepository.findAllByOrderByNameAsc()).thenReturn(allInnovationAreas); when(innovationAreaMapper.mapToResource(refEq(allInnovationAreas))).thenReturn(expectedInnovationAreaResources); List<InnovationAreaResource> actualInnovationAreaResources = categoryService.getInnovationAreasBySector(sectorId).getSuccess(); assertEquals(expectedInnovationAreaResources, actualInnovationAreaResources); verify(innovationSectorRepository, times(1)).findById(sectorId); InOrder inOrder = inOrder(innovationAreaRepository, innovationAreaMapper); inOrder.verify(innovationAreaMapper).mapToResource(innovationAreas); inOrder.verify(innovationAreaRepository).findAllByOrderByNameAsc(); inOrder.verify(innovationAreaMapper).mapToResource(allInnovationAreas); inOrder.verifyNoMoreInteractions(); } |
AddressController { @GetMapping("/do-lookup") public RestResult<List<AddressResource>> doLookup(@RequestParam(name="lookup", defaultValue="") final String lookup) { return addressLookupService.doLookup(lookup).toGetResponse(); } @GetMapping("/do-lookup") RestResult<List<AddressResource>> doLookup(@RequestParam(name="lookup", defaultValue="") final String lookup); @GetMapping("/validate-postcode") RestResult<Boolean> validatePostcode(@RequestParam(name="postcode", defaultValue="") final String postcode); } | @Test public void doLookupShouldReturnAddresses() throws Exception { int numberOfAddresses = 4; String postCode = "BS348XU"; List<AddressResource> addressResources = newAddressResource().build(numberOfAddresses); when(addressLookupServiceMock.doLookup(postCode)).thenReturn(serviceSuccess(addressResources)); mockMvc.perform(get("/address/do-lookup?lookup=" + postCode)) .andExpect(status().isOk()) .andExpect(jsonPath("$", hasSize(numberOfAddresses))); }
@Test public void doLookupWithSpecialCharacters() throws Exception { int numberOfAddresses = 4; String postCode = "!@£ !@£$"; List<AddressResource> addressResources = newAddressResource().build(numberOfAddresses); when(addressLookupServiceMock.doLookup(postCode)).thenReturn(serviceSuccess(addressResources)); mockMvc.perform(get("/address/do-lookup?lookup=" + postCode)) .andExpect(status().isOk()) .andExpect(jsonPath("$", hasSize(numberOfAddresses))); } |
PostcoderWeb implements AddressLookupService { @Override public ServiceResult<List<AddressResource>> doLookup(String lookup) { if (StringUtils.isEmpty(lookup)) { return ServiceResult.serviceSuccess(new ArrayList<>()); } else if (StringUtils.isEmpty(postcodeLookupUrl) || StringUtils.isEmpty(postcodeLookupKey)) { return ServiceResult.serviceSuccess(exampleAddresses()); } else { return doAPILookup(lookup); } } @Override ServiceResult<List<AddressResource>> doLookup(String lookup); @Override ServiceResult<Boolean> validatePostcode(String postcode); } | @Test public void testEmptyLookup() { ServiceResult<List<AddressResource>> lookupResult = postcoderWeb.doLookup(""); List<AddressResource> addressResources = lookupResult.getSuccess(); assertEquals(0, addressResources.size()); }
@Test public void testDummyDataLookup() { String postcode = "BS348XU"; ServiceResult<List<AddressResource>> lookupResult = postcoderWeb.doLookup(postcode); List<AddressResource> addressResources = lookupResult.getSuccess(); assertEquals(2, addressResources.size()); } |
ReviewParticipantPermissionRules extends BasePermissionRules { @PermissionRule(value = "ACCEPT", description = "only the same user can accept a panel invitation") public boolean userCanAcceptAssessmentPanelInvite(ReviewParticipantResource assessmentPanelParticipant, UserResource user) { return user != null && assessmentPanelParticipant != null && isSameUser(assessmentPanelParticipant, user); } @PermissionRule(value = "ACCEPT", description = "only the same user can accept a panel invitation") boolean userCanAcceptAssessmentPanelInvite(ReviewParticipantResource assessmentPanelParticipant, UserResource user); @PermissionRule(value = "READ", description = "only the same user can read their panel participation") boolean userCanViewTheirOwnAssessmentPanelParticipation(ReviewParticipantResource assessmentPanelParticipant, UserResource user); } | @Test public void userCanAcceptAssessmentPanelInvite() { ReviewParticipantResource reviewParticipantResource = newReviewParticipantResource() .withUser(1L) .build(); UserResource userResource = newUserResource() .withId(1L) .withRolesGlobal(singletonList(ASSESSOR)) .build(); assertTrue(rules.userCanAcceptAssessmentPanelInvite(reviewParticipantResource, userResource)); }
@Test public void userCanAcceptAssessmentPanelInvite_differentParticipantUser() { ReviewParticipantResource reviewParticipantResource = newReviewParticipantResource() .withUser(1L) .build(); UserResource userResource = newUserResource() .withId(2L) .withRolesGlobal(singletonList(ASSESSOR)) .build(); assertFalse(rules.userCanAcceptAssessmentPanelInvite(reviewParticipantResource, userResource)); }
@Test public void userCanAcceptAssessmentPanelInvite_noParticipantUserAndSameEmail() { ReviewParticipantResource reviewParticipantResource = newReviewParticipantResource() .withInvite(newReviewInviteResource().withEmail("[email protected]")) .build(); UserResource userResource = newUserResource() .withEmail("[email protected]") .withRolesGlobal(singletonList(ASSESSOR)) .build(); assertTrue(rules.userCanAcceptAssessmentPanelInvite(reviewParticipantResource, userResource)); }
@Test public void userCanAcceptCompetitionInvite_noParticipantUserAndDifferentEmail() { ReviewParticipantResource reviewParticipantResource = newReviewParticipantResource() .withInvite(newReviewInviteResource().withEmail("[email protected]")) .build(); UserResource userResource = newUserResource() .withEmail("[email protected]") .withRolesGlobal(singletonList(ASSESSOR)) .build(); assertFalse(rules.userCanAcceptAssessmentPanelInvite(reviewParticipantResource, userResource)); } |
ReviewParticipantPermissionRules extends BasePermissionRules { @PermissionRule(value = "READ", description = "only the same user can read their panel participation") public boolean userCanViewTheirOwnAssessmentPanelParticipation(ReviewParticipantResource assessmentPanelParticipant, UserResource user) { return isSameParticipant(assessmentPanelParticipant, user); } @PermissionRule(value = "ACCEPT", description = "only the same user can accept a panel invitation") boolean userCanAcceptAssessmentPanelInvite(ReviewParticipantResource assessmentPanelParticipant, UserResource user); @PermissionRule(value = "READ", description = "only the same user can read their panel participation") boolean userCanViewTheirOwnAssessmentPanelParticipation(ReviewParticipantResource assessmentPanelParticipant, UserResource user); } | @Test public void userCanViewTheirOwnAssessmentPanelParticipation() { ReviewParticipantResource reviewParticipantResource = newReviewParticipantResource() .withUser(7L) .withInvite(newReviewInviteResource().withStatus(SENT).build()) .build(); UserResource userResource = newUserResource() .withId(7L) .withRolesGlobal(singletonList(ASSESSOR)) .build(); assertTrue(rules.userCanViewTheirOwnAssessmentPanelParticipation(reviewParticipantResource, userResource)); }
@Test public void userCanViewTheirOwnAssessmentPanelParticipation_differentUser() { ReviewParticipantResource reviewParticipantResource = newReviewParticipantResource() .withUser(7L) .build(); UserResource userResource = newUserResource() .withId(11L) .withRolesGlobal(singletonList(ASSESSOR)) .build(); assertFalse(rules.userCanViewTheirOwnAssessmentPanelParticipation(reviewParticipantResource, userResource)); } |
UserPermissionRules { @PermissionRule(value = "READ", description = "A user can read their own profile agreement") public boolean usersCanViewTheirOwnProfileAgreement(ProfileAgreementResource profileAgreementResource, UserResource user) { return user.getId().equals(profileAgreementResource.getUser()); } @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "An internal user can invite a monitoring officer and create the pending user associated.") boolean compAdminProjectFinanceCanCreateMonitoringOfficer(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserRegistrationResource userToCreate, UserResource user); @PermissionRule(value = "VERIFY", description = "A System Registration User can send a new User a verification link by e-mail") boolean systemRegistrationUserCanSendUserVerificationEmail(UserResource userToSendVerificationEmail, UserResource user); @PermissionRule(value = "READ", description = "Any user can view themselves") boolean anyUserCanViewThemselves(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Internal users can view everyone") boolean internalUsersCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can view users in competitions they are assigned to") boolean stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Competition finance users can view users in competitions they are assigned to") boolean competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can view users in projects they are assigned to") boolean monitoringOfficersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ_USER_ORGANISATION", description = "Internal support users can view all users and associated organisations") boolean internalUsersCanViewUserOrganisation(UserOrganisationResource userToView, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "IFS admins can update all users email addresses") boolean ifsAdminCanUpdateAllEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "Support users can update external users email addresses ") boolean supportCanUpdateExternalUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "System Maintenance update all users email addresses") boolean systemMaintenanceUserCanUpdateUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ_INTERNAL", description = "Administrators can view internal users") boolean internalUsersCanViewEveryone(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Support users and administrators can view external users") boolean supportUsersCanViewExternalUsers(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "The System Registration user can view everyone") boolean systemRegistrationUserCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Comp admins and project finance can view assessors") boolean compAdminAndProjectFinanceCanViewAssessors(UserPageResource usersToView, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewOtherConsortiumMembers(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewConsortiumUsersOnApplicationsTheyAreAssessing(UserResource userToView, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "A User should be able to change their own password") boolean usersCanChangeTheirOwnPassword(UserResource userToUpdate, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "The System Registration user should be able to change passwords on behalf of other Users") boolean systemRegistrationUserCanChangePasswordsForUsers(UserResource userToUpdate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A System Registration User can activate Users") boolean systemRegistrationUserCanActivateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "UPDATE", description = "A User can update their own profile") boolean usersCanUpdateTheirOwnProfiles(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE", description = "An admin user can update user details to assign monitoring officers") boolean adminsCanUpdateUserDetails(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile skills") boolean usersCanViewTheirOwnProfileSkills(ProfileSkillsResource profileSkills, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile agreement") boolean usersCanViewTheirOwnProfileAgreement(ProfileAgreementResource profileAgreementResource, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own affiliations") boolean usersCanViewTheirOwnAffiliations(AffiliationResource affiliation, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A user can read their own profile") boolean usersCanViewTheirOwnProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A ifs admin user can read any user's profile") boolean ifsAdminCanViewAnyUsersProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as Comp Admin and Exec can read the user's profile status") boolean usersAndCompAdminCanViewProfileStatus(UserProfileStatusResource profileStatus, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own role") boolean usersCanViewTheirOwnProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the process role of others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewTheProcessRolesOfOtherConsortiumMembers(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Project managers and partners can view the process role for the same organisation") boolean projectPartnersCanViewTheProcessRolesWithinSameApplication(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as internal users can read the user's process role") boolean usersAndInternalUsersCanViewProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the process roles of members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewTheProcessRolesOfConsortiumUsersOnApplicationsTheyAreAssessing(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "CHECK_USER_APPLICATION", description = "The user can check if they have an application for the competition") boolean userCanCheckTheyHaveApplicationForCompetition(UserResource userToCheck, UserResource user); @PermissionRule(value = "EDIT_INTERNAL_USER", description = "Only an IFS Administrator can edit an internal user") boolean ifsAdminCanEditInternalUser(final UserResource userToEdit, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "IFS Administrator can deactivate Users") boolean ifsAdminCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "A Support user can deactivate external Users") boolean supportUserCanDeactivateExternalUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "System Maintenance can deactivate Users") boolean systemMaintenanceUserCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "IFS Administrator can reactivate Users") boolean ifsAdminCanReactivateUsers(UserResource userToReactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A Support user can reactivate external Users") boolean supportUserCanReactivateExternalUsers(UserResource userToActivate, UserResource user); @PermissionRule(value = "AGREE_TERMS", description = "A user can accept the site terms and conditions") boolean usersCanAgreeSiteTermsAndConditions(UserResource userToUpdate, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An assessor can request applicant role") boolean assessorCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant monitoring officer role") boolean isGrantingMonitoringOfficerRoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant a KTA role") boolean isGrantingKTARoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An stakeholder can request applicant role") boolean stakeholderCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An monitoring officer can request applicant role") boolean monitoringOfficerCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "CAN_VIEW_OWN_DASHBOARD", description = "User is requesting own dashboard") boolean isViewingOwnDashboard(UserResource userToView, UserResource user); } | @Test public void usersCanViewTheirOwnProfileAgreement() { UserResource user = newUserResource().build(); ProfileAgreementResource profileAgreementResource = newProfileAgreementResource() .withUser(user.getId()) .build(); assertTrue(rules.usersCanViewTheirOwnProfileAgreement(profileAgreementResource, user)); }
@Test public void usersCanViewTheirOwnProfileAgreementButAttemptingToViewAnotherUsersProfileAgreement() { UserResource user = newUserResource().build(); UserResource anotherUser = newUserResource().build(); ProfileAgreementResource profileAgreementResource = newProfileAgreementResource() .withUser(user.getId()) .build(); assertFalse(rules.usersCanViewTheirOwnProfileAgreement(profileAgreementResource, anotherUser)); } |
ReviewPermissionRules extends BasePermissionRules { @PermissionRule(value = "READ_PANEL_DASHBOARD", description = "Assessors can view all Assessment Reviews on the competition " + "dashboard, except those rejected or withdrawn") public boolean userCanReadAssessmentReviewOnDashboard(ReviewResource assessmentReview, UserResource user) { Set<ReviewState> allowedStates = EnumSet.of(PENDING, ACCEPTED); return isAssessorForAssessmentReview(assessmentReview, user, allowedStates); } @PermissionRule(value = "READ_PANEL_DASHBOARD", description = "Assessors can view all Assessment Reviews on the competition " + "dashboard, except those rejected or withdrawn") boolean userCanReadAssessmentReviewOnDashboard(ReviewResource assessmentReview, UserResource user); @PermissionRule(value = "UPDATE", description = "An assessor may only update their own invites to assessment reviews") boolean userCanUpdateAssessmentReview(ReviewResource assessmentReview, UserResource loggedInUser); @PermissionRule(value = "READ", description = "An assessor may only read their own invites to assessment reviews") boolean userCanReadAssessmentReviews(ReviewResource assessmentReview, UserResource loggedInUser); } | @Test public void ownersCanReadAssessmentsOnDashboard() { EnumSet<ReviewState> allowedStates = EnumSet.of(PENDING, ACCEPTED); allowedStates.forEach(state -> assertTrue("the owner of an assessment review should be able to read that assessment review on the dashboard", rules.userCanReadAssessmentReviewOnDashboard(assessmentReviews.get(state), assessorUser))); EnumSet.complementOf(allowedStates).forEach(state -> assertFalse("the owner of an assessment review should not be able to read that assessment review on the dashboard", rules.userCanReadAssessmentReviewOnDashboard(assessmentReviews.get(state), assessorUser))); }
@Test public void otherUsersCanNotReadAssessmentsOnDashboard() { EnumSet.allOf(ReviewState.class).forEach(state -> assertFalse("other users should not be able to read any assessment reviews", rules.userCanReadAssessmentReviewOnDashboard(assessmentReviews.get(state), otherUser))); } |
ReviewInviteController { @GetMapping("/get-available-assessors/{competitionId}") public RestResult<AvailableAssessorPageResource> getAvailableAssessors( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable) { return reviewInviteService.getAvailableAssessors(competitionId, pageable).toGetResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<ReviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping("/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping( "/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<ReviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void getAvailableAssessors() throws Exception { int page = 5; int pageSize = 30; List<AvailableAssessorResource> expectedAvailableAssessorResources = newAvailableAssessorResource().build(2); AvailableAssessorPageResource expectedAvailableAssessorPageResource = newAvailableAssessorPageResource() .withContent(expectedAvailableAssessorResources) .withNumber(page) .withTotalElements(300L) .withTotalPages(10) .withSize(30) .build(); Pageable pageable = PageRequest.of(page, pageSize, new Sort(DESC, "lastName")); when(reviewInviteServiceMock.getAvailableAssessors(COMPETITION_ID, pageable)) .thenReturn(serviceSuccess(expectedAvailableAssessorPageResource)); mockMvc.perform(get("/assessment-panel-invite/get-available-assessors/{competitionId}", COMPETITION_ID) .param("page", String.valueOf(page)) .param("size", String.valueOf(pageSize)) .param("sort", "lastName,desc")) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedAvailableAssessorPageResource))); verify(reviewInviteServiceMock, only()).getAvailableAssessors(COMPETITION_ID, pageable); }
@Test public void getAvailableAssessors_defaultParameters() throws Exception { int page = 0; int pageSize = 20; List<AvailableAssessorResource> expectedAvailableAssessorResources = newAvailableAssessorResource().build(2); AvailableAssessorPageResource expectedAvailableAssessorPageResource = newAvailableAssessorPageResource() .withContent(expectedAvailableAssessorResources) .withNumber(page) .withTotalElements(300L) .withTotalPages(10) .withSize(30) .build(); Pageable pageable = PageRequest.of(page, pageSize, new Sort(ASC, "user.firstName", "user.lastName")); when(reviewInviteServiceMock.getAvailableAssessors(COMPETITION_ID, pageable)) .thenReturn(serviceSuccess(expectedAvailableAssessorPageResource)); mockMvc.perform(get("/assessment-panel-invite/get-available-assessors/{competitionId}", COMPETITION_ID)) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedAvailableAssessorPageResource))); verify(reviewInviteServiceMock, only()).getAvailableAssessors(COMPETITION_ID, pageable); } |
ReviewInviteController { @GetMapping("/get-available-assessor-ids/{competitionId}") public RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId) { return reviewInviteService.getAvailableAssessorIds(competitionId).toGetResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<ReviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping("/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping( "/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<ReviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void getAvailableAssessorsIds() throws Exception { List<Long> expectedAvailableAssessorIds = asList(1L, 2L); when(reviewInviteServiceMock.getAvailableAssessorIds(COMPETITION_ID)) .thenReturn(serviceSuccess(expectedAvailableAssessorIds)); mockMvc.perform(get("/assessment-panel-invite/get-available-assessor-ids/{competitionId}", COMPETITION_ID)) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedAvailableAssessorIds))); verify(reviewInviteServiceMock, only()).getAvailableAssessorIds(COMPETITION_ID); } |
ReviewInviteController { @GetMapping("/get-created-invites/{competitionId}") public RestResult<AssessorCreatedInvitePageResource> getCreatedInvites( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable) { return reviewInviteService.getCreatedInvites(competitionId, pageable).toGetResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<ReviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping("/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping( "/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<ReviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void getCreatedInvites() throws Exception { int page = 5; int pageSize = 40; List<AssessorCreatedInviteResource> expectedAssessorCreatedInviteResources = newAssessorCreatedInviteResource() .build(2); AssessorCreatedInvitePageResource expectedPageResource = newAssessorCreatedInvitePageResource() .withContent(expectedAssessorCreatedInviteResources) .withNumber(page) .withTotalElements(200L) .withTotalPages(10) .withSize(pageSize) .build(); Pageable pageable = PageRequest.of(page, pageSize, new Sort(ASC, "email")); when(reviewInviteServiceMock.getCreatedInvites(COMPETITION_ID, pageable)).thenReturn(serviceSuccess(expectedPageResource)); mockMvc.perform(get("/assessment-panel-invite/get-created-invites/{competitionId}", COMPETITION_ID) .param("page", String.valueOf(page)) .param("size", String.valueOf(pageSize)) .param("sort", "email,ASC")) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedPageResource))); verify(reviewInviteServiceMock, only()).getCreatedInvites(COMPETITION_ID, pageable); }
@Test public void getCreatedInvites_defaultParameters() throws Exception { int page = 0; int pageSize = 20; List<AssessorCreatedInviteResource> expectedAssessorCreatedInviteResources = newAssessorCreatedInviteResource() .build(2); AssessorCreatedInvitePageResource expectedPageResource = newAssessorCreatedInvitePageResource() .withContent(expectedAssessorCreatedInviteResources) .withNumber(page) .withTotalElements(200L) .withTotalPages(10) .withSize(pageSize) .build(); Pageable pageable = PageRequest.of(page, pageSize, new Sort(ASC, "name")); when(reviewInviteServiceMock.getCreatedInvites(COMPETITION_ID, pageable)).thenReturn(serviceSuccess(expectedPageResource)); mockMvc.perform(get("/assessment-panel-invite/get-created-invites/{competitionId}", COMPETITION_ID)) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedPageResource))); verify(reviewInviteServiceMock, only()).getCreatedInvites(COMPETITION_ID, pageable); } |
ReviewInviteController { @PostMapping("/invite-users") public RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites) { return reviewInviteService.inviteUsers(existingUserStagedInvites.getInvites()).toPostWithBodyResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<ReviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping("/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping( "/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<ReviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void inviteUsers() throws Exception { List<ExistingUserStagedInviteResource> existingUserStagedInvites = newExistingUserStagedInviteResource() .withUserId(1L, 2L) .withCompetitionId(1L) .build(2); ExistingUserStagedInviteListResource existingUserStagedInviteList = newExistingUserStagedInviteListResource() .withInvites(existingUserStagedInvites) .build(); when(reviewInviteServiceMock.inviteUsers(existingUserStagedInvites)).thenReturn(serviceSuccess()); mockMvc.perform(post("/assessment-panel-invite/invite-users") .contentType(MediaType.APPLICATION_JSON) .content(toJson(existingUserStagedInviteList))) .andExpect(status().isOk()); verify(reviewInviteServiceMock, only()).inviteUsers(existingUserStagedInvites); } |
ReviewInviteController { @PostMapping("/send-all-invites/{competitionId}") public RestResult<Void> sendAllInvites(@PathVariable long competitionId, @RequestBody AssessorInviteSendResource assessorInviteSendResource) { return reviewInviteService.sendAllInvites(competitionId, assessorInviteSendResource).toPostResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<ReviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping("/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping( "/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<ReviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void sendAllInvites() throws Exception { AssessorInviteSendResource assessorInviteSendResource = newAssessorInviteSendResource() .withSubject("subject") .withContent("content") .build(); when(reviewInviteServiceMock.sendAllInvites(COMPETITION_ID, assessorInviteSendResource)).thenReturn(serviceSuccess()); mockMvc.perform(post("/assessment-panel-invite/send-all-invites/{competitionId}", COMPETITION_ID) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(assessorInviteSendResource))) .andExpect(status().isOk()); verify(reviewInviteServiceMock).sendAllInvites(COMPETITION_ID, assessorInviteSendResource); } |
ReviewInviteController { @GetMapping("/get-all-invites-to-send/{competitionId}") public RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId) { return reviewInviteService.getAllInvitesToSend(competitionId).toGetResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<ReviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping("/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping( "/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<ReviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void getAllInvitesToSend() throws Exception { AssessorInvitesToSendResource resource = newAssessorInvitesToSendResource().build(); when(reviewInviteServiceMock.getAllInvitesToSend(COMPETITION_ID)).thenReturn(serviceSuccess(resource)); mockMvc.perform(get("/assessment-panel-invite/get-all-invites-to-send/{competitionId}", COMPETITION_ID).contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()); verify(reviewInviteServiceMock, only()).getAllInvitesToSend(COMPETITION_ID); } |
ReviewInviteController { @GetMapping("/get-all-invites-by-user/{userId}") public RestResult<List<ReviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId) { return reviewInviteService.getAllInvitesByUser(userId).toGetResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<ReviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping("/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping( "/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<ReviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void getAllInvitesByUser() throws Exception { final long USER_ID = 12L; ReviewInviteResource invite = newReviewInviteResource() .withCompetitionId(1L) .withCompetitionName("Juggling craziness") .withInviteHash("") .withStatus(InviteStatus.SENT) .build(); ReviewParticipantResource reviewParticipantResource = newReviewParticipantResource() .withStatus(PENDING) .withInvite(invite) .build(); when(reviewInviteServiceMock.getAllInvitesByUser(USER_ID)).thenReturn(serviceSuccess(singletonList(reviewParticipantResource))); mockMvc.perform(get("/assessment-panel-invite/get-all-invites-by-user/{user_id}", USER_ID)) .andExpect(status().isOk()); } |
ReviewInviteController { @GetMapping("/get-all-invites-to-resend/{competitionId}") public RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId, @RequestParam List<Long> inviteIds) { return reviewInviteService.getAllInvitesToResend(competitionId, inviteIds).toGetResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<ReviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping("/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping( "/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<ReviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void getAllInvitesToResend() throws Exception { AssessorInvitesToSendResource resource = newAssessorInvitesToSendResource().build(); List<Long> inviteIds = asList(1L, 2L); when(reviewInviteServiceMock.getAllInvitesToResend(COMPETITION_ID, inviteIds)).thenReturn(serviceSuccess(resource)); mockMvc.perform(get("/assessment-panel-invite/get-all-invites-to-resend/{competitionId}", COMPETITION_ID).contentType(MediaType.APPLICATION_JSON) .param("inviteIds", simpleJoiner(inviteIds, ","))) .andExpect(status().isOk()); verify(reviewInviteServiceMock, only()).getAllInvitesToResend(COMPETITION_ID, inviteIds); } |
ReviewInviteController { @PostMapping("/resend-invites") public RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds, @RequestBody AssessorInviteSendResource assessorInviteSendResource) { return reviewInviteService.resendInvites(inviteIds, assessorInviteSendResource).toPostWithBodyResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<ReviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping("/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping( "/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<ReviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void resendInvites() throws Exception { List<Long> inviteIds = asList(1L, 2L); AssessorInviteSendResource assessorInviteSendResource = newAssessorInviteSendResource() .withSubject("subject") .withContent("content") .build(); when(reviewInviteServiceMock.resendInvites(inviteIds, assessorInviteSendResource)).thenReturn(serviceSuccess()); mockMvc.perform(post("/assessment-panel-invite/resend-invites") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(assessorInviteSendResource)) .param("inviteIds", simpleJoiner(inviteIds, ","))) .andExpect(status().isOk()); verify(reviewInviteServiceMock).resendInvites(inviteIds, assessorInviteSendResource); } |
ReviewInviteController { @GetMapping( "/get-invitation-overview/{competitionId}") public RestResult<AssessorInviteOverviewPageResource> getInvitationOverview( @PathVariable long competitionId, @RequestParam List<ParticipantStatus> statuses, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable) { return reviewInviteService.getInvitationOverview(competitionId, pageable, statuses).toGetResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<ReviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping("/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping( "/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<ReviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void getInvitationOverview() throws Exception { long competitionId = 1L; int page = 2; int size = 10; List<ParticipantStatus> status = Collections.singletonList(ACCEPTED); AssessorInviteOverviewPageResource expectedPageResource = newAssessorInviteOverviewPageResource() .withContent(newAssessorInviteOverviewResource().build(2)) .build(); Pageable pageable = PageRequest.of(page, size, new Sort(Sort.Direction.ASC, "invite.email")); when(reviewInviteServiceMock.getInvitationOverview(competitionId, pageable, status)) .thenReturn(serviceSuccess(expectedPageResource)); mockMvc.perform(get("/assessment-panel-invite/get-invitation-overview/{competitionId}", competitionId) .param("page", "2") .param("size", "10") .param("sort", "invite.email") .param("statuses", "ACCEPTED")) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedPageResource))); verify(reviewInviteServiceMock, only()).getInvitationOverview(competitionId, pageable, status); } |
ReviewInviteController { @DeleteMapping("/delete-invite") public RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId) { return reviewInviteService.deleteInvite(email, competitionId).toDeleteResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<ReviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping("/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping( "/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<ReviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void deleteInvite() throws Exception { String email = "[email protected]"; long competitionId = 1L; when(reviewInviteServiceMock.deleteInvite(email, competitionId)).thenReturn(serviceSuccess()); mockMvc.perform(delete("/assessment-panel-invite/delete-invite") .param("email", email) .param("competitionId", String.valueOf(competitionId))) .andExpect(status().isNoContent()); verify(reviewInviteServiceMock, only()).deleteInvite(email, competitionId); } |
ReviewInviteController { @DeleteMapping("/delete-all-invites") public RestResult<Void> deleteAllInvites(@RequestParam long competitionId) { return reviewInviteService.deleteAllInvites(competitionId).toDeleteResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId,
@RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds,
@RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors(
@PathVariable long competitionId,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping("/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<ReviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping("/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping( "/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview(
@PathVariable long competitionId,
@RequestParam List<ParticipantStatus> statuses,
@PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<ReviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); } | @Test public void deleteAllInvites() throws Exception { long competitionId = 1L; when(reviewInviteServiceMock.deleteAllInvites(competitionId)).thenReturn(serviceSuccess()); mockMvc.perform(delete("/assessment-panel-invite/delete-all-invites") .param("competitionId", String.valueOf(competitionId))) .andExpect(status().isNoContent()); verify(reviewInviteServiceMock).deleteAllInvites(competitionId); } |
ReviewController { @PostMapping("/assign-application/{applicationId}") public RestResult<Void> assignApplication(@PathVariable long applicationId) { return reviewService.assignApplicationToPanel(applicationId).toPostResponse(); } @PostMapping("/assign-application/{applicationId}") RestResult<Void> assignApplication(@PathVariable long applicationId); @PostMapping("/unassign-application/{applicationId}") RestResult<Void> unAssignApplication(@PathVariable long applicationId); @PostMapping("/notify-assessors/{competitionId}") RestResult<Void> notifyAssessors(@PathVariable("competitionId") long competitionId); @GetMapping("/notify-assessors/{competitionId}") RestResult<Boolean> isPendingReviewNotifications(@PathVariable("competitionId") long competitionId); @GetMapping("/user/{userId}/competition/{competitionId}") RestResult<List<ReviewResource>> getReviews(
@PathVariable("userId") long userId,
@PathVariable("competitionId") long competitionId); @GetMapping("/review/{id}") RestResult<ReviewResource> getReview(@PathVariable("id") long id); @PutMapping("/review/{id}/accept") RestResult<Void> acceptInvitation(@PathVariable("id") long id); @PutMapping("/review/{id}/reject") RestResult<Void> rejectInvitation(@PathVariable("id") long id,
@RequestBody @Valid ReviewRejectOutcomeResource reviewRejectOutcomeResource); } | @Test public void assignApplication() throws Exception { when(reviewServiceMock.assignApplicationToPanel(applicationId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/assessmentpanel/assign-application/{applicationId}", applicationId)) .andExpect(status().isOk()); verify(reviewServiceMock, only()).assignApplicationToPanel(applicationId); } |
ReviewController { @PostMapping("/unassign-application/{applicationId}") public RestResult<Void> unAssignApplication(@PathVariable long applicationId) { return reviewService.unassignApplicationFromPanel(applicationId).toPostResponse(); } @PostMapping("/assign-application/{applicationId}") RestResult<Void> assignApplication(@PathVariable long applicationId); @PostMapping("/unassign-application/{applicationId}") RestResult<Void> unAssignApplication(@PathVariable long applicationId); @PostMapping("/notify-assessors/{competitionId}") RestResult<Void> notifyAssessors(@PathVariable("competitionId") long competitionId); @GetMapping("/notify-assessors/{competitionId}") RestResult<Boolean> isPendingReviewNotifications(@PathVariable("competitionId") long competitionId); @GetMapping("/user/{userId}/competition/{competitionId}") RestResult<List<ReviewResource>> getReviews(
@PathVariable("userId") long userId,
@PathVariable("competitionId") long competitionId); @GetMapping("/review/{id}") RestResult<ReviewResource> getReview(@PathVariable("id") long id); @PutMapping("/review/{id}/accept") RestResult<Void> acceptInvitation(@PathVariable("id") long id); @PutMapping("/review/{id}/reject") RestResult<Void> rejectInvitation(@PathVariable("id") long id,
@RequestBody @Valid ReviewRejectOutcomeResource reviewRejectOutcomeResource); } | @Test public void unAssignApplication() throws Exception { when(reviewServiceMock.unassignApplicationFromPanel(applicationId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/assessmentpanel/unassign-application/{applicationId}", applicationId)) .andExpect(status().isOk()); verify(reviewServiceMock, only()).unassignApplicationFromPanel(applicationId); } |
ReviewController { @PostMapping("/notify-assessors/{competitionId}") public RestResult<Void> notifyAssessors(@PathVariable("competitionId") long competitionId) { return reviewService.createAndNotifyReviews(competitionId).toPostResponse(); } @PostMapping("/assign-application/{applicationId}") RestResult<Void> assignApplication(@PathVariable long applicationId); @PostMapping("/unassign-application/{applicationId}") RestResult<Void> unAssignApplication(@PathVariable long applicationId); @PostMapping("/notify-assessors/{competitionId}") RestResult<Void> notifyAssessors(@PathVariable("competitionId") long competitionId); @GetMapping("/notify-assessors/{competitionId}") RestResult<Boolean> isPendingReviewNotifications(@PathVariable("competitionId") long competitionId); @GetMapping("/user/{userId}/competition/{competitionId}") RestResult<List<ReviewResource>> getReviews(
@PathVariable("userId") long userId,
@PathVariable("competitionId") long competitionId); @GetMapping("/review/{id}") RestResult<ReviewResource> getReview(@PathVariable("id") long id); @PutMapping("/review/{id}/accept") RestResult<Void> acceptInvitation(@PathVariable("id") long id); @PutMapping("/review/{id}/reject") RestResult<Void> rejectInvitation(@PathVariable("id") long id,
@RequestBody @Valid ReviewRejectOutcomeResource reviewRejectOutcomeResource); } | @Test public void notifyAssessors() throws Exception { when(reviewServiceMock.createAndNotifyReviews(competitionId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/assessmentpanel/notify-assessors/{competitionId}", competitionId)) .andExpect(status().isOk()); verify(reviewServiceMock, only()).createAndNotifyReviews(competitionId); } |
ReviewController { @GetMapping("/notify-assessors/{competitionId}") public RestResult<Boolean> isPendingReviewNotifications(@PathVariable("competitionId") long competitionId) { return reviewService.isPendingReviewNotifications(competitionId).toGetResponse(); } @PostMapping("/assign-application/{applicationId}") RestResult<Void> assignApplication(@PathVariable long applicationId); @PostMapping("/unassign-application/{applicationId}") RestResult<Void> unAssignApplication(@PathVariable long applicationId); @PostMapping("/notify-assessors/{competitionId}") RestResult<Void> notifyAssessors(@PathVariable("competitionId") long competitionId); @GetMapping("/notify-assessors/{competitionId}") RestResult<Boolean> isPendingReviewNotifications(@PathVariable("competitionId") long competitionId); @GetMapping("/user/{userId}/competition/{competitionId}") RestResult<List<ReviewResource>> getReviews(
@PathVariable("userId") long userId,
@PathVariable("competitionId") long competitionId); @GetMapping("/review/{id}") RestResult<ReviewResource> getReview(@PathVariable("id") long id); @PutMapping("/review/{id}/accept") RestResult<Void> acceptInvitation(@PathVariable("id") long id); @PutMapping("/review/{id}/reject") RestResult<Void> rejectInvitation(@PathVariable("id") long id,
@RequestBody @Valid ReviewRejectOutcomeResource reviewRejectOutcomeResource); } | @Test public void isPendingReviewNotifications() throws Exception { Boolean expected = true; when(reviewServiceMock.isPendingReviewNotifications(competitionId)).thenReturn(serviceSuccess(expected)); mockMvc.perform(get("/assessmentpanel/notify-assessors/{competitionId}", competitionId)) .andExpect(status().isOk()) .andExpect(content().string(objectMapper.writeValueAsString(expected))); verify(reviewServiceMock, only()).isPendingReviewNotifications(competitionId); } |
UserPermissionRules { @PermissionRule(value = "READ", description = "A user can read their own affiliations") public boolean usersCanViewTheirOwnAffiliations(AffiliationResource affiliation, UserResource user) { return user.getId().equals(affiliation.getUser()); } @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "An internal user can invite a monitoring officer and create the pending user associated.") boolean compAdminProjectFinanceCanCreateMonitoringOfficer(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserRegistrationResource userToCreate, UserResource user); @PermissionRule(value = "VERIFY", description = "A System Registration User can send a new User a verification link by e-mail") boolean systemRegistrationUserCanSendUserVerificationEmail(UserResource userToSendVerificationEmail, UserResource user); @PermissionRule(value = "READ", description = "Any user can view themselves") boolean anyUserCanViewThemselves(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Internal users can view everyone") boolean internalUsersCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can view users in competitions they are assigned to") boolean stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Competition finance users can view users in competitions they are assigned to") boolean competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can view users in projects they are assigned to") boolean monitoringOfficersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ_USER_ORGANISATION", description = "Internal support users can view all users and associated organisations") boolean internalUsersCanViewUserOrganisation(UserOrganisationResource userToView, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "IFS admins can update all users email addresses") boolean ifsAdminCanUpdateAllEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "Support users can update external users email addresses ") boolean supportCanUpdateExternalUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "System Maintenance update all users email addresses") boolean systemMaintenanceUserCanUpdateUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ_INTERNAL", description = "Administrators can view internal users") boolean internalUsersCanViewEveryone(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Support users and administrators can view external users") boolean supportUsersCanViewExternalUsers(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "The System Registration user can view everyone") boolean systemRegistrationUserCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Comp admins and project finance can view assessors") boolean compAdminAndProjectFinanceCanViewAssessors(UserPageResource usersToView, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewOtherConsortiumMembers(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewConsortiumUsersOnApplicationsTheyAreAssessing(UserResource userToView, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "A User should be able to change their own password") boolean usersCanChangeTheirOwnPassword(UserResource userToUpdate, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "The System Registration user should be able to change passwords on behalf of other Users") boolean systemRegistrationUserCanChangePasswordsForUsers(UserResource userToUpdate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A System Registration User can activate Users") boolean systemRegistrationUserCanActivateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "UPDATE", description = "A User can update their own profile") boolean usersCanUpdateTheirOwnProfiles(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE", description = "An admin user can update user details to assign monitoring officers") boolean adminsCanUpdateUserDetails(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile skills") boolean usersCanViewTheirOwnProfileSkills(ProfileSkillsResource profileSkills, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile agreement") boolean usersCanViewTheirOwnProfileAgreement(ProfileAgreementResource profileAgreementResource, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own affiliations") boolean usersCanViewTheirOwnAffiliations(AffiliationResource affiliation, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A user can read their own profile") boolean usersCanViewTheirOwnProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A ifs admin user can read any user's profile") boolean ifsAdminCanViewAnyUsersProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as Comp Admin and Exec can read the user's profile status") boolean usersAndCompAdminCanViewProfileStatus(UserProfileStatusResource profileStatus, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own role") boolean usersCanViewTheirOwnProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the process role of others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewTheProcessRolesOfOtherConsortiumMembers(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Project managers and partners can view the process role for the same organisation") boolean projectPartnersCanViewTheProcessRolesWithinSameApplication(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as internal users can read the user's process role") boolean usersAndInternalUsersCanViewProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the process roles of members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewTheProcessRolesOfConsortiumUsersOnApplicationsTheyAreAssessing(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "CHECK_USER_APPLICATION", description = "The user can check if they have an application for the competition") boolean userCanCheckTheyHaveApplicationForCompetition(UserResource userToCheck, UserResource user); @PermissionRule(value = "EDIT_INTERNAL_USER", description = "Only an IFS Administrator can edit an internal user") boolean ifsAdminCanEditInternalUser(final UserResource userToEdit, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "IFS Administrator can deactivate Users") boolean ifsAdminCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "A Support user can deactivate external Users") boolean supportUserCanDeactivateExternalUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "System Maintenance can deactivate Users") boolean systemMaintenanceUserCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "IFS Administrator can reactivate Users") boolean ifsAdminCanReactivateUsers(UserResource userToReactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A Support user can reactivate external Users") boolean supportUserCanReactivateExternalUsers(UserResource userToActivate, UserResource user); @PermissionRule(value = "AGREE_TERMS", description = "A user can accept the site terms and conditions") boolean usersCanAgreeSiteTermsAndConditions(UserResource userToUpdate, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An assessor can request applicant role") boolean assessorCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant monitoring officer role") boolean isGrantingMonitoringOfficerRoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant a KTA role") boolean isGrantingKTARoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An stakeholder can request applicant role") boolean stakeholderCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An monitoring officer can request applicant role") boolean monitoringOfficerCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "CAN_VIEW_OWN_DASHBOARD", description = "User is requesting own dashboard") boolean isViewingOwnDashboard(UserResource userToView, UserResource user); } | @Test public void usersCanViewTheirOwnAffiliations() { UserResource user = newUserResource().build(); AffiliationResource affiliation = newAffiliationResource() .withUser(user.getId()) .build(); assertTrue(rules.usersCanViewTheirOwnAffiliations(affiliation, user)); }
@Test public void usersCanViewTheirOwnAffiliationsButAttemptingToViewAnotherUsersAffiliation() { UserResource user = newUserResource().build(); UserResource anotherUser = newUserResource().build(); AffiliationResource affiliation = newAffiliationResource() .withUser(user.getId()) .build(); assertFalse(rules.usersCanViewTheirOwnAffiliations(affiliation, anotherUser)); } |
ReviewController { @GetMapping("/user/{userId}/competition/{competitionId}") public RestResult<List<ReviewResource>> getReviews( @PathVariable("userId") long userId, @PathVariable("competitionId") long competitionId) { return reviewService.getReviews(userId, competitionId).toGetResponse(); } @PostMapping("/assign-application/{applicationId}") RestResult<Void> assignApplication(@PathVariable long applicationId); @PostMapping("/unassign-application/{applicationId}") RestResult<Void> unAssignApplication(@PathVariable long applicationId); @PostMapping("/notify-assessors/{competitionId}") RestResult<Void> notifyAssessors(@PathVariable("competitionId") long competitionId); @GetMapping("/notify-assessors/{competitionId}") RestResult<Boolean> isPendingReviewNotifications(@PathVariable("competitionId") long competitionId); @GetMapping("/user/{userId}/competition/{competitionId}") RestResult<List<ReviewResource>> getReviews(
@PathVariable("userId") long userId,
@PathVariable("competitionId") long competitionId); @GetMapping("/review/{id}") RestResult<ReviewResource> getReview(@PathVariable("id") long id); @PutMapping("/review/{id}/accept") RestResult<Void> acceptInvitation(@PathVariable("id") long id); @PutMapping("/review/{id}/reject") RestResult<Void> rejectInvitation(@PathVariable("id") long id,
@RequestBody @Valid ReviewRejectOutcomeResource reviewRejectOutcomeResource); } | @Test public void getAssessmentReviews() throws Exception { List<ReviewResource> assessmentReviews = newReviewResource().build(2); when(reviewServiceMock.getReviews(userId, competitionId)).thenReturn(serviceSuccess(assessmentReviews)); mockMvc.perform(get("/assessmentpanel/user/{userId}/competition/{competitionId}", userId, competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(assessmentReviews))); verify(reviewServiceMock, only()).getReviews(userId, competitionId); } |
ReviewController { @PutMapping("/review/{id}/accept") public RestResult<Void> acceptInvitation(@PathVariable("id") long id) { return reviewService.acceptReview(id).toPutResponse(); } @PostMapping("/assign-application/{applicationId}") RestResult<Void> assignApplication(@PathVariable long applicationId); @PostMapping("/unassign-application/{applicationId}") RestResult<Void> unAssignApplication(@PathVariable long applicationId); @PostMapping("/notify-assessors/{competitionId}") RestResult<Void> notifyAssessors(@PathVariable("competitionId") long competitionId); @GetMapping("/notify-assessors/{competitionId}") RestResult<Boolean> isPendingReviewNotifications(@PathVariable("competitionId") long competitionId); @GetMapping("/user/{userId}/competition/{competitionId}") RestResult<List<ReviewResource>> getReviews(
@PathVariable("userId") long userId,
@PathVariable("competitionId") long competitionId); @GetMapping("/review/{id}") RestResult<ReviewResource> getReview(@PathVariable("id") long id); @PutMapping("/review/{id}/accept") RestResult<Void> acceptInvitation(@PathVariable("id") long id); @PutMapping("/review/{id}/reject") RestResult<Void> rejectInvitation(@PathVariable("id") long id,
@RequestBody @Valid ReviewRejectOutcomeResource reviewRejectOutcomeResource); } | @Test public void acceptInvitation() throws Exception { long assessmentReviewId = 1L; when(reviewServiceMock.acceptReview(assessmentReviewId)).thenReturn(serviceSuccess()); mockMvc.perform(put("/assessmentpanel/review/{id}/accept", assessmentReviewId)) .andExpect(status().isOk()); verify(reviewServiceMock, only()).acceptReview(assessmentReviewId); } |
ReviewController { @PutMapping("/review/{id}/reject") public RestResult<Void> rejectInvitation(@PathVariable("id") long id, @RequestBody @Valid ReviewRejectOutcomeResource reviewRejectOutcomeResource) { return reviewService.rejectReview(id, reviewRejectOutcomeResource).toPutResponse(); } @PostMapping("/assign-application/{applicationId}") RestResult<Void> assignApplication(@PathVariable long applicationId); @PostMapping("/unassign-application/{applicationId}") RestResult<Void> unAssignApplication(@PathVariable long applicationId); @PostMapping("/notify-assessors/{competitionId}") RestResult<Void> notifyAssessors(@PathVariable("competitionId") long competitionId); @GetMapping("/notify-assessors/{competitionId}") RestResult<Boolean> isPendingReviewNotifications(@PathVariable("competitionId") long competitionId); @GetMapping("/user/{userId}/competition/{competitionId}") RestResult<List<ReviewResource>> getReviews(
@PathVariable("userId") long userId,
@PathVariable("competitionId") long competitionId); @GetMapping("/review/{id}") RestResult<ReviewResource> getReview(@PathVariable("id") long id); @PutMapping("/review/{id}/accept") RestResult<Void> acceptInvitation(@PathVariable("id") long id); @PutMapping("/review/{id}/reject") RestResult<Void> rejectInvitation(@PathVariable("id") long id,
@RequestBody @Valid ReviewRejectOutcomeResource reviewRejectOutcomeResource); } | @Test public void rejectInvitation() throws Exception { long assessmentReviewId = 1L; String rejectComment = String.join(" ", nCopies(100, "comment")); ReviewRejectOutcomeResource reviewRejectOutcomeResource = newReviewRejectOutcomeResource() .withReason(rejectComment) .build(); when(reviewServiceMock.rejectReview(assessmentReviewId, reviewRejectOutcomeResource)).thenReturn(serviceSuccess()); mockMvc.perform(put("/assessmentpanel/review/{id}/reject", assessmentReviewId) .contentType(APPLICATION_JSON) .content(toJson(reviewRejectOutcomeResource))) .andExpect(status().isOk()); verify(reviewServiceMock, only()).rejectReview(assessmentReviewId, reviewRejectOutcomeResource); } |
ReviewController { @GetMapping("/review/{id}") public RestResult<ReviewResource> getReview(@PathVariable("id") long id) { return reviewService.getReview(id).toGetResponse(); } @PostMapping("/assign-application/{applicationId}") RestResult<Void> assignApplication(@PathVariable long applicationId); @PostMapping("/unassign-application/{applicationId}") RestResult<Void> unAssignApplication(@PathVariable long applicationId); @PostMapping("/notify-assessors/{competitionId}") RestResult<Void> notifyAssessors(@PathVariable("competitionId") long competitionId); @GetMapping("/notify-assessors/{competitionId}") RestResult<Boolean> isPendingReviewNotifications(@PathVariable("competitionId") long competitionId); @GetMapping("/user/{userId}/competition/{competitionId}") RestResult<List<ReviewResource>> getReviews(
@PathVariable("userId") long userId,
@PathVariable("competitionId") long competitionId); @GetMapping("/review/{id}") RestResult<ReviewResource> getReview(@PathVariable("id") long id); @PutMapping("/review/{id}/accept") RestResult<Void> acceptInvitation(@PathVariable("id") long id); @PutMapping("/review/{id}/reject") RestResult<Void> rejectInvitation(@PathVariable("id") long id,
@RequestBody @Valid ReviewRejectOutcomeResource reviewRejectOutcomeResource); } | @Test public void getReview() throws Exception { ReviewResource reviewResource = newReviewResource().build(); when(reviewServiceMock.getReview(reviewResource.getId())).thenReturn(serviceSuccess(reviewResource)); mockMvc.perform(get("/assessmentpanel/review/{id}", reviewResource.getId())) .andExpect(status().isOk()); verify(reviewServiceMock, only()).getReview(reviewResource.getId()); } |
ReviewServiceImpl implements ReviewService { @Override public ServiceResult<Void> assignApplicationToPanel(long applicationId) { return getApplication(applicationId) .andOnSuccessReturnVoid(application -> application.setInAssessmentReviewPanel(true)); } @Override ServiceResult<Void> assignApplicationToPanel(long applicationId); @Override ServiceResult<Void> unassignApplicationFromPanel(long applicationId); @Override ServiceResult<Void> createAndNotifyReviews(long competitionId); @Override ServiceResult<Boolean> isPendingReviewNotifications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<List<ReviewResource>> getReviews(long userId, long competitionId); @Override ServiceResult<Void> acceptReview(long assessmentReviewId); @Override ServiceResult<Void> rejectReview(long assessmentReviewId,
ReviewRejectOutcomeResource assessmentReviewRejectOutcome); @Override @Transactional(readOnly = true) ServiceResult<ReviewResource> getReview(long assessmentReviewId); } | @Test public void assignApplicationsToPanel() { when(applicationRepositoryMock.findById(applicationId)).thenReturn(Optional.of(application)); ServiceResult<Void> result = service.assignApplicationToPanel(applicationId); assertTrue(result.isSuccess()); assertTrue(application.isInAssessmentReviewPanel()); verify(applicationRepositoryMock).findById(applicationId); verifyNoMoreInteractions(applicationRepositoryMock); } |
ReviewServiceImpl implements ReviewService { @Override public ServiceResult<Void> unassignApplicationFromPanel(long applicationId) { return getApplication(applicationId) .andOnSuccess(this::unassignApplicationFromPanel) .andOnSuccessReturnVoid(this::withdrawAssessmentReviewsForApplication); } @Override ServiceResult<Void> assignApplicationToPanel(long applicationId); @Override ServiceResult<Void> unassignApplicationFromPanel(long applicationId); @Override ServiceResult<Void> createAndNotifyReviews(long competitionId); @Override ServiceResult<Boolean> isPendingReviewNotifications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<List<ReviewResource>> getReviews(long userId, long competitionId); @Override ServiceResult<Void> acceptReview(long assessmentReviewId); @Override ServiceResult<Void> rejectReview(long assessmentReviewId,
ReviewRejectOutcomeResource assessmentReviewRejectOutcome); @Override @Transactional(readOnly = true) ServiceResult<ReviewResource> getReview(long assessmentReviewId); } | @Test public void unAssignApplicationsFromPanel() { when(applicationRepositoryMock.findById(applicationId)).thenReturn(Optional.of(application)); when(reviewRepositoryMock .findByTargetIdAndActivityStateNot(applicationId, ReviewState.WITHDRAWN)) .thenReturn(emptyList()); ServiceResult<Void> result = service.unassignApplicationFromPanel(applicationId); assertTrue(result.isSuccess()); assertFalse(application.isInAssessmentReviewPanel()); verify(applicationRepositoryMock).findById(applicationId); verify(reviewRepositoryMock).findByTargetIdAndActivityStateNot(applicationId, ReviewState.WITHDRAWN); verifyNoMoreInteractions(applicationRepositoryMock, reviewRepositoryMock); }
@Test public void unAssignApplicationsFromPanel_existingReviews() { List<Review> reviews = newReview().withTarget(application).withState(ReviewState.WITHDRAWN).build(2); when(applicationRepositoryMock.findById(applicationId)).thenReturn(Optional.of(application)); when(reviewRepositoryMock .findByTargetIdAndActivityStateNot(applicationId, ReviewState.WITHDRAWN)) .thenReturn(reviews); ServiceResult<Void> result = service.unassignApplicationFromPanel(applicationId); assertTrue(result.isSuccess()); assertFalse(application.isInAssessmentReviewPanel()); reviews.forEach(a -> assertEquals(ReviewState.WITHDRAWN, a.getProcessState())); verify(applicationRepositoryMock).findById(applicationId); verifyNoMoreInteractions(applicationRepositoryMock); } |
ReviewServiceImpl implements ReviewService { @Override public ServiceResult<Void> createAndNotifyReviews(long competitionId) { getAllAssessorsOnPanel(competitionId) .forEach(assessor -> getAllApplicationsOnPanel(competitionId) .forEach(application -> createAssessmentReview(assessor, application))); return notifyAllCreated(competitionId); } @Override ServiceResult<Void> assignApplicationToPanel(long applicationId); @Override ServiceResult<Void> unassignApplicationFromPanel(long applicationId); @Override ServiceResult<Void> createAndNotifyReviews(long competitionId); @Override ServiceResult<Boolean> isPendingReviewNotifications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<List<ReviewResource>> getReviews(long userId, long competitionId); @Override ServiceResult<Void> acceptReview(long assessmentReviewId); @Override ServiceResult<Void> rejectReview(long assessmentReviewId,
ReviewRejectOutcomeResource assessmentReviewRejectOutcome); @Override @Transactional(readOnly = true) ServiceResult<ReviewResource> getReview(long assessmentReviewId); } | @Test public void createAndNotifyReviews() { String competitionName = "Competition name"; ZonedDateTime panelDate = ZonedDateTime.parse("2017-12-18T12:00:00+00:00"); User assessor = newUser() .withEmailAddress("[email protected]") .withFirstName("Tom") .withLastName("Baldwin") .build(); Competition competition = newCompetition() .withId(competitionId) .withName(competitionName) .withMilestones(singletonList(newMilestone() .withType(MilestoneType.ASSESSMENT_PANEL) .withDate(panelDate) .build()) ) .build(); List<ReviewParticipant> reviewParticipants = newReviewParticipant() .withUser(assessor) .build(1); List<Application> applications = newApplication() .withCompetition(competition) .build(1); List<ProcessRole> processRoles = newProcessRole() .withUser(assessor) .withApplication(applications.toArray(new Application[1])) .build(1); Review review = new Review(applications.get(0), reviewParticipants.get(0)); review.setProcessState(CREATED); when(reviewParticipantRepositoryMock .getPanelAssessorsByCompetitionAndStatusContains(competitionId, singletonList(ParticipantStatus.ACCEPTED))) .thenReturn(reviewParticipants); when(applicationRepositoryMock .findByCompetitionIdAndInAssessmentReviewPanelTrueAndApplicationProcessActivityState(competitionId, ApplicationState.SUBMITTED.SUBMITTED)) .thenReturn(applications); when(reviewRepositoryMock.existsByParticipantUserAndTargetAndActivityStateNot(assessor, application, ReviewState.WITHDRAWN)) .thenReturn(true); when(processRoleRepositoryMock.save(isA(ProcessRole.class))).thenReturn(processRoles.get(0)); when(reviewRepositoryMock .findByTargetCompetitionIdAndActivityState(competitionId, CREATED)) .thenReturn(asList(review)); when(reviewWorkflowHandlerMock.notifyInvitation(isA(Review.class))).thenReturn(true); Notification expectedNotification = createLambdaMatcher(n -> { Map<String, Object> globalArguments = n.getGlobalArguments(); assertEquals(assessor.getEmail(), n.getTo().get(0).getEmailAddress()); assertEquals(globalArguments.get("subject"), "Applications ready for review"); assertEquals(globalArguments.get("name"), "Tom Baldwin"); assertEquals(globalArguments.get("competitionName"), competitionName); assertEquals(globalArguments.get("panelDate"), panelDate.format(INVITE_DATE_FORMAT)); assertEquals(globalArguments.get("ifsUrl"), webBaseUrl); }); when(notificationServiceMock.sendNotificationWithFlush(expectedNotification, eq(EMAIL))).thenReturn(serviceSuccess()); service.createAndNotifyReviews(competitionId).getSuccess(); InOrder inOrder = inOrder(reviewParticipantRepositoryMock, applicationRepositoryMock, reviewRepositoryMock, reviewRepositoryMock, reviewRepositoryMock, reviewWorkflowHandlerMock, notificationServiceMock, processRoleRepositoryMock); inOrder.verify(reviewParticipantRepositoryMock) .getPanelAssessorsByCompetitionAndStatusContains(competitionId, singletonList(ParticipantStatus.ACCEPTED)); inOrder.verify(applicationRepositoryMock) .findByCompetitionIdAndInAssessmentReviewPanelTrueAndApplicationProcessActivityState(competitionId, ApplicationState.SUBMITTED); inOrder.verify(reviewRepositoryMock) .existsByParticipantUserAndTargetAndActivityStateNot(assessor, applications.get(0), ReviewState.WITHDRAWN); inOrder.verify(reviewRepositoryMock) .save(review); inOrder.verify(reviewRepositoryMock) .findByTargetCompetitionIdAndActivityState(competitionId, CREATED); inOrder.verify(reviewWorkflowHandlerMock) .notifyInvitation(review); inOrder.verify(notificationServiceMock) .sendNotificationWithFlush(isA(Notification.class), eq(EMAIL)); inOrder.verifyNoMoreInteractions(); } |
ReviewServiceImpl implements ReviewService { @Override public ServiceResult<Boolean> isPendingReviewNotifications(long competitionId) { return serviceSuccess(reviewRepository.notifiable(competitionId)); } @Override ServiceResult<Void> assignApplicationToPanel(long applicationId); @Override ServiceResult<Void> unassignApplicationFromPanel(long applicationId); @Override ServiceResult<Void> createAndNotifyReviews(long competitionId); @Override ServiceResult<Boolean> isPendingReviewNotifications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<List<ReviewResource>> getReviews(long userId, long competitionId); @Override ServiceResult<Void> acceptReview(long assessmentReviewId); @Override ServiceResult<Void> rejectReview(long assessmentReviewId,
ReviewRejectOutcomeResource assessmentReviewRejectOutcome); @Override @Transactional(readOnly = true) ServiceResult<ReviewResource> getReview(long assessmentReviewId); } | @Test public void isPendingReviewNotifications() { final boolean expectedPendingReviewNotifications = true; when(reviewRepositoryMock.notifiable(competitionId)).thenReturn(expectedPendingReviewNotifications); assertEquals(expectedPendingReviewNotifications, service.isPendingReviewNotifications(competitionId).getSuccess()); verify(reviewRepositoryMock, only()).notifiable(competitionId); }
@Test public void isPendingReviewNotifications_none() { final boolean expectedPendingReviewNotifications = false; when(reviewRepositoryMock.notifiable(competitionId)).thenReturn(expectedPendingReviewNotifications); assertEquals(expectedPendingReviewNotifications, service.isPendingReviewNotifications(competitionId).getSuccess()); verify(reviewRepositoryMock, only()).notifiable(competitionId); } |
ReviewServiceImpl implements ReviewService { @Override @Transactional(readOnly = true) public ServiceResult<List<ReviewResource>> getReviews(long userId, long competitionId) { List<Review> reviews = reviewRepository.findByParticipantUserIdAndTargetCompetitionIdOrderByActivityStateAscIdAsc(userId, competitionId); return serviceSuccess(simpleMap(reviews, reviewMapper::mapToResource)); } @Override ServiceResult<Void> assignApplicationToPanel(long applicationId); @Override ServiceResult<Void> unassignApplicationFromPanel(long applicationId); @Override ServiceResult<Void> createAndNotifyReviews(long competitionId); @Override ServiceResult<Boolean> isPendingReviewNotifications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<List<ReviewResource>> getReviews(long userId, long competitionId); @Override ServiceResult<Void> acceptReview(long assessmentReviewId); @Override ServiceResult<Void> rejectReview(long assessmentReviewId,
ReviewRejectOutcomeResource assessmentReviewRejectOutcome); @Override @Transactional(readOnly = true) ServiceResult<ReviewResource> getReview(long assessmentReviewId); } | @Test public void getAssessmentReviews() { List<Review> reviews = newReview().build(2); List<ReviewResource> reviewResources = newReviewResource().build(2); when(reviewRepositoryMock.findByParticipantUserIdAndTargetCompetitionIdOrderByActivityStateAscIdAsc(userId, competitionId)).thenReturn(reviews); when(reviewMapperMock.mapToResource(same(reviews.get(0)))).thenReturn(reviewResources.get(0)); when(reviewMapperMock.mapToResource(same(reviews.get(1)))).thenReturn(reviewResources.get(1)); assertEquals(reviewResources, service.getReviews(userId, competitionId).getSuccess()); InOrder inOrder = inOrder(reviewRepositoryMock, reviewMapperMock); inOrder.verify(reviewRepositoryMock).findByParticipantUserIdAndTargetCompetitionIdOrderByActivityStateAscIdAsc(userId, competitionId); inOrder.verify(reviewMapperMock).mapToResource(same(reviews.get(0))); inOrder.verify(reviewMapperMock).mapToResource(same(reviews.get(1))); } |
ReviewServiceImpl implements ReviewService { private ServiceResult<Void> acceptAssessmentReview(Review review) { if (!workflowHandler.acceptInvitation(review)) { return serviceFailure(ASSESSMENT_REVIEW_ACCEPT_FAILED); } return serviceSuccess(); } @Override ServiceResult<Void> assignApplicationToPanel(long applicationId); @Override ServiceResult<Void> unassignApplicationFromPanel(long applicationId); @Override ServiceResult<Void> createAndNotifyReviews(long competitionId); @Override ServiceResult<Boolean> isPendingReviewNotifications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<List<ReviewResource>> getReviews(long userId, long competitionId); @Override ServiceResult<Void> acceptReview(long assessmentReviewId); @Override ServiceResult<Void> rejectReview(long assessmentReviewId,
ReviewRejectOutcomeResource assessmentReviewRejectOutcome); @Override @Transactional(readOnly = true) ServiceResult<ReviewResource> getReview(long assessmentReviewId); } | @Test public void acceptAssessmentReview() { Review review = newReview().build(); when(reviewRepositoryMock.findById(review.getId())).thenReturn(Optional.of(review)); when(reviewWorkflowHandlerMock.acceptInvitation(review)).thenReturn(true); service.acceptReview(review.getId()).getSuccess(); InOrder inOrder = inOrder(reviewRepositoryMock, reviewWorkflowHandlerMock); inOrder.verify(reviewRepositoryMock).findById(review.getId()); inOrder.verify(reviewWorkflowHandlerMock).acceptInvitation(review); inOrder.verifyNoMoreInteractions(); } |
ReviewServiceImpl implements ReviewService { @Override public ServiceResult<Void> acceptReview(long assessmentReviewId) { return findAssessmentReview(assessmentReviewId).andOnSuccess(this::acceptAssessmentReview); } @Override ServiceResult<Void> assignApplicationToPanel(long applicationId); @Override ServiceResult<Void> unassignApplicationFromPanel(long applicationId); @Override ServiceResult<Void> createAndNotifyReviews(long competitionId); @Override ServiceResult<Boolean> isPendingReviewNotifications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<List<ReviewResource>> getReviews(long userId, long competitionId); @Override ServiceResult<Void> acceptReview(long assessmentReviewId); @Override ServiceResult<Void> rejectReview(long assessmentReviewId,
ReviewRejectOutcomeResource assessmentReviewRejectOutcome); @Override @Transactional(readOnly = true) ServiceResult<ReviewResource> getReview(long assessmentReviewId); } | @Test public void acceptAssessmentReview_notFound() { Review review = newReview().build(); ServiceResult<Void> serviceResult = service.acceptReview(review.getId()); assertTrue(serviceResult.isFailure()); assertEquals(GENERAL_NOT_FOUND.getErrorKey(), serviceResult.getErrors().get(0).getErrorKey()); InOrder inOrder = inOrder(reviewRepositoryMock, reviewWorkflowHandlerMock); inOrder.verify(reviewRepositoryMock).findById(review.getId()); inOrder.verifyNoMoreInteractions(); }
@Test public void acceptAssessmentReview_invalidState() { Review review = newReview().build(); when(reviewRepositoryMock.findById(review.getId())).thenReturn(Optional.of(review)); when(reviewWorkflowHandlerMock.acceptInvitation(review)).thenReturn(false); ServiceResult<Void> serviceResult = service.acceptReview(review.getId()); assertTrue(serviceResult.isFailure()); assertEquals(ASSESSMENT_REVIEW_ACCEPT_FAILED.getErrorKey(), serviceResult.getErrors().get(0).getErrorKey()); InOrder inOrder = inOrder(reviewRepositoryMock, reviewWorkflowHandlerMock); inOrder.verify(reviewRepositoryMock).findById(review.getId()); inOrder.verify(reviewWorkflowHandlerMock).acceptInvitation(review); inOrder.verifyNoMoreInteractions(); } |
ReviewServiceImpl implements ReviewService { private ServiceResult<Void> rejectAssessmentReview(Review review, ReviewRejectOutcome rejectOutcome) { if (!workflowHandler.rejectInvitation(review, rejectOutcome)) { return serviceFailure(ASSESSMENT_REVIEW_REJECT_FAILED); } return serviceSuccess(); } @Override ServiceResult<Void> assignApplicationToPanel(long applicationId); @Override ServiceResult<Void> unassignApplicationFromPanel(long applicationId); @Override ServiceResult<Void> createAndNotifyReviews(long competitionId); @Override ServiceResult<Boolean> isPendingReviewNotifications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<List<ReviewResource>> getReviews(long userId, long competitionId); @Override ServiceResult<Void> acceptReview(long assessmentReviewId); @Override ServiceResult<Void> rejectReview(long assessmentReviewId,
ReviewRejectOutcomeResource assessmentReviewRejectOutcome); @Override @Transactional(readOnly = true) ServiceResult<ReviewResource> getReview(long assessmentReviewId); } | @Test public void rejectAssessmentReview() { ReviewRejectOutcomeResource rejectOutcomeResource = newReviewRejectOutcomeResource().build(); Review review = newReview().build(); ReviewRejectOutcome reviewRejectOutcome = newReviewRejectOutcome().build(); when(reviewRepositoryMock.findById(review.getId())).thenReturn(Optional.of(review)); when(reviewWorkflowHandlerMock.rejectInvitation(review, reviewRejectOutcome)).thenReturn(true); when(reviewRejectOutcomeMapperMock.mapToDomain(rejectOutcomeResource)).thenReturn(reviewRejectOutcome); service.rejectReview(review.getId(), rejectOutcomeResource).getSuccess(); InOrder inOrder = inOrder(reviewRepositoryMock, reviewWorkflowHandlerMock, reviewRejectOutcomeMapperMock); inOrder.verify(reviewRepositoryMock).findById(review.getId()); inOrder.verify(reviewRejectOutcomeMapperMock).mapToDomain(rejectOutcomeResource); inOrder.verify(reviewWorkflowHandlerMock).rejectInvitation(review, reviewRejectOutcome); inOrder.verifyNoMoreInteractions(); } |
ReviewServiceImpl implements ReviewService { @Override public ServiceResult<Void> rejectReview(long assessmentReviewId, ReviewRejectOutcomeResource assessmentReviewRejectOutcome) { return findAssessmentReview(assessmentReviewId) .andOnSuccess( r -> rejectAssessmentReview(r, reviewRejectOutcomeMapper.mapToDomain(assessmentReviewRejectOutcome))); } @Override ServiceResult<Void> assignApplicationToPanel(long applicationId); @Override ServiceResult<Void> unassignApplicationFromPanel(long applicationId); @Override ServiceResult<Void> createAndNotifyReviews(long competitionId); @Override ServiceResult<Boolean> isPendingReviewNotifications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<List<ReviewResource>> getReviews(long userId, long competitionId); @Override ServiceResult<Void> acceptReview(long assessmentReviewId); @Override ServiceResult<Void> rejectReview(long assessmentReviewId,
ReviewRejectOutcomeResource assessmentReviewRejectOutcome); @Override @Transactional(readOnly = true) ServiceResult<ReviewResource> getReview(long assessmentReviewId); } | @Test public void rejectAssessmentReview_invalidState() { ReviewRejectOutcomeResource rejectOutcomeResource = newReviewRejectOutcomeResource().build(); Review review = newReview().build(); ReviewRejectOutcome reviewRejectOutcome = newReviewRejectOutcome().build(); when(reviewRepositoryMock.findById(review.getId())).thenReturn(Optional.of(review)); when(reviewWorkflowHandlerMock.rejectInvitation(review, reviewRejectOutcome)).thenReturn(false); when(reviewRejectOutcomeMapperMock.mapToDomain(rejectOutcomeResource)).thenReturn(reviewRejectOutcome); ServiceResult<Void> serviceResult = service.rejectReview(review.getId(), rejectOutcomeResource); assertTrue(serviceResult.isFailure()); assertEquals(ASSESSMENT_REVIEW_REJECT_FAILED.getErrorKey(), serviceResult.getErrors().get(0).getErrorKey()); InOrder inOrder = inOrder(reviewRepositoryMock, reviewWorkflowHandlerMock, reviewRejectOutcomeMapperMock); inOrder.verify(reviewRepositoryMock).findById(review.getId()); inOrder.verify(reviewRejectOutcomeMapperMock).mapToDomain(rejectOutcomeResource); inOrder.verify(reviewWorkflowHandlerMock).rejectInvitation(review, reviewRejectOutcome); inOrder.verifyNoMoreInteractions(); } |
ReviewServiceImpl implements ReviewService { @Override @Transactional(readOnly = true) public ServiceResult<ReviewResource> getReview(long assessmentReviewId) { return find(reviewRepository.findById(assessmentReviewId), notFoundError(ReviewResource.class, assessmentReviewId)) .andOnSuccessReturn(reviewMapper::mapToResource); } @Override ServiceResult<Void> assignApplicationToPanel(long applicationId); @Override ServiceResult<Void> unassignApplicationFromPanel(long applicationId); @Override ServiceResult<Void> createAndNotifyReviews(long competitionId); @Override ServiceResult<Boolean> isPendingReviewNotifications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<List<ReviewResource>> getReviews(long userId, long competitionId); @Override ServiceResult<Void> acceptReview(long assessmentReviewId); @Override ServiceResult<Void> rejectReview(long assessmentReviewId,
ReviewRejectOutcomeResource assessmentReviewRejectOutcome); @Override @Transactional(readOnly = true) ServiceResult<ReviewResource> getReview(long assessmentReviewId); } | @Test public void getAssessmentReview() { ReviewResource reviewResource = newReviewResource().build(); Review review = newReview().build(); when(reviewRepositoryMock.findById(reviewResource.getId())).thenReturn(Optional.of(review)); when(reviewMapperMock.mapToResource(review)).thenReturn(reviewResource); ReviewResource result = service.getReview(reviewResource.getId()) .getSuccess(); assertEquals(reviewResource, result); InOrder inOrder = inOrder(reviewRepositoryMock, reviewMapperMock); inOrder.verify(reviewRepositoryMock).findById(reviewResource.getId()); inOrder.verify(reviewMapperMock).mapToResource(review); inOrder.verifyNoMoreInteractions(); } |
ReviewStatisticsServiceImpl implements ReviewStatisticsService { @Override public ServiceResult<ReviewKeyStatisticsResource> getReviewPanelKeyStatistics(long competitionId) { ReviewKeyStatisticsResource reviewKeyStatisticsResource = new ReviewKeyStatisticsResource(); List<Long> assessmentPanelInviteIds = simpleMap(reviewInviteRepository.getByCompetitionId(competitionId), Invite::getId); reviewKeyStatisticsResource.setApplicationsInPanel(getApplicationPanelAssignedCountStatistic(competitionId)); reviewKeyStatisticsResource.setAssessorsAccepted(getReviewParticipantCountStatistic(competitionId, ACCEPTED, assessmentPanelInviteIds)); reviewKeyStatisticsResource.setAssessorsPending(reviewInviteRepository.countByCompetitionIdAndStatusIn(competitionId, singleton(SENT))); return serviceSuccess(reviewKeyStatisticsResource); } ReviewStatisticsServiceImpl(); @Autowired ReviewStatisticsServiceImpl(ReviewInviteRepository reviewInviteRepository,
ReviewParticipantRepository reviewParticipantRepository,
ApplicationRepository applicationRepository); @Override ServiceResult<ReviewKeyStatisticsResource> getReviewPanelKeyStatistics(long competitionId); @Override ServiceResult<ReviewInviteStatisticsResource> getReviewInviteStatistics(long competitionId); } | @Test public void getReviewPanelKeyStatistics() { long competitionId = 1L; List<String> emails = asList("[email protected]", "[email protected]"); List<String> names = asList("John Barnes", "Peter Jones"); Profile profile = newProfile().withId(7L).build(); User user = newUser().withId(11L).withProfileId(profile.getId()).build(); ZonedDateTime acceptsDate = ZonedDateTime.of(2016, 12, 20, 12, 0,0,0, ZoneId.systemDefault()); ZonedDateTime deadlineDate = ZonedDateTime.of(2017, 1, 17, 12, 0,0,0, ZoneId.systemDefault()); Competition competition = newCompetition() .withName("my competition") .withAssessorAcceptsDate(acceptsDate) .withAssessorDeadlineDate(deadlineDate) .build(); List<ReviewInvite> panelInvites = newReviewInvite() .withCompetition(competition) .withEmail(emails.get(0), emails.get(1)) .withHash(Invite.generateInviteHash()) .withName(names.get(0), names.get(1)) .withStatus(SENT) .withUser(user) .build(2); List<Long> panelInviteIds = simpleMap(panelInvites, ReviewInvite::getId); List<Application> applications = newApplication() .withCompetition(competition) .withApplicationState(ApplicationState.SUBMITTED) .build(2); when(applicationRepositoryMock.findByApplicationStateAndFundingDecision( competitionId, SUBMITTED_STATES, "", null,true)).thenReturn(applications); when(reviewInviteRepositoryMock.getByCompetitionId(competitionId)).thenReturn(panelInvites); when(reviewParticipantRepositoryMock.countByCompetitionIdAndRoleAndStatusAndInviteIdIn( competitionId, CompetitionParticipantRole.PANEL_ASSESSOR, ParticipantStatus.ACCEPTED, panelInviteIds)) .thenReturn(1); when(reviewInviteRepositoryMock.countByCompetitionIdAndStatusIn(competitionId, singleton(InviteStatus.SENT))) .thenReturn(1); when(reviewParticipantRepositoryMock.countByCompetitionIdAndRoleAndStatusAndInviteIdIn( competitionId, CompetitionParticipantRole.PANEL_ASSESSOR, ParticipantStatus.PENDING, panelInviteIds)) .thenReturn(1); ServiceResult<ReviewKeyStatisticsResource> serviceResult = reviewStatisticsService.getReviewPanelKeyStatistics(competitionId); InOrder inOrder = inOrder(applicationRepositoryMock, reviewInviteRepositoryMock, reviewParticipantRepositoryMock); inOrder.verify(reviewInviteRepositoryMock).getByCompetitionId(competitionId); inOrder.verify(applicationRepositoryMock).findByApplicationStateAndFundingDecision( competitionId, SUBMITTED_STATES, "", null,true); inOrder.verify(reviewParticipantRepositoryMock).countByCompetitionIdAndRoleAndStatusAndInviteIdIn(competitionId, CompetitionParticipantRole.PANEL_ASSESSOR, ParticipantStatus.ACCEPTED, panelInviteIds); inOrder.verify(reviewInviteRepositoryMock).countByCompetitionIdAndStatusIn(competitionId, singleton(InviteStatus.SENT)); inOrder.verifyNoMoreInteractions(); assertTrue(serviceResult.isSuccess()); ReviewKeyStatisticsResource result = serviceResult.getSuccess(); assertEquals(2, result.getApplicationsInPanel()); assertEquals(1, result.getAssessorsAccepted()); assertEquals(1, result.getAssessorsPending()); } |
ReviewStatisticsServiceImpl implements ReviewStatisticsService { @Override public ServiceResult<ReviewInviteStatisticsResource> getReviewInviteStatistics(long competitionId) { List<Long> reviewPanelInviteIds = simpleMap(reviewInviteRepository.getByCompetitionId(competitionId), Invite::getId); int totalAssessorsInvited = reviewInviteRepository.countByCompetitionIdAndStatusIn(competitionId, EnumSet.of(OPENED, SENT)); int assessorsAccepted = getReviewParticipantCountStatistic(competitionId, ACCEPTED, reviewPanelInviteIds); int assessorsDeclined = getReviewParticipantCountStatistic(competitionId, REJECTED, reviewPanelInviteIds); return serviceSuccess( new ReviewInviteStatisticsResource(totalAssessorsInvited, assessorsAccepted, assessorsDeclined) ); } ReviewStatisticsServiceImpl(); @Autowired ReviewStatisticsServiceImpl(ReviewInviteRepository reviewInviteRepository,
ReviewParticipantRepository reviewParticipantRepository,
ApplicationRepository applicationRepository); @Override ServiceResult<ReviewKeyStatisticsResource> getReviewPanelKeyStatistics(long competitionId); @Override ServiceResult<ReviewInviteStatisticsResource> getReviewInviteStatistics(long competitionId); } | @Test public void getReviewInviteStatistics() { long competitionId = 1L; List<String> emails = asList("[email protected]", "[email protected]"); List<String> names = asList("John Barnes", "Peter Jones"); Profile profile = newProfile().withId(7L).build(); User user = newUser().withId(11L).withProfileId(profile.getId()).build(); ZonedDateTime acceptsDate = ZonedDateTime.of(2016, 12, 20, 12, 0,0,0, ZoneId.systemDefault()); ZonedDateTime deadlineDate = ZonedDateTime.of(2017, 1, 17, 12, 0,0,0, ZoneId.systemDefault()); Competition competition = newCompetition() .withName("my competition") .withAssessorAcceptsDate(acceptsDate) .withAssessorDeadlineDate(deadlineDate) .build(); List<ReviewInvite> panelInvites = newReviewInvite() .withCompetition(competition) .withEmail(emails.get(0), emails.get(1)) .withHash(Invite.generateInviteHash()) .withName(names.get(0), names.get(1)) .withStatus(SENT) .withUser(user) .build(2); List<Long> panelInviteIds = simpleMap(panelInvites, ReviewInvite::getId); when(reviewInviteRepositoryMock.countByCompetitionIdAndStatusIn(competitionId, EnumSet.of(OPENED, SENT))).thenReturn(2); when(reviewInviteRepositoryMock.getByCompetitionId(competitionId)).thenReturn(panelInvites); when(reviewParticipantRepositoryMock.countByCompetitionIdAndRoleAndStatusAndInviteIdIn( competitionId, CompetitionParticipantRole.PANEL_ASSESSOR, ParticipantStatus.ACCEPTED, panelInviteIds)) .thenReturn(1); when(reviewParticipantRepositoryMock.countByCompetitionIdAndRoleAndStatusAndInviteIdIn( competitionId, CompetitionParticipantRole.PANEL_ASSESSOR, ParticipantStatus.REJECTED, panelInviteIds)) .thenReturn(1); ServiceResult<ReviewInviteStatisticsResource> serviceResult = reviewStatisticsService.getReviewInviteStatistics(competitionId); InOrder inOrder = inOrder(reviewInviteRepositoryMock, reviewParticipantRepositoryMock); inOrder.verify(reviewInviteRepositoryMock).getByCompetitionId(competitionId); inOrder.verify(reviewParticipantRepositoryMock).countByCompetitionIdAndRoleAndStatusAndInviteIdIn(competitionId, CompetitionParticipantRole.PANEL_ASSESSOR, ParticipantStatus.ACCEPTED, panelInviteIds); inOrder.verify(reviewParticipantRepositoryMock).countByCompetitionIdAndRoleAndStatusAndInviteIdIn(competitionId, CompetitionParticipantRole.PANEL_ASSESSOR, ParticipantStatus.REJECTED, panelInviteIds); inOrder.verifyNoMoreInteractions(); assertTrue(serviceResult.isSuccess()); ReviewInviteStatisticsResource result = serviceResult.getSuccess(); assertEquals(2, result.getInvited()); assertEquals(1, result.getAccepted()); assertEquals(1, result.getDeclined()); } |
ReviewInviteServiceImpl extends InviteService<ReviewInvite> implements ReviewInviteService { @Override public ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable) { final Page<AssessmentParticipant> pagedResult = assessmentParticipantRepository.findParticipantsNotOnAssessmentPanel(competitionId, pageable); return serviceSuccess(new AvailableAssessorPageResource( pagedResult.getTotalElements(), pagedResult.getTotalPages(), simpleMap(pagedResult.getContent(), availableAssessorMapper::mapToResource), pagedResult.getNumber(), pagedResult.getSize() )); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override @Transactional ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override @Transactional ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId,
Pageable pageable,
List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<ReviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<ReviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); } | @Test public void getAvailableAssessors() { long competitionId = 1L; int page = 1; int pageSize = 1; List<InnovationAreaResource> innovationAreaResources = newInnovationAreaResource() .withName("Emerging Tech and Industries") .build(1); List<AvailableAssessorResource> assessorItems = newAvailableAssessorResource() .withId(4L, 8L) .withName("Jeremy Alufson", "Felix Wilson") .withCompliant(TRUE) .withEmail("[email protected]", "[email protected]") .withBusinessType(BUSINESS, ACADEMIC) .withInnovationAreas(innovationAreaResources) .build(2); AvailableAssessorPageResource expected = newAvailableAssessorPageResource() .withContent(assessorItems) .withSize(pageSize) .withNumber(page) .withTotalPages(2) .withTotalElements(2L) .build(); InnovationArea innovationArea = newInnovationArea() .withName("Emerging Tech and Industries") .build(); List<Profile> profile = newProfile() .withSkillsAreas("Java", "Javascript") .withInnovationArea(innovationArea) .withBusinessType(BUSINESS, ACADEMIC) .withAgreementSignedDate(now()) .build(2); List<User> assessors = newUser() .withId(4L, 8L) .withFirstName("Jeremy", "Felix") .withLastName("Alufson", "Wilson") .withEmailAddress("[email protected]", "[email protected]") .withAffiliations(newAffiliation() .withAffiliationType(EMPLOYER) .withOrganisation("Hive IT") .withPosition("Software Developer") .withExists(true) .build(1)) .withProfileId(profile.get(0).getId(), profile.get(1).getId()) .build(2); List<AssessmentParticipant> participants = newAssessmentParticipant() .withUser(assessors.get(0), assessors.get(1)) .build(2); Pageable pageable = PageRequest.of(page, pageSize, new Sort(ASC, "firstName")); Page<AssessmentParticipant> expectedPage = new PageImpl<>(participants, pageable, 2L); when(assessmentParticipantRepositoryMock.findParticipantsNotOnAssessmentPanel(competitionId, pageable)) .thenReturn(expectedPage); when(availableAssessorMapperMock.mapToResource(participants.get(0))).thenReturn(assessorItems.get(0)); when(availableAssessorMapperMock.mapToResource(participants.get(1))).thenReturn(assessorItems.get(1)); AvailableAssessorPageResource actual = service.getAvailableAssessors(competitionId, pageable) .getSuccess(); verify(assessmentParticipantRepositoryMock).findParticipantsNotOnAssessmentPanel(competitionId, pageable); verify(availableAssessorMapperMock).mapToResource(participants.get(0)); verify(availableAssessorMapperMock).mapToResource(participants.get(1)); assertEquals(expected.getNumber(), actual.getNumber()); assertEquals(expected.getSize(), actual.getSize()); assertEquals(expected.getTotalElements(), actual.getTotalElements()); assertEquals(expected.getTotalPages(), actual.getTotalPages()); assertEquals(expected.getContent(), actual.getContent()); }
@Test public void getAvailableAssessors_empty() { long competitionId = 1L; int page = 0; int pageSize = 20; Pageable pageable = PageRequest.of(page, pageSize, new Sort(ASC, "firstName")); Page<AssessmentParticipant> assessorPage = new PageImpl<>(emptyList(), pageable, 0); when(assessmentParticipantRepositoryMock.findParticipantsNotOnAssessmentPanel(competitionId, pageable)) .thenReturn(assessorPage); AvailableAssessorPageResource result = service.getAvailableAssessors(competitionId, pageable) .getSuccess(); verify(assessmentParticipantRepositoryMock).findParticipantsNotOnAssessmentPanel(competitionId, pageable); assertEquals(page, result.getNumber()); assertEquals(pageSize, result.getSize()); assertEquals(0, result.getTotalElements()); assertEquals(0, result.getTotalPages()); assertEquals(emptyList(), result.getContent()); } |
UserPermissionRules { @PermissionRule(value = "READ_USER_PROFILE", description = "A user can read their own profile") public boolean usersCanViewTheirOwnProfile(UserProfileResource profileDetails, UserResource user) { return profileDetails.getUser().equals(user.getId()); } @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "An internal user can invite a monitoring officer and create the pending user associated.") boolean compAdminProjectFinanceCanCreateMonitoringOfficer(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserRegistrationResource userToCreate, UserResource user); @PermissionRule(value = "VERIFY", description = "A System Registration User can send a new User a verification link by e-mail") boolean systemRegistrationUserCanSendUserVerificationEmail(UserResource userToSendVerificationEmail, UserResource user); @PermissionRule(value = "READ", description = "Any user can view themselves") boolean anyUserCanViewThemselves(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Internal users can view everyone") boolean internalUsersCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can view users in competitions they are assigned to") boolean stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Competition finance users can view users in competitions they are assigned to") boolean competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can view users in projects they are assigned to") boolean monitoringOfficersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ_USER_ORGANISATION", description = "Internal support users can view all users and associated organisations") boolean internalUsersCanViewUserOrganisation(UserOrganisationResource userToView, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "IFS admins can update all users email addresses") boolean ifsAdminCanUpdateAllEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "Support users can update external users email addresses ") boolean supportCanUpdateExternalUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "System Maintenance update all users email addresses") boolean systemMaintenanceUserCanUpdateUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ_INTERNAL", description = "Administrators can view internal users") boolean internalUsersCanViewEveryone(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Support users and administrators can view external users") boolean supportUsersCanViewExternalUsers(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "The System Registration user can view everyone") boolean systemRegistrationUserCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Comp admins and project finance can view assessors") boolean compAdminAndProjectFinanceCanViewAssessors(UserPageResource usersToView, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewOtherConsortiumMembers(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewConsortiumUsersOnApplicationsTheyAreAssessing(UserResource userToView, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "A User should be able to change their own password") boolean usersCanChangeTheirOwnPassword(UserResource userToUpdate, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "The System Registration user should be able to change passwords on behalf of other Users") boolean systemRegistrationUserCanChangePasswordsForUsers(UserResource userToUpdate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A System Registration User can activate Users") boolean systemRegistrationUserCanActivateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "UPDATE", description = "A User can update their own profile") boolean usersCanUpdateTheirOwnProfiles(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE", description = "An admin user can update user details to assign monitoring officers") boolean adminsCanUpdateUserDetails(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile skills") boolean usersCanViewTheirOwnProfileSkills(ProfileSkillsResource profileSkills, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile agreement") boolean usersCanViewTheirOwnProfileAgreement(ProfileAgreementResource profileAgreementResource, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own affiliations") boolean usersCanViewTheirOwnAffiliations(AffiliationResource affiliation, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A user can read their own profile") boolean usersCanViewTheirOwnProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A ifs admin user can read any user's profile") boolean ifsAdminCanViewAnyUsersProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as Comp Admin and Exec can read the user's profile status") boolean usersAndCompAdminCanViewProfileStatus(UserProfileStatusResource profileStatus, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own role") boolean usersCanViewTheirOwnProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the process role of others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewTheProcessRolesOfOtherConsortiumMembers(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Project managers and partners can view the process role for the same organisation") boolean projectPartnersCanViewTheProcessRolesWithinSameApplication(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as internal users can read the user's process role") boolean usersAndInternalUsersCanViewProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the process roles of members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewTheProcessRolesOfConsortiumUsersOnApplicationsTheyAreAssessing(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "CHECK_USER_APPLICATION", description = "The user can check if they have an application for the competition") boolean userCanCheckTheyHaveApplicationForCompetition(UserResource userToCheck, UserResource user); @PermissionRule(value = "EDIT_INTERNAL_USER", description = "Only an IFS Administrator can edit an internal user") boolean ifsAdminCanEditInternalUser(final UserResource userToEdit, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "IFS Administrator can deactivate Users") boolean ifsAdminCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "A Support user can deactivate external Users") boolean supportUserCanDeactivateExternalUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "System Maintenance can deactivate Users") boolean systemMaintenanceUserCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "IFS Administrator can reactivate Users") boolean ifsAdminCanReactivateUsers(UserResource userToReactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A Support user can reactivate external Users") boolean supportUserCanReactivateExternalUsers(UserResource userToActivate, UserResource user); @PermissionRule(value = "AGREE_TERMS", description = "A user can accept the site terms and conditions") boolean usersCanAgreeSiteTermsAndConditions(UserResource userToUpdate, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An assessor can request applicant role") boolean assessorCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant monitoring officer role") boolean isGrantingMonitoringOfficerRoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant a KTA role") boolean isGrantingKTARoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An stakeholder can request applicant role") boolean stakeholderCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An monitoring officer can request applicant role") boolean monitoringOfficerCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "CAN_VIEW_OWN_DASHBOARD", description = "User is requesting own dashboard") boolean isViewingOwnDashboard(UserResource userToView, UserResource user); } | @Test public void usersCanViewTheirOwnDetails() { UserResource user = newUserResource().build(); UserProfileResource userDetails = newUserProfileResource().withUser(user.getId()).build(); assertTrue(rules.usersCanViewTheirOwnProfile(userDetails, user)); }
@Test public void usersCanViewTheirOwnDetailsButNotAnotherUsersDetails() { UserResource anotherUser = newUserResource().withId(1L).build(); UserProfileResource userDetails = newUserProfileResource().withUser(2L).build(); assertFalse(rules.usersCanViewTheirOwnProfile(userDetails, anotherUser)); } |
ReviewInviteServiceImpl extends InviteService<ReviewInvite> implements ReviewInviteService { @Override public ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId) { List<AssessmentParticipant> result = assessmentParticipantRepository.findParticipantsNotOnAssessmentPanel(competitionId); return serviceSuccess(simpleMap(result, competitionParticipant -> competitionParticipant.getUser().getId())); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override @Transactional ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override @Transactional ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId,
Pageable pageable,
List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<ReviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<ReviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); } | @Test public void getAvailableAssessorIds() { long competitionId = 1L; InnovationArea innovationArea = newInnovationArea() .withName("Emerging Tech and Industries") .build(); List<Long> expectedAssessorIds = asList(4L, 8L); List<Profile> profiles = newProfile() .withSkillsAreas("Java", "Javascript") .withInnovationArea(innovationArea) .withBusinessType(BUSINESS, ACADEMIC) .withAgreementSignedDate(now()) .build(2); List<User> assessorUsers = newUser() .withId(expectedAssessorIds.get(0), expectedAssessorIds.get(1)) .withFirstName("Jeremy", "Felix") .withLastName("Alufson", "Wilson") .withEmailAddress("[email protected]", "[email protected]") .withAffiliations(newAffiliation() .withAffiliationType(EMPLOYER) .withOrganisation("Hive IT") .withPosition("Software Developer") .withExists(true) .build(1)) .withProfileId(profiles.get(0).getId(), profiles.get(1).getId()) .build(2); List<AssessmentParticipant> participants = newAssessmentParticipant() .withUser(assessorUsers.get(0), assessorUsers.get(1)) .build(2); when(assessmentParticipantRepositoryMock.findParticipantsNotOnAssessmentPanel(competitionId)) .thenReturn(participants); List<Long> actualAssessorIds = service.getAvailableAssessorIds(competitionId) .getSuccess(); verify(assessmentParticipantRepositoryMock).findParticipantsNotOnAssessmentPanel(competitionId); assertEquals(expectedAssessorIds, actualAssessorIds); } |
ReviewInviteServiceImpl extends InviteService<ReviewInvite> implements ReviewInviteService { @Override public ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable) { Page<ReviewInvite> pagedResult = reviewInviteRepository.getByCompetitionIdAndStatus(competitionId, CREATED, pageable); List<AssessorCreatedInviteResource> createdInvites = simpleMap( pagedResult.getContent(), assessorCreatedInviteMapper::mapToResource ); return serviceSuccess(new AssessorCreatedInvitePageResource( pagedResult.getTotalElements(), pagedResult.getTotalPages(), createdInvites, pagedResult.getNumber(), pagedResult.getSize() )); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override @Transactional ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override @Transactional ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId,
Pageable pageable,
List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<ReviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<ReviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); } | @Test public void getCreatedInvites() { long competitionId = 1L; InnovationArea innovationArea = newInnovationArea().build(); InnovationAreaResource innovationAreaResource = newInnovationAreaResource() .withId(2L) .withName("Earth Observation") .build(); List<InnovationAreaResource> innovationAreaList = singletonList(innovationAreaResource); Profile profile1 = newProfile() .withSkillsAreas("Java") .withAgreementSignedDate(now()) .withInnovationArea(innovationArea) .build(); User compliantUser = newUser() .withAffiliations(newAffiliation() .withAffiliationType(EMPLOYER) .withOrganisation("Hive IT") .withPosition("Software Developer") .withExists(true) .build(1)) .withProfileId(profile1.getId()) .build(); Profile profile2 = newProfile() .withSkillsAreas() .withAgreementSignedDate(now()) .build(); User nonCompliantUserNoSkills = newUser() .withAffiliations(newAffiliation() .withAffiliationType(EMPLOYER) .withOrganisation("Hive IT") .withPosition("Software Developer") .withExists(true) .build(1)) .withProfileId(profile2.getId()) .build(); Profile profile3 = newProfile() .withSkillsAreas("Java") .withAgreementSignedDate(now()) .build(); User nonCompliantUserNoAffiliations = newUser() .withAffiliations() .withProfileId(profile3.getId()) .build(); Profile profile4 = newProfile() .withSkillsAreas("Java") .withAgreementSignedDate() .build(); User nonCompliantUserNoAgreement = newUser() .withAffiliations(newAffiliation() .withAffiliationType(EMPLOYER) .withOrganisation("Hive IT") .withPosition("Software Developer") .withExists(true) .build(1)) .withProfileId(profile4.getId()) .build(); List<ReviewInvite> existingUserInvites = newReviewInvite() .withId(1L, 2L, 3L, 4L) .withName("John Barnes", "Dave Smith", "Richard Turner", "Oliver Romero") .withEmail("[email protected]", "[email protected]", "[email protected]", "[email protected]") .withUser(compliantUser, nonCompliantUserNoSkills, nonCompliantUserNoAffiliations, nonCompliantUserNoAgreement) .build(4); List<AssessorCreatedInviteResource> expectedInvites = newAssessorCreatedInviteResource() .withId(compliantUser.getId(), nonCompliantUserNoSkills.getId(), nonCompliantUserNoAffiliations.getId(), nonCompliantUserNoAgreement.getId()) .withInviteId(1L, 2L, 3L, 4L) .withName("John Barnes", "Dave Smith", "Richard Turner", "Oliver Romero") .withInnovationAreas(innovationAreaList, emptyList(), emptyList(), emptyList()) .withCompliant(true, false, false, false) .withEmail("[email protected]", "[email protected]", "[email protected]", "[email protected]") .build(4); long totalElements = 100L; Pageable pageable = PageRequest.of(0, 20); Page<ReviewInvite> page = new PageImpl<>(existingUserInvites, pageable, totalElements); when(reviewInviteRepositoryMock.getByCompetitionIdAndStatus(competitionId, CREATED, pageable)).thenReturn(page); when(assessorCreatedInviteMapperMock.mapToResource(isA(ReviewInvite.class))).thenReturn( expectedInvites.get(0), expectedInvites.get(1), expectedInvites.get(2), expectedInvites.get(3) ); AssessorCreatedInvitePageResource actual = service.getCreatedInvites(competitionId, pageable).getSuccess(); assertEquals(totalElements, actual.getTotalElements()); assertEquals(5, actual.getTotalPages()); assertEquals(expectedInvites, actual.getContent()); assertEquals(0, actual.getNumber()); assertEquals(20, actual.getSize()); InOrder inOrder = inOrder(reviewInviteRepositoryMock, assessorCreatedInviteMapperMock); inOrder.verify(reviewInviteRepositoryMock).getByCompetitionIdAndStatus(competitionId, CREATED, pageable); inOrder.verify(assessorCreatedInviteMapperMock, times(4)) .mapToResource(isA(ReviewInvite.class)); inOrder.verifyNoMoreInteractions(); } |
ReviewInviteServiceImpl extends InviteService<ReviewInvite> implements ReviewInviteService { @Override public ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites) { return serviceSuccess(mapWithIndex(stagedInvites, (i, invite) -> getUser(invite.getUserId()).andOnSuccess(user -> getByEmailAndCompetition(user.getEmail(), invite.getCompetitionId()).andOnFailure(() -> inviteUserToCompetition(user, invite.getCompetitionId()) )))).andOnSuccessReturnVoid(); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override @Transactional ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override @Transactional ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId,
Pageable pageable,
List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<ReviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<ReviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); } | @Test public void inviteUsers_existing() { List<User> existingUsers = newUser() .withEmailAddress("[email protected]", "[email protected]") .withFirstName("fred", "joe") .withLastName("smith", "brown") .build(2); Competition competition = newCompetition() .withName("competition name") .build(); List<ExistingUserStagedInviteResource> existingAssessors = newExistingUserStagedInviteResource() .withUserId(existingUsers.get(0).getId(), existingUsers.get(1).getId()) .withCompetitionId(competition.getId()) .build(2); when(userRepositoryMock.findById(existingUsers.get(0).getId())).thenReturn(Optional.of(existingUsers.get(0))); when(userRepositoryMock.findById(existingUsers.get(1).getId())).thenReturn(Optional.of(existingUsers.get(1))); when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition)); when(reviewInviteRepositoryMock.save(isA(ReviewInvite.class))).thenReturn(new ReviewInvite()); ServiceResult<Void> serviceResult = service.inviteUsers(existingAssessors); assertTrue(serviceResult.isSuccess()); InOrder inOrder = inOrder(userRepositoryMock, competitionRepositoryMock, reviewInviteRepositoryMock); inOrder.verify(userRepositoryMock).findById(existingAssessors.get(0).getUserId()); inOrder.verify(competitionRepositoryMock).findById(competition.getId()); inOrder.verify(reviewInviteRepositoryMock).save(createInviteExpectations(existingUsers.get(0).getName(), existingUsers.get(0).getEmail(), CREATED, competition)); inOrder.verify(userRepositoryMock).findById(existingAssessors.get(1).getUserId()); inOrder.verify(competitionRepositoryMock).findById(competition.getId()); inOrder.verify(reviewInviteRepositoryMock).save(createInviteExpectations(existingUsers.get(1).getName(), existingUsers.get(1).getEmail(), CREATED, competition)); inOrder.verifyNoMoreInteractions(); } |
ReviewInviteServiceImpl extends InviteService<ReviewInvite> implements ReviewInviteService { @Override @Transactional public ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource) { return getCompetition(competitionId).andOnSuccess(competition -> { String customTextPlain = stripHtml(assessorInviteSendResource.getContent()); String customTextHtml = plainTextToHtml(customTextPlain); return ServiceResult.processAnyFailuresOrSucceed(simpleMap( reviewInviteRepository.getByCompetitionIdAndStatus(competition.getId(), CREATED), invite -> { reviewParticipantRepository.save( new ReviewParticipant(invite.send(loggedInUserSupplier.get(), now())) ); return sendInviteNotification( assessorInviteSendResource.getSubject(), customTextPlain, customTextHtml, invite, Notifications.INVITE_ASSESSOR_GROUP_TO_PANEL ); } )); }); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override @Transactional ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override @Transactional ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId,
Pageable pageable,
List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<ReviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<ReviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); } | @Test public void sendAllInvites() { List<String> emails = asList("[email protected]", "[email protected]"); List<String> names = asList("John Barnes", "Peter Jones"); Competition competition = newCompetition() .withName("my competition") .withAssessorAcceptsDate(ZonedDateTime.parse("2017-08-24T12:00:00+01:00")) .withAssessorDeadlineDate(ZonedDateTime.parse("2017-08-30T12:00:00+01:00")) .build(); List<ReviewInvite> invites = newReviewInvite() .withCompetition(competition) .withEmail(emails.get(0), emails.get(1)) .withHash(Invite.generateInviteHash()) .withName(names.get(0), names.get(1)) .withStatus(CREATED) .withUser(newUser().withFirstName("Paul").build()) .build(2); AssessorInviteSendResource assessorInviteSendResource = setUpAssessorInviteSendResource(); Map<String, Object> expectedNotificationArguments1 = asMap( "subject", assessorInviteSendResource.getSubject(), "name", invites.get(0).getName(), "competitionName", invites.get(0).getTarget().getName(), "inviteUrl", "https: "customTextPlain", "content", "customTextHtml", "content" ); Map<String, Object> expectedNotificationArguments2 = asMap( "subject", assessorInviteSendResource.getSubject(), "name", invites.get(1).getName(), "competitionName", invites.get(1).getTarget().getName(), "inviteUrl", "https: "customTextPlain", "content", "customTextHtml", "content" ); SystemNotificationSource from = systemNotificationSourceMock; NotificationTarget to1 = new UserNotificationTarget(names.get(0), emails.get(0)); NotificationTarget to2 = new UserNotificationTarget(names.get(1), emails.get(1)); List<Notification> notifications = newNotification() .withSource(from, from) .withMessageKey(INVITE_ASSESSOR_GROUP_TO_PANEL, INVITE_ASSESSOR_GROUP_TO_PANEL) .withTargets(singletonList(to1), singletonList(to2)) .withGlobalArguments(expectedNotificationArguments1, expectedNotificationArguments2) .build(2); when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition)); when(reviewInviteRepositoryMock.getByCompetitionIdAndStatus(competition.getId(), CREATED)).thenReturn(invites); when(userRepositoryMock.findByEmail(emails.get(0))).thenReturn(Optional.empty()); when(userRepositoryMock.findByEmail(emails.get(1))).thenReturn(Optional.empty()); when(notificationService.sendNotificationWithFlush(notifications.get(0), EMAIL)).thenReturn(serviceSuccess()); when(notificationService.sendNotificationWithFlush(notifications.get(1), EMAIL)).thenReturn(serviceSuccess()); ServiceResult<Void> serviceResult = service.sendAllInvites(competition.getId(), assessorInviteSendResource); assertTrue(serviceResult.isSuccess()); InOrder inOrder = inOrder(competitionRepositoryMock, reviewInviteRepositoryMock, userRepositoryMock, reviewParticipantRepositoryMock, notificationService); inOrder.verify(competitionRepositoryMock).findById(competition.getId()); inOrder.verify(reviewInviteRepositoryMock).getByCompetitionIdAndStatus(competition.getId(), CREATED); inOrder.verify(reviewParticipantRepositoryMock).save(createAssessmentPanelParticipantExpectations(invites.get(0))); inOrder.verify(notificationService).sendNotificationWithFlush(notifications.get(0), EMAIL); inOrder.verify(reviewParticipantRepositoryMock).save(createAssessmentPanelParticipantExpectations(invites.get(1))); inOrder.verify(notificationService).sendNotificationWithFlush(notifications.get(1), EMAIL); inOrder.verifyNoMoreInteractions(); } |
ReviewInviteServiceImpl extends InviteService<ReviewInvite> implements ReviewInviteService { @Override public ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId) { return getCompetition(competitionId).andOnSuccess(competition -> { List<ReviewInvite> invites = reviewInviteRepository.getByCompetitionIdAndStatus(competition.getId(), CREATED); List<String> recipients = simpleMap(invites, ReviewInvite::getName); recipients.sort(String::compareTo); return serviceSuccess(new AssessorInvitesToSendResource( recipients, competition.getId(), competition.getName(), getInvitePreviewContent(competition) )); }); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override @Transactional ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override @Transactional ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId,
Pageable pageable,
List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<ReviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<ReviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); } | @Test public void getAllInvitesToSend() { List<String> emails = asList("[email protected]", "[email protected]"); List<String> names = asList("John Barnes", "Peter Jones"); ZonedDateTime acceptsDate = of(2016, 12, 20, 12, 0,0,0, ZoneId.systemDefault()); ZonedDateTime deadlineDate = of(2017, 1, 17, 12, 0,0,0, ZoneId.systemDefault()); Competition competition = newCompetition() .withName("Competition in Assessor Panel") .withAssessorAcceptsDate(acceptsDate) .withAssessorDeadlineDate(deadlineDate) .build(); List<ReviewInvite> invites = newReviewInvite() .withCompetition(competition) .withEmail(emails.get(0), emails.get(1)) .withHash(Invite.generateInviteHash()) .withName(names.get(0), names.get(1)) .withStatus(CREATED) .withUser(new User()) .build(2); Map<String, Object> expectedNotificationArguments = asMap( "competitionName", competition.getName() ); NotificationTarget notificationTarget = new UserNotificationTarget("", ""); String templatePath = PREVIEW_TEMPLATES_PATH + "invite_assessors_to_assessors_panel_text.txt"; when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition)); when(reviewInviteRepositoryMock.getByCompetitionIdAndStatus(competition.getId(), CREATED)).thenReturn(invites); when(notificationTemplateRendererMock.renderTemplate(systemNotificationSourceMock, notificationTarget, templatePath, expectedNotificationArguments)).thenReturn(serviceSuccess("content")); AssessorInvitesToSendResource expectedAssessorInviteToSendResource = newAssessorInvitesToSendResource() .withContent("content") .withCompetitionId(competition.getId()) .withCompetitionName(competition.getName()) .withRecipients(names) .build(); AssessorInvitesToSendResource result = service.getAllInvitesToSend(competition.getId()).getSuccess(); assertEquals(expectedAssessorInviteToSendResource, result); InOrder inOrder = inOrder(competitionRepositoryMock, reviewInviteRepositoryMock, notificationTemplateRendererMock); inOrder.verify(competitionRepositoryMock).findById(competition.getId()); inOrder.verify(reviewInviteRepositoryMock).getByCompetitionIdAndStatus(competition.getId(), CREATED); inOrder.verify(notificationTemplateRendererMock).renderTemplate(systemNotificationSourceMock, notificationTarget, templatePath, expectedNotificationArguments); inOrder.verifyNoMoreInteractions(); } |
ReviewInviteServiceImpl extends InviteService<ReviewInvite> implements ReviewInviteService { @Override public ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds) { return getCompetition(competitionId).andOnSuccess(competition -> { List<ReviewInvite> invites = reviewInviteRepository.getByIdIn(inviteIds); List<String> recipients = simpleMap(invites, ReviewInvite::getName); recipients.sort(String::compareTo); return serviceSuccess(new AssessorInvitesToSendResource( recipients, competition.getId(), competition.getName(), getInvitePreviewContent(competition) )); }); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override @Transactional ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override @Transactional ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId,
Pageable pageable,
List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<ReviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<ReviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); } | @Test public void getAllInvitesToResend() { List<String> emails = asList("[email protected]", "[email protected]"); List<String> names = asList("John Barnes", "Peter Jones"); List<Long> inviteIds = asList(1L, 2L); ZonedDateTime acceptsDate = of(2016, 12, 20, 12, 0,0,0, ZoneId.systemDefault()); ZonedDateTime deadlineDate = of(2017, 1, 17, 12, 0,0,0, ZoneId.systemDefault()); Competition competition = newCompetition() .withName("my competition") .withAssessorAcceptsDate(acceptsDate) .withAssessorDeadlineDate(deadlineDate) .build(); List<ReviewInvite> invites = newReviewInvite() .withCompetition(competition) .withEmail(emails.get(0), emails.get(1)) .withHash(Invite.generateInviteHash()) .withName(names.get(0), names.get(1)) .withStatus(SENT) .withUser(newUser()) .build(2); Map<String, Object> expectedNotificationArguments = asMap( "competitionName", competition.getName() ); NotificationTarget notificationTarget = new UserNotificationTarget("", ""); String templatePath = PREVIEW_TEMPLATES_PATH + "invite_assessors_to_assessors_panel_text.txt"; when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition)); when(reviewInviteRepositoryMock.getByIdIn(inviteIds)).thenReturn(invites); when(notificationTemplateRendererMock.renderTemplate(systemNotificationSourceMock, notificationTarget, templatePath, expectedNotificationArguments)).thenReturn(serviceSuccess("content")); AssessorInvitesToSendResource expectedAssessorInviteToSendResource = newAssessorInvitesToSendResource() .withContent("content") .withCompetitionId(competition.getId()) .withCompetitionName(competition.getName()) .withRecipients(names) .build(); AssessorInvitesToSendResource result = service.getAllInvitesToResend(competition.getId(), inviteIds).getSuccess(); assertEquals(expectedAssessorInviteToSendResource, result); InOrder inOrder = inOrder(competitionRepositoryMock, reviewInviteRepositoryMock, notificationTemplateRendererMock); inOrder.verify(competitionRepositoryMock).findById(competition.getId()); inOrder.verify(reviewInviteRepositoryMock).getByIdIn(inviteIds); inOrder.verify(notificationTemplateRendererMock).renderTemplate(systemNotificationSourceMock, notificationTarget, templatePath, expectedNotificationArguments); inOrder.verifyNoMoreInteractions(); } |
ReviewInviteServiceImpl extends InviteService<ReviewInvite> implements ReviewInviteService { @Override @Transactional public ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource) { String customTextPlain = stripHtml(assessorInviteSendResource.getContent()); String customTextHtml = plainTextToHtml(customTextPlain); return ServiceResult.processAnyFailuresOrSucceed(simpleMap( reviewInviteRepository.getByIdIn(inviteIds), invite -> { updateParticipantStatus(invite); return sendInviteNotification( assessorInviteSendResource.getSubject(), customTextPlain, customTextHtml, invite.sendOrResend(loggedInUserSupplier.get(), now()), Notifications.INVITE_ASSESSOR_GROUP_TO_PANEL ); } )); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override @Transactional ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override @Transactional ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId,
Pageable pageable,
List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<ReviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<ReviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); } | @Test public void resendInvites() { List<String> emails = asList("[email protected]", "[email protected]"); List<String> names = asList("John Barnes", "Peter Jones"); List<Long> inviteIds = asList(1L, 2L); Competition competition = newCompetition() .withName("my competition") .withAssessorAcceptsDate(ZonedDateTime.parse("2017-05-24T12:00:00+01:00")) .withAssessorDeadlineDate(ZonedDateTime.parse("2017-05-30T12:00:00+01:00")) .build(); List<ReviewInvite> invites = newReviewInvite() .withCompetition(competition) .withEmail(emails.get(0), emails.get(1)) .withHash(Invite.generateInviteHash()) .withName(names.get(0), names.get(1)) .withStatus(SENT) .withUser(newUser().build()) .build(2); List<ReviewParticipant> reviewParticipants = newReviewParticipant() .with(id(null)) .withStatus(PENDING, REJECTED) .withRole(ASSESSOR, ASSESSOR) .withCompetition(competition, competition) .withInvite(invites.get(0), invites.get(1)) .withUser() .build(2); AssessorInviteSendResource assessorInviteSendResource = setUpAssessorInviteSendResource(); Map<String, Object> expectedNotificationArguments1 = asMap( "subject", assessorInviteSendResource.getSubject(), "name", invites.get(0).getName(), "competitionName", invites.get(0).getTarget().getName(), "inviteUrl", "https: "customTextPlain", "content", "customTextHtml", "content" ); Map<String, Object> expectedNotificationArguments2 = asMap( "subject", assessorInviteSendResource.getSubject(), "name", invites.get(1).getName(), "competitionName", invites.get(1).getTarget().getName(), "inviteUrl", "https: "customTextPlain", "content", "customTextHtml", "content" ); SystemNotificationSource from = systemNotificationSourceMock; NotificationTarget to1 = new UserNotificationTarget(names.get(0), emails.get(0)); NotificationTarget to2 = new UserNotificationTarget(names.get(1), emails.get(1)); List<Notification> notifications = newNotification() .withSource(from, from) .withMessageKey(INVITE_ASSESSOR_GROUP_TO_PANEL, INVITE_ASSESSOR_GROUP_TO_PANEL) .withTargets(singletonList(to1), singletonList(to2)) .withGlobalArguments(expectedNotificationArguments1, expectedNotificationArguments2) .build(2); when(reviewInviteRepositoryMock.getByIdIn(inviteIds)).thenReturn(invites); when(reviewParticipantRepositoryMock.getByInviteHash(invites.get(0).getHash())).thenReturn(reviewParticipants.get(0)); when(reviewParticipantRepositoryMock.getByInviteHash(invites.get(1).getHash())).thenReturn(reviewParticipants.get(1)); when(notificationService.sendNotificationWithFlush(notifications.get(0), EMAIL)).thenReturn(serviceSuccess()); when(notificationService.sendNotificationWithFlush(notifications.get(1), EMAIL)).thenReturn(serviceSuccess()); ServiceResult<Void> serviceResult = service.resendInvites(inviteIds, assessorInviteSendResource); assertTrue(serviceResult.isSuccess()); InOrder inOrder = inOrder(reviewInviteRepositoryMock, reviewParticipantRepositoryMock, notificationService); inOrder.verify(reviewInviteRepositoryMock).getByIdIn(inviteIds); inOrder.verify(reviewParticipantRepositoryMock).getByInviteHash(invites.get(0).getHash()); inOrder.verify(notificationService).sendNotificationWithFlush(notifications.get(0), EMAIL); inOrder.verify(reviewParticipantRepositoryMock).getByInviteHash(invites.get(1).getHash()); inOrder.verify(notificationService).sendNotificationWithFlush(notifications.get(1), EMAIL); inOrder.verifyNoMoreInteractions(); } |
ReviewInviteServiceImpl extends InviteService<ReviewInvite> implements ReviewInviteService { @Override public ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId, Pageable pageable, List<ParticipantStatus> statuses) { Page<ReviewParticipant> pagedResult = reviewParticipantRepository.getPanelAssessorsByCompetitionAndStatusContains( competitionId, statuses, pageable); List<AssessorInviteOverviewResource> inviteOverviews = simpleMap( pagedResult.getContent(), assessorInviteOverviewMapper::mapToResource ); return serviceSuccess(new AssessorInviteOverviewPageResource( pagedResult.getTotalElements(), pagedResult.getTotalPages(), inviteOverviews, pagedResult.getNumber(), pagedResult.getSize() )); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override @Transactional ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override @Transactional ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId,
Pageable pageable,
List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<ReviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<ReviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); } | @Test public void getInvitationOverview() { long competitionId = 1L; Pageable pageable = PageRequest.of(0, 5); List<ReviewParticipant> expectedParticipants = newReviewParticipant() .withInvite( newReviewInvite() .withName("Name 1", "Name 2", "Name 3", "Name 4", "Name 5") .withSentOn(now()) .withStatus(SENT) .buildArray(5, ReviewInvite.class) ) .withStatus(PENDING) .build(5); Page<ReviewParticipant> pageResult = new PageImpl<>(expectedParticipants, pageable, 10); when(reviewParticipantRepositoryMock.getPanelAssessorsByCompetitionAndStatusContains(competitionId, singletonList(PENDING), pageable)) .thenReturn(pageResult); List<AssessorInviteOverviewResource> overviewResources = newAssessorInviteOverviewResource() .withName("Name 1", "Name 2", "Name 3", "Name 4", "Name 5") .build(5); when(assessorInviteOverviewMapperMock.mapToResource(isA(ReviewParticipant.class))) .thenReturn( overviewResources.get(0), overviewResources.get(1), overviewResources.get(2), overviewResources.get(3), overviewResources.get(4) ); when(participantStatusMapperMock.mapToResource(PENDING)).thenReturn(ParticipantStatusResource.PENDING); ServiceResult<AssessorInviteOverviewPageResource> result = service.getInvitationOverview(competitionId, pageable, singletonList(PENDING)); verify(reviewParticipantRepositoryMock) .getPanelAssessorsByCompetitionAndStatusContains(competitionId, singletonList(PENDING), pageable); verify(assessorInviteOverviewMapperMock, times(5)) .mapToResource(isA(ReviewParticipant.class)); assertTrue(result.isSuccess()); AssessorInviteOverviewPageResource pageResource = result.getSuccess(); assertEquals(0, pageResource.getNumber()); assertEquals(5, pageResource.getSize()); assertEquals(2, pageResource.getTotalPages()); assertEquals(10, pageResource.getTotalElements()); List<AssessorInviteOverviewResource> content = pageResource.getContent(); assertEquals("Name 1", content.get(0).getName()); assertEquals("Name 2", content.get(1).getName()); assertEquals("Name 3", content.get(2).getName()); assertEquals("Name 4", content.get(3).getName()); assertEquals("Name 5", content.get(4).getName()); content.forEach(this::assertNotExistingAssessorUser); } |
ReviewInviteServiceImpl extends InviteService<ReviewInvite> implements ReviewInviteService { @Override public ServiceResult<List<ReviewParticipantResource>> getAllInvitesByUser(long userId) { List<ReviewParticipantResource> reviewParticipantResources = reviewParticipantRepository .findByUserIdAndRole(userId, PANEL_ASSESSOR) .stream() .filter(participant -> now().isBefore(participant.getInvite().getTarget().getAssessmentPanelDate())) .map(reviewParticipantMapper::mapToResource) .collect(toList()); reviewParticipantResources.forEach(this::determineStatusOfPanelApplications); return serviceSuccess(reviewParticipantResources); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override @Transactional ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override @Transactional ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId,
Pageable pageable,
List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<ReviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<ReviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); } | @Test public void getAllInvitesByUser() { User user = newUser() .withId(1L) .build(); Milestone milestone = newMilestone() .withType(ASSESSMENT_PANEL) .withDate(now().plusDays(1)) .build(); Competition competition = newCompetition() .withId(2L) .withName("Competition in Assessor Panel") .withMilestones(singletonList(milestone)) .build(); List<ReviewInvite> invites = newReviewInvite() .withEmail("[email protected]") .withHash("") .withCompetition(competition) .withUser(user) .build(2); List<ReviewParticipant> reviewParticipants = newReviewParticipant() .withInvite(invites.get(0), invites.get(1)) .withStatus(PENDING) .withCompetition(competition) .withUser(user) .build(2); List<ReviewParticipantResource> expected = newReviewParticipantResource() .withCompetition(2L) .withCompetitionName("Competition in Assessor Panel") .withUser(1L) .build(2); List<Review> reviews = newReview() .withState(ReviewState.PENDING) .build(2); when(reviewParticipantRepositoryMock.findByUserIdAndRole(1L, PANEL_ASSESSOR)).thenReturn(reviewParticipants); when(reviewParticipantMapperMock.mapToResource(reviewParticipants.get(0))).thenReturn(expected.get(0)); when(reviewParticipantMapperMock.mapToResource(reviewParticipants.get(1))).thenReturn(expected.get(1)); when(reviewRepositoryMock.findByParticipantUserIdAndTargetCompetitionIdOrderByActivityStateAscIdAsc(1L, competition.getId())).thenReturn(reviews); List<ReviewParticipantResource> actual = service.getAllInvitesByUser(1L).getSuccess(); assertEquals(actual.get(0), expected.get(0)); assertEquals(actual.get(1), expected.get(1)); InOrder inOrder = inOrder(reviewParticipantRepositoryMock); inOrder.verify(reviewParticipantRepositoryMock).findByUserIdAndRole(1L, PANEL_ASSESSOR); inOrder.verifyNoMoreInteractions(); }
@Test public void getAllInvitesByUser_invitesExpired() { User user = newUser() .withId(1L) .build(); Milestone milestone = newMilestone() .withType(ASSESSMENT_PANEL) .withDate(now().minusDays(2)) .build(); Competition competition = newCompetition() .withId(2L) .withName("Competition in Assessor Panel") .withMilestones(singletonList(milestone)) .build(); List<ReviewInvite> invites = newReviewInvite() .withEmail("[email protected]") .withHash("") .withCompetition(competition) .withUser(user) .build(2); List<ReviewParticipant> reviewParticipants = newReviewParticipant() .withInvite(invites.get(0), invites.get(1)) .withStatus(PENDING) .withCompetition(competition) .withUser(user) .build(2); List<ReviewParticipantResource> expected = newReviewParticipantResource() .withCompetition(2L) .withCompetitionName("Competition in Assessor Panel") .withUser(1L) .build(2); when(reviewParticipantRepositoryMock.findByUserIdAndRole(1L, PANEL_ASSESSOR)).thenReturn(reviewParticipants); when(reviewParticipantMapperMock.mapToResource(reviewParticipants.get(0))).thenReturn(expected.get(0)); when(reviewParticipantMapperMock.mapToResource(reviewParticipants.get(1))).thenReturn(expected.get(1)); List<ReviewParticipantResource> actual = service.getAllInvitesByUser(1L).getSuccess(); assertTrue(actual.isEmpty()); InOrder inOrder = inOrder(reviewParticipantRepositoryMock); inOrder.verify(reviewParticipantRepositoryMock).findByUserIdAndRole(1L, PANEL_ASSESSOR); inOrder.verifyNoMoreInteractions(); } |
ReviewInviteServiceImpl extends InviteService<ReviewInvite> implements ReviewInviteService { @Override public ServiceResult<Void> deleteInvite(String email, long competitionId) { return getByEmailAndCompetition(email, competitionId).andOnSuccess(this::deleteInvite); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override @Transactional ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override @Transactional ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId,
Pageable pageable,
List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<ReviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<ReviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); } | @Test public void deleteInvite() { String email = "[email protected]"; long competitionId = 11L; ReviewInvite reviewInvite = newReviewInvite() .withStatus(CREATED) .build(); when(reviewInviteRepositoryMock.getByEmailAndCompetitionId(email, competitionId)).thenReturn(reviewInvite); service.deleteInvite(email, competitionId).getSuccess(); InOrder inOrder = inOrder(reviewInviteRepositoryMock); inOrder.verify(reviewInviteRepositoryMock).getByEmailAndCompetitionId(email, competitionId); inOrder.verify(reviewInviteRepositoryMock).delete(reviewInvite); inOrder.verifyNoMoreInteractions(); }
@Test public void deleteInvite_sent() { String email = "[email protected]"; long competitionId = 11L; ReviewInvite reviewInvite = newReviewInvite() .withStatus(SENT) .build(); when(reviewInviteRepositoryMock.getByEmailAndCompetitionId(email, competitionId)).thenReturn(reviewInvite); ServiceResult<Void> serviceResult = service.deleteInvite(email, competitionId); assertTrue(serviceResult.isFailure()); verify(reviewInviteRepositoryMock).getByEmailAndCompetitionId(email, competitionId); verifyNoMoreInteractions(reviewInviteRepositoryMock); } |
ReviewInviteServiceImpl extends InviteService<ReviewInvite> implements ReviewInviteService { @Override public ServiceResult<Void> deleteAllInvites(long competitionId) { return find(competitionRepository.findById(competitionId), notFoundError(Competition.class, competitionId)) .andOnSuccessReturnVoid(competition -> reviewInviteRepository.deleteByCompetitionIdAndStatus(competition.getId(), CREATED)); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override @Transactional ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override @Transactional ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId,
Pageable pageable,
List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<ReviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<ReviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); } | @Test public void deleteAllInvites() { long competitionId = 1L; when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.of(newCompetition().build())); assertTrue(service.deleteAllInvites(competitionId).isSuccess()); verify(competitionRepositoryMock).findById(competitionId); }
@Test public void deleteAllInvites_noCompetition() { long competitionId = 1L; when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.empty()); assertFalse(service.deleteAllInvites(competitionId).isSuccess()); verify(competitionRepositoryMock).findById(competitionId); } |
ReviewInviteServiceImpl extends InviteService<ReviewInvite> implements ReviewInviteService { @Override public ServiceResult<ReviewInviteResource> openInvite(String inviteHash) { return getByHashIfOpen(inviteHash) .andOnSuccessReturn(this::openInvite) .andOnSuccessReturn(reviewInviteMapper::mapToResource); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override @Transactional ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override @Transactional ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId,
Pageable pageable,
List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<ReviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<ReviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); } | @Test public void openInvite() { Milestone milestone = newMilestone() .withType(ASSESSMENT_PANEL) .withDate(now().plusDays(1)) .build(); ReviewInvite reviewInvite = setUpAssessmentPanelInvite(newCompetition() .withName("my competition") .withMilestones(singletonList(milestone)) .build(), SENT); when(reviewInviteRepositoryMock.getByHash(isA(String.class))).thenReturn(reviewInvite); ServiceResult<ReviewInviteResource> inviteServiceResult = service.openInvite(INVITE_HASH); assertTrue(inviteServiceResult.isSuccess()); ReviewInviteResource reviewInviteResource = inviteServiceResult.getSuccess(); assertEquals("my competition", reviewInviteResource.getCompetitionName()); InOrder inOrder = inOrder(reviewInviteRepositoryMock, reviewInviteMapperMock); inOrder.verify(reviewInviteRepositoryMock).getByHash(INVITE_HASH); inOrder.verify(reviewInviteRepositoryMock).save(isA(ReviewInvite.class)); inOrder.verify(reviewInviteMapperMock).mapToResource(isA(ReviewInvite.class)); inOrder.verifyNoMoreInteractions(); }
@Test public void openInvite_inviteExpired() { Milestone milestone = newMilestone() .withType(ASSESSMENT_PANEL) .withDate(now().minusDays(1)) .build(); ReviewInvite reviewInvite = setUpAssessmentPanelInvite(newCompetition() .withName("my competition") .withMilestones(singletonList(milestone)) .build(), SENT); when(reviewInviteRepositoryMock.getByHash(isA(String.class))).thenReturn(reviewInvite); ServiceResult<ReviewInviteResource> inviteServiceResult = service.openInvite("inviteHashExpired"); assertTrue(inviteServiceResult.isFailure()); assertTrue(inviteServiceResult.getFailure().is(new Error(ASSESSMENT_PANEL_INVITE_EXPIRED, "my competition"))); InOrder inOrder = inOrder(reviewInviteRepositoryMock); inOrder.verify(reviewInviteRepositoryMock).getByHash("inviteHashExpired"); inOrder.verifyNoMoreInteractions(); } |
ReviewInviteServiceImpl extends InviteService<ReviewInvite> implements ReviewInviteService { @Override public ServiceResult<Void> acceptInvite(String inviteHash) { return getParticipantByInviteHash(inviteHash) .andOnSuccess(ReviewInviteServiceImpl::accept) .andOnSuccess(this::assignAllPanelApplicationsToParticipant) .andOnSuccessReturnVoid(); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override @Transactional ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override @Transactional ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId,
Pageable pageable,
List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<ReviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<ReviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); } | @Test public void acceptInvite() { String openedInviteHash = "openedInviteHash"; Competition competition = newCompetition().build(); ReviewParticipant reviewParticipant = newReviewParticipant() .withInvite(newReviewInvite().withStatus(OPENED)) .withUser(newUser()) .withCompetition(competition) .build(); when(reviewParticipantRepositoryMock.getByInviteHash(openedInviteHash)).thenReturn(reviewParticipant); when(applicationRepositoryMock.findByCompetitionAndInAssessmentReviewPanelTrueAndApplicationProcessActivityState(competition, ApplicationState.SUBMITTED)).thenReturn(emptyList()); service.acceptInvite(openedInviteHash).getSuccess(); assertEquals(ParticipantStatus.ACCEPTED, reviewParticipant.getStatus()); InOrder inOrder = inOrder(reviewParticipantRepositoryMock, applicationRepositoryMock); inOrder.verify(reviewParticipantRepositoryMock).getByInviteHash(openedInviteHash); inOrder.verify(applicationRepositoryMock).findByCompetitionAndInAssessmentReviewPanelTrueAndApplicationProcessActivityState(competition, ApplicationState.SUBMITTED); inOrder.verifyNoMoreInteractions(); }
@Test public void acceptInvite_existingApplicationsOnPanel() { String openedInviteHash = "openedInviteHash"; Competition competition = newCompetition().build(); ReviewParticipant reviewParticipant = newReviewParticipant() .withInvite(newReviewInvite().withStatus(OPENED)) .withUser(newUser()) .withCompetition(competition) .build(); List<Application> applicationsOnPanel = newApplication().build(2); when(reviewParticipantRepositoryMock.getByInviteHash(openedInviteHash)).thenReturn(reviewParticipant); when(applicationRepositoryMock.findByCompetitionAndInAssessmentReviewPanelTrueAndApplicationProcessActivityState(competition, ApplicationState.SUBMITTED)).thenReturn(applicationsOnPanel); service.acceptInvite(openedInviteHash).getSuccess(); assertEquals(ParticipantStatus.ACCEPTED, reviewParticipant.getStatus()); InOrder inOrder = inOrder(reviewParticipantRepositoryMock, applicationRepositoryMock, reviewRepositoryMock); inOrder.verify(reviewParticipantRepositoryMock).getByInviteHash(openedInviteHash); inOrder.verify(applicationRepositoryMock).findByCompetitionAndInAssessmentReviewPanelTrueAndApplicationProcessActivityState(competition, ApplicationState.SUBMITTED); inOrder.verify(reviewRepositoryMock, times(2)).save(any(Review.class)); inOrder.verifyNoMoreInteractions(); } |
SetupStatusServiceImpl implements SetupStatusService { @Override public ServiceResult<List<SetupStatusResource>> findByTargetClassNameAndTargetId(String targetClassName, Long targetId) { return serviceSuccess((List<SetupStatusResource>) setupStatusMapper .mapToResource(setupStatusRepository .findByTargetClassNameAndTargetId(targetClassName, targetId))); } @Override ServiceResult<List<SetupStatusResource>> findByTargetClassNameAndTargetId(String targetClassName, Long targetId); @Override ServiceResult<List<SetupStatusResource>> findByTargetClassNameAndTargetIdAndParentId(String targetClassName, Long targetId, Long parentId); @Override ServiceResult<List<SetupStatusResource>> findByClassNameAndParentId(String className, Long parentId); @Override ServiceResult<SetupStatusResource> findSetupStatus(String className, Long classPk); @Override ServiceResult<SetupStatusResource> findSetupStatusAndTarget(String className, Long classPk, String targetClassName, Long targetId); @Override ServiceResult<SetupStatusResource> saveSetupStatus(SetupStatusResource setupStatusResource); } | @Test public void testFindByTargetIdAndTargetClassName() { final String targetClassName = Question.class.getName(); final Long targetId = 23L; final List<SetupStatus> setupStatus = newSetupStatus() .withId(1L) .withTargetId(targetId) .withTargetClassName(targetClassName) .build(1); final List<SetupStatusResource> setupStatusResource = newSetupStatusResource() .withId(1L) .withTargetId(targetId) .withTargetClassName(targetClassName) .build(1); when(setupStatusRepository.findByTargetClassNameAndTargetId(targetClassName, targetId)).thenReturn(setupStatus); when(setupStatusMapper.mapToResource(setupStatus)).thenReturn(setupStatusResource); ServiceResult<List<SetupStatusResource>> serviceResult = service.findByTargetClassNameAndTargetId(targetClassName, targetId); assertTrue(serviceResult.isSuccess()); assertEquals(setupStatusResource, serviceResult.getSuccess()); } |
SetupStatusServiceImpl implements SetupStatusService { @Override public ServiceResult<List<SetupStatusResource>> findByClassNameAndParentId(String className, Long parentId) { return serviceSuccess((List<SetupStatusResource>) setupStatusMapper .mapToResource(setupStatusRepository .findByClassNameAndParentId(className, parentId))); } @Override ServiceResult<List<SetupStatusResource>> findByTargetClassNameAndTargetId(String targetClassName, Long targetId); @Override ServiceResult<List<SetupStatusResource>> findByTargetClassNameAndTargetIdAndParentId(String targetClassName, Long targetId, Long parentId); @Override ServiceResult<List<SetupStatusResource>> findByClassNameAndParentId(String className, Long parentId); @Override ServiceResult<SetupStatusResource> findSetupStatus(String className, Long classPk); @Override ServiceResult<SetupStatusResource> findSetupStatusAndTarget(String className, Long classPk, String targetClassName, Long targetId); @Override ServiceResult<SetupStatusResource> saveSetupStatus(SetupStatusResource setupStatusResource); } | @Test public void testFindByTargetClassNameAndParentId() { final String className = Competition.class.getName(); final Long parentId = 8234L; List<SetupStatus> setupStatuses = newSetupStatus() .withId(1L, 2L) .withTargetClassName(className, className) .withParentId(parentId, parentId) .build(2); List<SetupStatusResource> setupStatusResources = newSetupStatusResource() .withId(1L, 2L) .withTargetClassName(className, className) .withParentId(parentId, parentId) .build(2); when(setupStatusRepository.findByClassNameAndParentId(className, parentId)).thenReturn(setupStatuses); when(setupStatusMapper.mapToResource(setupStatuses)).thenReturn(setupStatusResources); ServiceResult<List<SetupStatusResource>> serviceResult = service.findByClassNameAndParentId(className, parentId); assertTrue(serviceResult.isSuccess()); assertEquals(setupStatusResources, serviceResult.getSuccess()); } |
SetupStatusServiceImpl implements SetupStatusService { @Override public ServiceResult<List<SetupStatusResource>> findByTargetClassNameAndTargetIdAndParentId(String targetClassName, Long targetId, Long parentId) { return serviceSuccess((List<SetupStatusResource>) setupStatusMapper .mapToResource(setupStatusRepository .findByTargetClassNameAndTargetIdAndParentId(targetClassName, targetId, parentId))); } @Override ServiceResult<List<SetupStatusResource>> findByTargetClassNameAndTargetId(String targetClassName, Long targetId); @Override ServiceResult<List<SetupStatusResource>> findByTargetClassNameAndTargetIdAndParentId(String targetClassName, Long targetId, Long parentId); @Override ServiceResult<List<SetupStatusResource>> findByClassNameAndParentId(String className, Long parentId); @Override ServiceResult<SetupStatusResource> findSetupStatus(String className, Long classPk); @Override ServiceResult<SetupStatusResource> findSetupStatusAndTarget(String className, Long classPk, String targetClassName, Long targetId); @Override ServiceResult<SetupStatusResource> saveSetupStatus(SetupStatusResource setupStatusResource); } | @Test public void testFindByTargetClassNameAndTargetIdAndParentId() { final String targetClassName = Competition.class.getName(); final Long targetId = 2314L; final Long parentId = 8234L; List<SetupStatus> setupStatuses = newSetupStatus() .withId(1L, 2L) .withTargetId(targetId, targetId) .withTargetClassName(targetClassName, targetClassName) .withParentId(parentId, parentId) .build(2); List<SetupStatusResource> setupStatusResources = newSetupStatusResource() .withId(1L, 2L) .withTargetId(targetId, targetId) .withTargetClassName(targetClassName, targetClassName) .withParentId(parentId, parentId) .build(2); when(setupStatusRepository.findByTargetClassNameAndTargetIdAndParentId(targetClassName, targetId, parentId)).thenReturn(setupStatuses); when(setupStatusMapper.mapToResource(setupStatuses)).thenReturn(setupStatusResources); ServiceResult<List<SetupStatusResource>> serviceResult = service.findByTargetClassNameAndTargetIdAndParentId(targetClassName, targetId, parentId); assertTrue(serviceResult.isSuccess()); assertEquals(setupStatusResources, serviceResult.getSuccess()); } |
SetupStatusServiceImpl implements SetupStatusService { @Override public ServiceResult<SetupStatusResource> findSetupStatus(String className, Long classPk) { Optional<SetupStatus> resultOpt = setupStatusRepository.findByClassNameAndClassPk(className, classPk); if(resultOpt.isPresent()) { return serviceSuccess(setupStatusMapper.mapToResource(resultOpt.get())); } return serviceFailure(notFoundError(SetupStatus.class, classPk, className)); } @Override ServiceResult<List<SetupStatusResource>> findByTargetClassNameAndTargetId(String targetClassName, Long targetId); @Override ServiceResult<List<SetupStatusResource>> findByTargetClassNameAndTargetIdAndParentId(String targetClassName, Long targetId, Long parentId); @Override ServiceResult<List<SetupStatusResource>> findByClassNameAndParentId(String className, Long parentId); @Override ServiceResult<SetupStatusResource> findSetupStatus(String className, Long classPk); @Override ServiceResult<SetupStatusResource> findSetupStatusAndTarget(String className, Long classPk, String targetClassName, Long targetId); @Override ServiceResult<SetupStatusResource> saveSetupStatus(SetupStatusResource setupStatusResource); } | @Test public void findSetupStatus() { final Long classPk = 32L; final String className = Question.class.getName(); final SetupStatus setupStatus = newSetupStatus() .withId(1L) .withCompleted(Boolean.FALSE) .withClassPk(classPk) .withClassName(className) .build(); final SetupStatusResource setupStatusResource = newSetupStatusResource() .withId(1L) .withCompleted(Boolean.FALSE) .withClassPk(classPk) .withClassName(className) .build(); when(setupStatusRepository.findByClassNameAndClassPk(className, classPk)).thenReturn(Optional.of(setupStatus)); when(setupStatusMapper.mapToResource(setupStatus)).thenReturn(setupStatusResource); ServiceResult<SetupStatusResource> serviceResult = service.findSetupStatus(className, classPk); assertTrue(serviceResult.isSuccess()); assertEquals(setupStatusResource, serviceResult.getSuccess()); }
@Test public void findSetupStatusNotFound() { final Long classPk = 32L; final String className = Question.class.getName(); when(setupStatusRepository.findByClassNameAndClassPk(className, classPk)).thenReturn(Optional.empty()); ServiceResult<SetupStatusResource> serviceResult = service.findSetupStatus(className, classPk); assertTrue(serviceResult.isFailure()); } |
SetupStatusServiceImpl implements SetupStatusService { @Override public ServiceResult<SetupStatusResource> findSetupStatusAndTarget(String className, Long classPk, String targetClassName, Long targetId) { Optional<SetupStatus> resultOpt = setupStatusRepository.findByClassNameAndClassPkAndTargetClassNameAndTargetId(className, classPk, targetClassName, targetId); if(resultOpt.isPresent()) { return serviceSuccess(setupStatusMapper.mapToResource(resultOpt.get())); } return serviceFailure(notFoundError(SetupStatus.class, classPk, className)); } @Override ServiceResult<List<SetupStatusResource>> findByTargetClassNameAndTargetId(String targetClassName, Long targetId); @Override ServiceResult<List<SetupStatusResource>> findByTargetClassNameAndTargetIdAndParentId(String targetClassName, Long targetId, Long parentId); @Override ServiceResult<List<SetupStatusResource>> findByClassNameAndParentId(String className, Long parentId); @Override ServiceResult<SetupStatusResource> findSetupStatus(String className, Long classPk); @Override ServiceResult<SetupStatusResource> findSetupStatusAndTarget(String className, Long classPk, String targetClassName, Long targetId); @Override ServiceResult<SetupStatusResource> saveSetupStatus(SetupStatusResource setupStatusResource); } | @Test public void findSetupStatusAndTarget() { final Long classPk = 32L; final String className = Question.class.getName(); final Long targetId = 492L; final String targetClassName = Competition.class.getName(); final SetupStatus setupStatus = newSetupStatus() .withId(1L) .withCompleted(Boolean.FALSE) .withClassPk(classPk) .withClassName(className) .withTargetClassName(targetClassName) .withTargetId(targetId) .build(); final SetupStatusResource setupStatusResource = newSetupStatusResource() .withId(1L) .withCompleted(Boolean.FALSE) .withClassPk(classPk) .withClassName(className) .withTargetClassName(targetClassName) .withTargetId(targetId) .build(); when(setupStatusRepository.findByClassNameAndClassPkAndTargetClassNameAndTargetId(className, classPk, targetClassName, targetId)) .thenReturn(Optional.of(setupStatus)); when(setupStatusMapper.mapToResource(setupStatus)).thenReturn(setupStatusResource); ServiceResult<SetupStatusResource> serviceResult = service.findSetupStatusAndTarget(className, classPk, targetClassName, targetId); assertTrue(serviceResult.isSuccess()); assertEquals(setupStatusResource, serviceResult.getSuccess()); }
@Test public void findSetupStatusAndTargetNotFound() { final Long classPk = 32L; final String className = Question.class.getName(); final Long targetId = 492L; final String targetClassName = Competition.class.getName(); when(setupStatusRepository.findByClassNameAndClassPkAndTargetClassNameAndTargetId(className, classPk, targetClassName, targetId)) .thenReturn(Optional.empty()); ServiceResult<SetupStatusResource> serviceResult = service.findSetupStatusAndTarget(className, classPk, targetClassName, targetId); assertTrue(serviceResult.isFailure()); } |
SetupStatusServiceImpl implements SetupStatusService { @Override public ServiceResult<SetupStatusResource> saveSetupStatus(SetupStatusResource setupStatusResource) { SetupStatus setupStatusToSave = setupStatusMapper.mapToDomain(setupStatusResource); return serviceSuccess( setupStatusMapper .mapToResource(setupStatusRepository .save(setupStatusToSave))); } @Override ServiceResult<List<SetupStatusResource>> findByTargetClassNameAndTargetId(String targetClassName, Long targetId); @Override ServiceResult<List<SetupStatusResource>> findByTargetClassNameAndTargetIdAndParentId(String targetClassName, Long targetId, Long parentId); @Override ServiceResult<List<SetupStatusResource>> findByClassNameAndParentId(String className, Long parentId); @Override ServiceResult<SetupStatusResource> findSetupStatus(String className, Long classPk); @Override ServiceResult<SetupStatusResource> findSetupStatusAndTarget(String className, Long classPk, String targetClassName, Long targetId); @Override ServiceResult<SetupStatusResource> saveSetupStatus(SetupStatusResource setupStatusResource); } | @Test public void testSaveSetupStatus() { final Long classPk = 32L; final String className = Question.class.getName(); final SetupStatus setupStatus = newSetupStatus() .withId(1L) .withCompleted(Boolean.TRUE) .withClassPk(classPk) .withClassName(className) .build(); final SetupStatusResource setupStatusResource = newSetupStatusResource() .withId(1L) .withCompleted(Boolean.TRUE) .withClassPk(classPk) .withClassName(className) .build(); when(setupStatusMapper.mapToDomain(setupStatusResource)).thenReturn(setupStatus); when(setupStatusMapper.mapToResource(setupStatus)).thenReturn(setupStatusResource); when(setupStatusRepository.save(setupStatus)).thenReturn(setupStatus); ServiceResult<SetupStatusResource> serviceResult = service.saveSetupStatus(setupStatusResource); assertTrue(serviceResult.isSuccess()); assertEquals(setupStatusResource, serviceResult.getSuccess()); } |
ByMediaTypeStringsMediaTypesGenerator implements MediaTypesGenerator<List<String>> { @Override public List<MediaType> apply(List<String> validMediaTypes) { return simpleMap(validMediaTypes, MediaType::valueOf); } @Override List<MediaType> apply(List<String> validMediaTypes); } | @Test public void testApply() { ByMediaTypeStringsMediaTypesGenerator generator = new ByMediaTypeStringsMediaTypesGenerator(); List<MediaType> mediaTypes = generator.apply(asList("application/pdf", "application/json")); assertArrayEquals(new MediaType[] {MediaType.APPLICATION_PDF, MediaType.APPLICATION_JSON}, mediaTypes.toArray()); } |
FileTypeController { @GetMapping("/{id}") public RestResult<FileTypeResource> findOne(@PathVariable("id") final long id) { return fileTypeService.findOne(id).toGetResponse(); } @GetMapping("/{id}") RestResult<FileTypeResource> findOne(@PathVariable("id") final long id); @GetMapping("/find-by-name/{name}") RestResult<FileTypeResource> findByName(@PathVariable("name") final String name); } | @Test public void findOne() throws Exception { long fileTypeId = 1L; FileTypeResource fileTypeResource = FileTypeResourceBuilder.newFileTypeResource() .withName("Spreadsheet") .withExtension("xls, xlsx") .build(); when(fileTypeServiceMock.findOne(fileTypeId)).thenReturn(serviceSuccess(fileTypeResource)); mockMvc.perform(get("/file/file-type/{fileTypeId}", fileTypeId) ) .andExpect(status().isOk()) .andExpect(content().json(toJson(fileTypeResource))); verify(fileTypeServiceMock, only()).findOne(fileTypeId); } |
FileTypeController { @GetMapping("/find-by-name/{name}") public RestResult<FileTypeResource> findByName(@PathVariable("name") final String name) { return fileTypeService.findByName(name).toGetResponse(); } @GetMapping("/{id}") RestResult<FileTypeResource> findOne(@PathVariable("id") final long id); @GetMapping("/find-by-name/{name}") RestResult<FileTypeResource> findByName(@PathVariable("name") final String name); } | @Test public void findByName() throws Exception { String name = "Spreadsheet"; FileTypeResource fileTypeResource = FileTypeResourceBuilder.newFileTypeResource() .withName("Spreadsheet") .withExtension("xls, xlsx") .build(); when(fileTypeServiceMock.findByName(name)).thenReturn(serviceSuccess(fileTypeResource)); mockMvc.perform(get("/file/file-type/find-by-name/{name}", name) ) .andExpect(status().isOk()) .andExpect(content().json(toJson(fileTypeResource))); verify(fileTypeServiceMock, only()).findByName(name); } |
UserPermissionRules { @PermissionRule(value = "READ", description = "The user, as well as Comp Admin and Exec can read the user's profile status") public boolean usersAndCompAdminCanViewProfileStatus(UserProfileStatusResource profileStatus, UserResource user) { return profileStatus.getUser() == user.getId() || isCompAdmin(user); } @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "An internal user can invite a monitoring officer and create the pending user associated.") boolean compAdminProjectFinanceCanCreateMonitoringOfficer(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserRegistrationResource userToCreate, UserResource user); @PermissionRule(value = "VERIFY", description = "A System Registration User can send a new User a verification link by e-mail") boolean systemRegistrationUserCanSendUserVerificationEmail(UserResource userToSendVerificationEmail, UserResource user); @PermissionRule(value = "READ", description = "Any user can view themselves") boolean anyUserCanViewThemselves(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Internal users can view everyone") boolean internalUsersCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can view users in competitions they are assigned to") boolean stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Competition finance users can view users in competitions they are assigned to") boolean competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can view users in projects they are assigned to") boolean monitoringOfficersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ_USER_ORGANISATION", description = "Internal support users can view all users and associated organisations") boolean internalUsersCanViewUserOrganisation(UserOrganisationResource userToView, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "IFS admins can update all users email addresses") boolean ifsAdminCanUpdateAllEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "Support users can update external users email addresses ") boolean supportCanUpdateExternalUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "System Maintenance update all users email addresses") boolean systemMaintenanceUserCanUpdateUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ_INTERNAL", description = "Administrators can view internal users") boolean internalUsersCanViewEveryone(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Support users and administrators can view external users") boolean supportUsersCanViewExternalUsers(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "The System Registration user can view everyone") boolean systemRegistrationUserCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Comp admins and project finance can view assessors") boolean compAdminAndProjectFinanceCanViewAssessors(UserPageResource usersToView, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewOtherConsortiumMembers(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewConsortiumUsersOnApplicationsTheyAreAssessing(UserResource userToView, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "A User should be able to change their own password") boolean usersCanChangeTheirOwnPassword(UserResource userToUpdate, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "The System Registration user should be able to change passwords on behalf of other Users") boolean systemRegistrationUserCanChangePasswordsForUsers(UserResource userToUpdate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A System Registration User can activate Users") boolean systemRegistrationUserCanActivateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "UPDATE", description = "A User can update their own profile") boolean usersCanUpdateTheirOwnProfiles(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE", description = "An admin user can update user details to assign monitoring officers") boolean adminsCanUpdateUserDetails(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile skills") boolean usersCanViewTheirOwnProfileSkills(ProfileSkillsResource profileSkills, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile agreement") boolean usersCanViewTheirOwnProfileAgreement(ProfileAgreementResource profileAgreementResource, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own affiliations") boolean usersCanViewTheirOwnAffiliations(AffiliationResource affiliation, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A user can read their own profile") boolean usersCanViewTheirOwnProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A ifs admin user can read any user's profile") boolean ifsAdminCanViewAnyUsersProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as Comp Admin and Exec can read the user's profile status") boolean usersAndCompAdminCanViewProfileStatus(UserProfileStatusResource profileStatus, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own role") boolean usersCanViewTheirOwnProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the process role of others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewTheProcessRolesOfOtherConsortiumMembers(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Project managers and partners can view the process role for the same organisation") boolean projectPartnersCanViewTheProcessRolesWithinSameApplication(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as internal users can read the user's process role") boolean usersAndInternalUsersCanViewProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the process roles of members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewTheProcessRolesOfConsortiumUsersOnApplicationsTheyAreAssessing(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "CHECK_USER_APPLICATION", description = "The user can check if they have an application for the competition") boolean userCanCheckTheyHaveApplicationForCompetition(UserResource userToCheck, UserResource user); @PermissionRule(value = "EDIT_INTERNAL_USER", description = "Only an IFS Administrator can edit an internal user") boolean ifsAdminCanEditInternalUser(final UserResource userToEdit, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "IFS Administrator can deactivate Users") boolean ifsAdminCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "A Support user can deactivate external Users") boolean supportUserCanDeactivateExternalUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "System Maintenance can deactivate Users") boolean systemMaintenanceUserCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "IFS Administrator can reactivate Users") boolean ifsAdminCanReactivateUsers(UserResource userToReactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A Support user can reactivate external Users") boolean supportUserCanReactivateExternalUsers(UserResource userToActivate, UserResource user); @PermissionRule(value = "AGREE_TERMS", description = "A user can accept the site terms and conditions") boolean usersCanAgreeSiteTermsAndConditions(UserResource userToUpdate, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An assessor can request applicant role") boolean assessorCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant monitoring officer role") boolean isGrantingMonitoringOfficerRoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant a KTA role") boolean isGrantingKTARoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An stakeholder can request applicant role") boolean stakeholderCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An monitoring officer can request applicant role") boolean monitoringOfficerCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "CAN_VIEW_OWN_DASHBOARD", description = "User is requesting own dashboard") boolean isViewingOwnDashboard(UserResource userToView, UserResource user); } | @Test public void usersCanViewTheirOwnProfileStatus() { UserResource user = newUserResource().build(); UserProfileStatusResource userProfileStatus = newUserProfileStatusResource().withUser(user.getId()).build(); assertTrue(rules.usersAndCompAdminCanViewProfileStatus(userProfileStatus, user)); }
@Test public void usersCanViewTheirOwnProfileStatusButNotAnotherUsersProfileStatus() { UserResource user = newUserResource().withId(1L).build(); UserProfileStatusResource anotherUsersProfileStatus = newUserProfileStatusResource().withUser(2L).build(); assertFalse(rules.usersAndCompAdminCanViewProfileStatus(anotherUsersProfileStatus, user)); }
@Test public void compAdminCanViewUserProfileStatus() { UserResource user = newUserResource().build(); UserProfileStatusResource userProfileStatus = newUserProfileStatusResource().withUser(user.getId()).build(); assertTrue(rules.usersAndCompAdminCanViewProfileStatus(userProfileStatus, compAdminUser())); } |
FileTypeServiceImpl extends BaseTransactionalService implements FileTypeService { @Override @Transactional public ServiceResult<FileTypeResource> findOne(long id) { return find(fileTypeRepository.findById(id), notFoundError(FileType.class, id)) .andOnSuccessReturn(fileType -> fileTypeMapper.mapToResource(fileType)); } @Override @Transactional ServiceResult<FileTypeResource> findOne(long id); @Override @Transactional ServiceResult<FileTypeResource> findByName(String name); } | @Test public void findOne() { Long fileTypeId = 1L; FileType fileType = new FileType(); FileTypeResource fileTypeResource = new FileTypeResource(); when(fileTypeRepositoryMock.findById(fileTypeId)).thenReturn(Optional.of(fileType)); when(fileTypeMapperMock.mapToResource(fileType)).thenReturn(fileTypeResource); ServiceResult<FileTypeResource> result = service.findOne(fileTypeId); assertTrue(result.isSuccess()); assertEquals(fileTypeResource, result.getSuccess()); verify(fileTypeRepositoryMock).findById(fileTypeId); } |
FileTypeServiceImpl extends BaseTransactionalService implements FileTypeService { @Override @Transactional public ServiceResult<FileTypeResource> findByName(String name) { return find(fileTypeRepository.findByName(name), notFoundError(FileType.class, name)) .andOnSuccessReturn(fileType -> fileTypeMapper.mapToResource(fileType)); } @Override @Transactional ServiceResult<FileTypeResource> findOne(long id); @Override @Transactional ServiceResult<FileTypeResource> findByName(String name); } | @Test public void findByName() { String name = "name"; FileType fileType = new FileType(); FileTypeResource fileTypeResource = new FileTypeResource(); when(fileTypeRepositoryMock.findByName(name)).thenReturn(fileType); when(fileTypeMapperMock.mapToResource(fileType)).thenReturn(fileTypeResource); ServiceResult<FileTypeResource> result = service.findByName(name); assertTrue(result.isSuccess()); assertEquals(fileTypeResource, result.getSuccess()); verify(fileTypeRepositoryMock).findByName(name); } |
FinanceReviewerController { @GetMapping("/find-all") public RestResult<List<SimpleUserResource>> findAll() { return financeReviewerService.findFinanceUsers().toGetResponse(); } @GetMapping("/find-all") RestResult<List<SimpleUserResource>> findAll(); @GetMapping(params = "projectId") RestResult<SimpleUserResource> getFinanceReviewer(@RequestParam long projectId); @PostMapping("/{userId}/assign/{projectId}") RestResult<Void> assignFinanceReviewer(@PathVariable long userId, @PathVariable long projectId); } | @Test public void findAll() throws Exception { List<SimpleUserResource> expected = newSimpleUserResource().build(1); when(financeReviewerService.findFinanceUsers()).thenReturn(serviceSuccess(expected)); mockMvc.perform(get("/finance-reviewer/find-all")) .andExpect(status().isOk()) .andExpect(content().json(toJson(expected))); verify(financeReviewerService).findFinanceUsers(); } |
FinanceReviewerController { @PostMapping("/{userId}/assign/{projectId}") public RestResult<Void> assignFinanceReviewer(@PathVariable long userId, @PathVariable long projectId) { return financeReviewerService.assignFinanceReviewer(userId, projectId).toPostResponse(); } @GetMapping("/find-all") RestResult<List<SimpleUserResource>> findAll(); @GetMapping(params = "projectId") RestResult<SimpleUserResource> getFinanceReviewer(@RequestParam long projectId); @PostMapping("/{userId}/assign/{projectId}") RestResult<Void> assignFinanceReviewer(@PathVariable long userId, @PathVariable long projectId); } | @Test public void assignProjectToMonitoringOfficer() throws Exception { long userId = 11; long projectId = 13; when(financeReviewerService.assignFinanceReviewer(userId, projectId)).thenReturn(serviceSuccess(1L)); mockMvc.perform(MockMvcRequestBuilders.post("/finance-reviewer/{userId}/assign/{projectId}", userId, projectId)) .andExpect(status().is2xxSuccessful()); verify(financeReviewerService, only()).assignFinanceReviewer(userId, projectId); } |
FinanceReviewerServiceImpl extends BaseTransactionalService implements FinanceReviewerService { @Override public ServiceResult<List<SimpleUserResource>> findFinanceUsers() { return serviceSuccess(userRepository.findByRolesAndStatusIn(PROJECT_FINANCE, EnumSet.of(ACTIVE)) .stream() .map(user -> new SimpleUserResource(user.getId(), user.getFirstName(), user.getLastName(), user.getEmail())) .collect(Collectors.toList())); } @Override @Transactional ServiceResult<Long> assignFinanceReviewer(long financeReviewerUserId, long projectId); @Override ServiceResult<List<SimpleUserResource>> findFinanceUsers(); @Override ServiceResult<SimpleUserResource> getFinanceReviewerForProject(long projectId); } | @Test public void findAll() { User user = newUser().build(); when(userRepository.findByRolesAndStatusIn(Role.PROJECT_FINANCE, EnumSet.of(ACTIVE))).thenReturn(singletonList(user)); List<SimpleUserResource> result = service.findFinanceUsers().getSuccess(); assertEquals(result.size(), 1); assertEquals(result.get(0).getId(), (long) user.getId()); } |
FinanceReviewerServiceImpl extends BaseTransactionalService implements FinanceReviewerService { @Override public ServiceResult<SimpleUserResource> getFinanceReviewerForProject(long projectId) { return getProject(projectId) .andOnSuccess(project -> find(project.getFinanceReviewer(), notFoundError(FinanceReviewer.class, projectId)) .andOnSuccessReturn(reviewer -> simpleUserResourceFromUser(reviewer.getUser()))); } @Override @Transactional ServiceResult<Long> assignFinanceReviewer(long financeReviewerUserId, long projectId); @Override ServiceResult<List<SimpleUserResource>> findFinanceUsers(); @Override ServiceResult<SimpleUserResource> getFinanceReviewerForProject(long projectId); } | @Test public void getFinanceReviewerForProject() { long projectId = 1L; User user = newUser().build(); Project project = newProject() .withId(projectId) .withFinanceReviewer(newFinanceReviewer() .withUser(user) .build()) .build(); when(projectRepository.findById(projectId)).thenReturn(Optional.of(project)); SimpleUserResource result = service.getFinanceReviewerForProject(projectId).getSuccess(); assertEquals(result.getId(), (long) user.getId()); } |
FinanceReviewerServiceImpl extends BaseTransactionalService implements FinanceReviewerService { @Override @Transactional public ServiceResult<Long> assignFinanceReviewer(long financeReviewerUserId, long projectId) { return getProjectFinanceUser(financeReviewerUserId) .andOnSuccess(user -> getProject(projectId) .andOnSuccessReturn((project) -> { if (project.getFinanceReviewer() != null) { project.getFinanceReviewer().setUser(user); return project.getFinanceReviewer().getId(); } else { FinanceReviewer reviewer = financeReviewerRepository.save(new FinanceReviewer(user, project)); return reviewer.getId(); } })); } @Override @Transactional ServiceResult<Long> assignFinanceReviewer(long financeReviewerUserId, long projectId); @Override ServiceResult<List<SimpleUserResource>> findFinanceUsers(); @Override ServiceResult<SimpleUserResource> getFinanceReviewerForProject(long projectId); } | @Test public void assignFinanceReviewer() { long projectId = 1L; User existing = newUser().build(); User financeReviewerUser = newUser().build(); Project project = newProject() .withId(projectId) .withFinanceReviewer(newFinanceReviewer() .withUser(existing) .build()) .build(); when(projectRepository.findById(projectId)).thenReturn(Optional.of(project)); when(userRepository.findByIdAndRoles(financeReviewerUser.getId(), Role.PROJECT_FINANCE)).thenReturn(Optional.of(financeReviewerUser)); service.assignFinanceReviewer(financeReviewerUser.getId(), projectId).getSuccess(); assertEquals(project.getFinanceReviewer().getUser().getId(), financeReviewerUser.getId()); } |
StatusPermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_TEAM_STATUS", description = "All partners can view team status") public boolean partnersCanViewTeamStatus(ProjectResource project, UserResource user) { return isPartner(project.getId(), user.getId()); } @PermissionRule( value = "VIEW_TEAM_STATUS", description = "All partners can view team status") boolean partnersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Internal users can see a team's status") boolean internalUsersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Stakeholders can see a team's status for a project on their competitions") boolean stakeholdersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Monitoring officers can see a team's status for a project") boolean monitoringOfficersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "All partners can view the project status") boolean partnersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "Internal users can see the project status") boolean internalUsersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of the competition") boolean internalAdminTeamCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Support users should be able to access the current status of the competition") boolean supportCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Innovation lead users should be able to access current status of competition that are assigned to them") boolean assignedInnovationLeadCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Stakeholders should be able to access current status of competition that are assigned to them") boolean assignedStakeholderCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Competition finance users should be able to access current status of competition that are assigned to them") boolean assignedCompetitionFinanceCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of project") boolean internalAdminTeamCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Support users should be able to view current status of project") boolean supportCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Innovation lead users should be able to view current status of project from competition assigned to them") boolean assignedInnovationLeadCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Stakeholders should be able to view current status of project from competition assigned to them") boolean assignedStakeholderCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Competition finance users should be able to view current status of project from competition assigned to them") boolean assignedCompetitionFinanceUsersCanViewProjectStatus(ProjectResource project, UserResource user); } | @Test public void partnersCanViewTeamStatus() { setupUserAsPartner(project, user); assertTrue(rules.partnersCanViewTeamStatus(project, user)); }
@Test public void nonPartnersCannotViewTeamStatus() { setupUserNotAsPartner(project, user); assertFalse(rules.partnersCanViewTeamStatus(project, user)); } |
StatusPermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Internal users can see a team's status") public boolean internalUsersCanViewTeamStatus(ProjectResource project, UserResource user) { return isInternal(user); } @PermissionRule( value = "VIEW_TEAM_STATUS", description = "All partners can view team status") boolean partnersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Internal users can see a team's status") boolean internalUsersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Stakeholders can see a team's status for a project on their competitions") boolean stakeholdersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Monitoring officers can see a team's status for a project") boolean monitoringOfficersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "All partners can view the project status") boolean partnersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "Internal users can see the project status") boolean internalUsersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of the competition") boolean internalAdminTeamCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Support users should be able to access the current status of the competition") boolean supportCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Innovation lead users should be able to access current status of competition that are assigned to them") boolean assignedInnovationLeadCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Stakeholders should be able to access current status of competition that are assigned to them") boolean assignedStakeholderCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Competition finance users should be able to access current status of competition that are assigned to them") boolean assignedCompetitionFinanceCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of project") boolean internalAdminTeamCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Support users should be able to view current status of project") boolean supportCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Innovation lead users should be able to view current status of project from competition assigned to them") boolean assignedInnovationLeadCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Stakeholders should be able to view current status of project from competition assigned to them") boolean assignedStakeholderCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Competition finance users should be able to view current status of project from competition assigned to them") boolean assignedCompetitionFinanceUsersCanViewProjectStatus(ProjectResource project, UserResource user); } | @Test public void internalUsersCanViewTeamStatus() { assertTrue(rules.internalUsersCanViewTeamStatus(project, compAdminUser())); assertTrue(rules.internalUsersCanViewTeamStatus(project, projectFinanceUser())); } |
StatusPermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_STATUS", description = "All partners can view the project status") public boolean partnersCanViewStatus(ProjectResource project, UserResource user) { return isPartner(project.getId(), user.getId()); } @PermissionRule( value = "VIEW_TEAM_STATUS", description = "All partners can view team status") boolean partnersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Internal users can see a team's status") boolean internalUsersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Stakeholders can see a team's status for a project on their competitions") boolean stakeholdersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Monitoring officers can see a team's status for a project") boolean monitoringOfficersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "All partners can view the project status") boolean partnersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "Internal users can see the project status") boolean internalUsersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of the competition") boolean internalAdminTeamCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Support users should be able to access the current status of the competition") boolean supportCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Innovation lead users should be able to access current status of competition that are assigned to them") boolean assignedInnovationLeadCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Stakeholders should be able to access current status of competition that are assigned to them") boolean assignedStakeholderCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Competition finance users should be able to access current status of competition that are assigned to them") boolean assignedCompetitionFinanceCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of project") boolean internalAdminTeamCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Support users should be able to view current status of project") boolean supportCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Innovation lead users should be able to view current status of project from competition assigned to them") boolean assignedInnovationLeadCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Stakeholders should be able to view current status of project from competition assigned to them") boolean assignedStakeholderCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Competition finance users should be able to view current status of project from competition assigned to them") boolean assignedCompetitionFinanceUsersCanViewProjectStatus(ProjectResource project, UserResource user); } | @Test public void partnersCanViewStatus() { setupUserAsPartner(project, user); assertTrue(rules.partnersCanViewStatus(project, user)); }
@Test public void nonPartnersCannotViewStatus() { setupUserNotAsPartner(project, user); assertFalse(rules.partnersCanViewStatus(project, user)); } |
StatusPermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_STATUS", description = "Internal users can see the project status") public boolean internalUsersCanViewStatus(ProjectResource project, UserResource user) { return isInternal(user); } @PermissionRule( value = "VIEW_TEAM_STATUS", description = "All partners can view team status") boolean partnersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Internal users can see a team's status") boolean internalUsersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Stakeholders can see a team's status for a project on their competitions") boolean stakeholdersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Monitoring officers can see a team's status for a project") boolean monitoringOfficersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "All partners can view the project status") boolean partnersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "Internal users can see the project status") boolean internalUsersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of the competition") boolean internalAdminTeamCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Support users should be able to access the current status of the competition") boolean supportCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Innovation lead users should be able to access current status of competition that are assigned to them") boolean assignedInnovationLeadCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Stakeholders should be able to access current status of competition that are assigned to them") boolean assignedStakeholderCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Competition finance users should be able to access current status of competition that are assigned to them") boolean assignedCompetitionFinanceCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of project") boolean internalAdminTeamCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Support users should be able to view current status of project") boolean supportCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Innovation lead users should be able to view current status of project from competition assigned to them") boolean assignedInnovationLeadCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Stakeholders should be able to view current status of project from competition assigned to them") boolean assignedStakeholderCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Competition finance users should be able to view current status of project from competition assigned to them") boolean assignedCompetitionFinanceUsersCanViewProjectStatus(ProjectResource project, UserResource user); } | @Test public void internalUsersCanViewStatus() { allGlobalRoleUsers.forEach(user -> { if (isInternal(user)) { assertTrue(rules.internalUsersCanViewStatus(newProjectResource().build(), user)); } else { assertFalse(rules.internalUsersCanViewStatus(newProjectResource().build(), user)); } }); } |
StatusPermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Stakeholders can see a team's status for a project on their competitions") public boolean stakeholdersCanViewTeamStatus(ProjectResource project, UserResource user) { return userIsStakeholderInCompetition(project.getCompetition(), user.getId()); } @PermissionRule( value = "VIEW_TEAM_STATUS", description = "All partners can view team status") boolean partnersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Internal users can see a team's status") boolean internalUsersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Stakeholders can see a team's status for a project on their competitions") boolean stakeholdersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Monitoring officers can see a team's status for a project") boolean monitoringOfficersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "All partners can view the project status") boolean partnersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "Internal users can see the project status") boolean internalUsersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of the competition") boolean internalAdminTeamCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Support users should be able to access the current status of the competition") boolean supportCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Innovation lead users should be able to access current status of competition that are assigned to them") boolean assignedInnovationLeadCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Stakeholders should be able to access current status of competition that are assigned to them") boolean assignedStakeholderCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Competition finance users should be able to access current status of competition that are assigned to them") boolean assignedCompetitionFinanceCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of project") boolean internalAdminTeamCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Support users should be able to view current status of project") boolean supportCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Innovation lead users should be able to view current status of project from competition assigned to them") boolean assignedInnovationLeadCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Stakeholders should be able to view current status of project from competition assigned to them") boolean assignedStakeholderCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Competition finance users should be able to view current status of project from competition assigned to them") boolean assignedCompetitionFinanceUsersCanViewProjectStatus(ProjectResource project, UserResource user); } | @Test public void stakeholdersCanViewTeamStatus() { ProjectResource project = newProjectResource() .withCompetition(competition.getId()) .build(); when(stakeholderRepository.existsByCompetitionIdAndUserId(competition.getId(), stakeholderUserResourceOnCompetition.getId())).thenReturn(true); assertTrue(rules.stakeholdersCanViewTeamStatus(project, stakeholderUserResourceOnCompetition)); allInternalUsers.forEach(user -> assertFalse(rules.stakeholdersCanViewTeamStatus(project, user))); } |
StatusPermissionRules extends BasePermissionRules { @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of the competition") public boolean internalAdminTeamCanViewCompetitionStatus(CompetitionResource competition, UserResource user){ return isInternalAdmin(user); } @PermissionRule( value = "VIEW_TEAM_STATUS", description = "All partners can view team status") boolean partnersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Internal users can see a team's status") boolean internalUsersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Stakeholders can see a team's status for a project on their competitions") boolean stakeholdersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Monitoring officers can see a team's status for a project") boolean monitoringOfficersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "All partners can view the project status") boolean partnersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "Internal users can see the project status") boolean internalUsersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of the competition") boolean internalAdminTeamCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Support users should be able to access the current status of the competition") boolean supportCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Innovation lead users should be able to access current status of competition that are assigned to them") boolean assignedInnovationLeadCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Stakeholders should be able to access current status of competition that are assigned to them") boolean assignedStakeholderCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Competition finance users should be able to access current status of competition that are assigned to them") boolean assignedCompetitionFinanceCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of project") boolean internalAdminTeamCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Support users should be able to view current status of project") boolean supportCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Innovation lead users should be able to view current status of project from competition assigned to them") boolean assignedInnovationLeadCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Stakeholders should be able to view current status of project from competition assigned to them") boolean assignedStakeholderCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Competition finance users should be able to view current status of project from competition assigned to them") boolean assignedCompetitionFinanceUsersCanViewProjectStatus(ProjectResource project, UserResource user); } | @Test public void internalAdminTeamCanViewCompetitionStatus() { allGlobalRoleUsers.forEach(user -> { if (isInternalAdmin(user)) { assertTrue(rules.internalAdminTeamCanViewCompetitionStatus(newCompetitionResource().build(), user)); } else { assertFalse(rules.internalAdminTeamCanViewCompetitionStatus(newCompetitionResource().build(), user)); } }); } |
StatusPermissionRules extends BasePermissionRules { @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Support users should be able to access the current status of the competition") public boolean supportCanViewCompetitionStatus(CompetitionResource competition, UserResource user){ return isSupport(user); } @PermissionRule( value = "VIEW_TEAM_STATUS", description = "All partners can view team status") boolean partnersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Internal users can see a team's status") boolean internalUsersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Stakeholders can see a team's status for a project on their competitions") boolean stakeholdersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Monitoring officers can see a team's status for a project") boolean monitoringOfficersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "All partners can view the project status") boolean partnersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "Internal users can see the project status") boolean internalUsersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of the competition") boolean internalAdminTeamCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Support users should be able to access the current status of the competition") boolean supportCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Innovation lead users should be able to access current status of competition that are assigned to them") boolean assignedInnovationLeadCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Stakeholders should be able to access current status of competition that are assigned to them") boolean assignedStakeholderCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Competition finance users should be able to access current status of competition that are assigned to them") boolean assignedCompetitionFinanceCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of project") boolean internalAdminTeamCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Support users should be able to view current status of project") boolean supportCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Innovation lead users should be able to view current status of project from competition assigned to them") boolean assignedInnovationLeadCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Stakeholders should be able to view current status of project from competition assigned to them") boolean assignedStakeholderCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Competition finance users should be able to view current status of project from competition assigned to them") boolean assignedCompetitionFinanceUsersCanViewProjectStatus(ProjectResource project, UserResource user); } | @Test public void supportCanViewCompetitionStatus() { allGlobalRoleUsers.forEach(user -> { if (isSupport(user)) { assertTrue(rules.supportCanViewCompetitionStatus(newCompetitionResource().build(), user)); } else { assertFalse(rules.supportCanViewCompetitionStatus(newCompetitionResource().build(), user)); } }); } |
StatusPermissionRules extends BasePermissionRules { @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Innovation lead users should be able to access current status of competition that are assigned to them") public boolean assignedInnovationLeadCanViewCompetitionStatus(CompetitionResource competition, UserResource user){ return userIsInnovationLeadOnCompetition(competition.getId(), user.getId()); } @PermissionRule( value = "VIEW_TEAM_STATUS", description = "All partners can view team status") boolean partnersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Internal users can see a team's status") boolean internalUsersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Stakeholders can see a team's status for a project on their competitions") boolean stakeholdersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Monitoring officers can see a team's status for a project") boolean monitoringOfficersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "All partners can view the project status") boolean partnersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "Internal users can see the project status") boolean internalUsersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of the competition") boolean internalAdminTeamCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Support users should be able to access the current status of the competition") boolean supportCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Innovation lead users should be able to access current status of competition that are assigned to them") boolean assignedInnovationLeadCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Stakeholders should be able to access current status of competition that are assigned to them") boolean assignedStakeholderCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Competition finance users should be able to access current status of competition that are assigned to them") boolean assignedCompetitionFinanceCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of project") boolean internalAdminTeamCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Support users should be able to view current status of project") boolean supportCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Innovation lead users should be able to view current status of project from competition assigned to them") boolean assignedInnovationLeadCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Stakeholders should be able to view current status of project from competition assigned to them") boolean assignedStakeholderCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Competition finance users should be able to view current status of project from competition assigned to them") boolean assignedCompetitionFinanceUsersCanViewProjectStatus(ProjectResource project, UserResource user); } | @Test public void assignedInnovationLeadCanViewCompetitionStatus() { assertTrue(rules.assignedInnovationLeadCanViewCompetitionStatus(competitionResource, innovationLeadUserResourceOnProject1)); assertFalse(rules.assignedInnovationLeadCanViewCompetitionStatus(competitionResource, innovationLeadUser())); } |
StatusPermissionRules extends BasePermissionRules { @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Stakeholders should be able to access current status of competition that are assigned to them") public boolean assignedStakeholderCanViewCompetitionStatus(CompetitionResource competition, UserResource user){ return userIsStakeholderInCompetition(competition.getId(), user.getId()); } @PermissionRule( value = "VIEW_TEAM_STATUS", description = "All partners can view team status") boolean partnersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Internal users can see a team's status") boolean internalUsersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Stakeholders can see a team's status for a project on their competitions") boolean stakeholdersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Monitoring officers can see a team's status for a project") boolean monitoringOfficersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "All partners can view the project status") boolean partnersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "Internal users can see the project status") boolean internalUsersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of the competition") boolean internalAdminTeamCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Support users should be able to access the current status of the competition") boolean supportCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Innovation lead users should be able to access current status of competition that are assigned to them") boolean assignedInnovationLeadCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Stakeholders should be able to access current status of competition that are assigned to them") boolean assignedStakeholderCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Competition finance users should be able to access current status of competition that are assigned to them") boolean assignedCompetitionFinanceCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of project") boolean internalAdminTeamCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Support users should be able to view current status of project") boolean supportCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Innovation lead users should be able to view current status of project from competition assigned to them") boolean assignedInnovationLeadCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Stakeholders should be able to view current status of project from competition assigned to them") boolean assignedStakeholderCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Competition finance users should be able to view current status of project from competition assigned to them") boolean assignedCompetitionFinanceUsersCanViewProjectStatus(ProjectResource project, UserResource user); } | @Test public void assignedStakeholderCanViewCompetitionStatus() { when(stakeholderRepository.existsByCompetitionIdAndUserId(competition.getId(), stakeholderUserResourceOnCompetition.getId())).thenReturn(true); assertTrue(rules.assignedStakeholderCanViewCompetitionStatus(competitionResource, stakeholderUserResourceOnCompetition)); assertFalse(rules.assignedStakeholderCanViewCompetitionStatus(competitionResource, stakeholderUser())); } |
StatusPermissionRules extends BasePermissionRules { @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Competition finance users should be able to access current status of competition that are assigned to them") public boolean assignedCompetitionFinanceCanViewCompetitionStatus(CompetitionResource competition, UserResource user){ return userIsExternalFinanceInCompetition(competition.getId(), user.getId()); } @PermissionRule( value = "VIEW_TEAM_STATUS", description = "All partners can view team status") boolean partnersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Internal users can see a team's status") boolean internalUsersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Stakeholders can see a team's status for a project on their competitions") boolean stakeholdersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Monitoring officers can see a team's status for a project") boolean monitoringOfficersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "All partners can view the project status") boolean partnersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "Internal users can see the project status") boolean internalUsersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of the competition") boolean internalAdminTeamCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Support users should be able to access the current status of the competition") boolean supportCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Innovation lead users should be able to access current status of competition that are assigned to them") boolean assignedInnovationLeadCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Stakeholders should be able to access current status of competition that are assigned to them") boolean assignedStakeholderCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Competition finance users should be able to access current status of competition that are assigned to them") boolean assignedCompetitionFinanceCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of project") boolean internalAdminTeamCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Support users should be able to view current status of project") boolean supportCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Innovation lead users should be able to view current status of project from competition assigned to them") boolean assignedInnovationLeadCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Stakeholders should be able to view current status of project from competition assigned to them") boolean assignedStakeholderCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Competition finance users should be able to view current status of project from competition assigned to them") boolean assignedCompetitionFinanceUsersCanViewProjectStatus(ProjectResource project, UserResource user); } | @Test public void assignedCompetitionFinanceUserCanViewCompetitionStatus() { when(externalFinanceRepository.existsByCompetitionIdAndUserId(competition.getId(), competitionFinanceUserResourceOnCompetition.getId())).thenReturn(true); assertTrue(rules.assignedCompetitionFinanceCanViewCompetitionStatus(competitionResource, competitionFinanceUserResourceOnCompetition)); assertFalse(rules.assignedCompetitionFinanceCanViewCompetitionStatus(competitionResource, competitionFinanceUser())); } |
StatusPermissionRules extends BasePermissionRules { @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of project") public boolean internalAdminTeamCanViewProjectStatus(ProjectResource project, UserResource user){ return isInternalAdmin(user); } @PermissionRule( value = "VIEW_TEAM_STATUS", description = "All partners can view team status") boolean partnersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Internal users can see a team's status") boolean internalUsersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Stakeholders can see a team's status for a project on their competitions") boolean stakeholdersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Monitoring officers can see a team's status for a project") boolean monitoringOfficersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "All partners can view the project status") boolean partnersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "Internal users can see the project status") boolean internalUsersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of the competition") boolean internalAdminTeamCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Support users should be able to access the current status of the competition") boolean supportCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Innovation lead users should be able to access current status of competition that are assigned to them") boolean assignedInnovationLeadCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Stakeholders should be able to access current status of competition that are assigned to them") boolean assignedStakeholderCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Competition finance users should be able to access current status of competition that are assigned to them") boolean assignedCompetitionFinanceCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of project") boolean internalAdminTeamCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Support users should be able to view current status of project") boolean supportCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Innovation lead users should be able to view current status of project from competition assigned to them") boolean assignedInnovationLeadCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Stakeholders should be able to view current status of project from competition assigned to them") boolean assignedStakeholderCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Competition finance users should be able to view current status of project from competition assigned to them") boolean assignedCompetitionFinanceUsersCanViewProjectStatus(ProjectResource project, UserResource user); } | @Test public void internalAdminTeamCanViewProjectStatus() { allGlobalRoleUsers.forEach(user -> { if (isInternalAdmin(user)) { assertTrue(rules.internalAdminTeamCanViewProjectStatus(newProjectResource().build(), user)); } else { assertFalse(rules.internalAdminTeamCanViewProjectStatus(newProjectResource().build(), user)); } }); } |
StatusPermissionRules extends BasePermissionRules { @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Support users should be able to view current status of project") public boolean supportCanViewProjectStatus(ProjectResource project, UserResource user){ return isSupport(user); } @PermissionRule( value = "VIEW_TEAM_STATUS", description = "All partners can view team status") boolean partnersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Internal users can see a team's status") boolean internalUsersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Stakeholders can see a team's status for a project on their competitions") boolean stakeholdersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Monitoring officers can see a team's status for a project") boolean monitoringOfficersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "All partners can view the project status") boolean partnersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "Internal users can see the project status") boolean internalUsersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of the competition") boolean internalAdminTeamCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Support users should be able to access the current status of the competition") boolean supportCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Innovation lead users should be able to access current status of competition that are assigned to them") boolean assignedInnovationLeadCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Stakeholders should be able to access current status of competition that are assigned to them") boolean assignedStakeholderCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Competition finance users should be able to access current status of competition that are assigned to them") boolean assignedCompetitionFinanceCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of project") boolean internalAdminTeamCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Support users should be able to view current status of project") boolean supportCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Innovation lead users should be able to view current status of project from competition assigned to them") boolean assignedInnovationLeadCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Stakeholders should be able to view current status of project from competition assigned to them") boolean assignedStakeholderCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Competition finance users should be able to view current status of project from competition assigned to them") boolean assignedCompetitionFinanceUsersCanViewProjectStatus(ProjectResource project, UserResource user); } | @Test public void supportCanViewProjectStatus() { allGlobalRoleUsers.forEach(user -> { if (isSupport(user)) { assertTrue(rules.supportCanViewProjectStatus(newProjectResource().build(), user)); } else { assertFalse(rules.supportCanViewProjectStatus(newProjectResource().build(), user)); } }); } |
StatusPermissionRules extends BasePermissionRules { @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Innovation lead users should be able to view current status of project from competition assigned to them") public boolean assignedInnovationLeadCanViewProjectStatus(ProjectResource project, UserResource user){ return userIsInnovationLeadOnCompetition(project.getCompetition(), user.getId()); } @PermissionRule( value = "VIEW_TEAM_STATUS", description = "All partners can view team status") boolean partnersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Internal users can see a team's status") boolean internalUsersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Stakeholders can see a team's status for a project on their competitions") boolean stakeholdersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Monitoring officers can see a team's status for a project") boolean monitoringOfficersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "All partners can view the project status") boolean partnersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "Internal users can see the project status") boolean internalUsersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of the competition") boolean internalAdminTeamCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Support users should be able to access the current status of the competition") boolean supportCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Innovation lead users should be able to access current status of competition that are assigned to them") boolean assignedInnovationLeadCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Stakeholders should be able to access current status of competition that are assigned to them") boolean assignedStakeholderCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Competition finance users should be able to access current status of competition that are assigned to them") boolean assignedCompetitionFinanceCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of project") boolean internalAdminTeamCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Support users should be able to view current status of project") boolean supportCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Innovation lead users should be able to view current status of project from competition assigned to them") boolean assignedInnovationLeadCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Stakeholders should be able to view current status of project from competition assigned to them") boolean assignedStakeholderCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Competition finance users should be able to view current status of project from competition assigned to them") boolean assignedCompetitionFinanceUsersCanViewProjectStatus(ProjectResource project, UserResource user); } | @Test public void assignedInnovationLeadCanViewProjectStatus() { assertTrue(rules.assignedInnovationLeadCanViewProjectStatus(projectResource1, innovationLeadUserResourceOnProject1)); assertFalse(rules.assignedInnovationLeadCanViewProjectStatus(projectResource1, innovationLeadUser())); } |
StatusPermissionRules extends BasePermissionRules { @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Stakeholders should be able to view current status of project from competition assigned to them") public boolean assignedStakeholderCanViewProjectStatus(ProjectResource project, UserResource user){ return userIsStakeholderInCompetition(project.getCompetition(), user.getId()); } @PermissionRule( value = "VIEW_TEAM_STATUS", description = "All partners can view team status") boolean partnersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Internal users can see a team's status") boolean internalUsersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Stakeholders can see a team's status for a project on their competitions") boolean stakeholdersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Monitoring officers can see a team's status for a project") boolean monitoringOfficersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "All partners can view the project status") boolean partnersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "Internal users can see the project status") boolean internalUsersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of the competition") boolean internalAdminTeamCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Support users should be able to access the current status of the competition") boolean supportCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Innovation lead users should be able to access current status of competition that are assigned to them") boolean assignedInnovationLeadCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Stakeholders should be able to access current status of competition that are assigned to them") boolean assignedStakeholderCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Competition finance users should be able to access current status of competition that are assigned to them") boolean assignedCompetitionFinanceCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of project") boolean internalAdminTeamCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Support users should be able to view current status of project") boolean supportCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Innovation lead users should be able to view current status of project from competition assigned to them") boolean assignedInnovationLeadCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Stakeholders should be able to view current status of project from competition assigned to them") boolean assignedStakeholderCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Competition finance users should be able to view current status of project from competition assigned to them") boolean assignedCompetitionFinanceUsersCanViewProjectStatus(ProjectResource project, UserResource user); } | @Test public void assignedStakeholderCanViewProjectStatus() { when(stakeholderRepository.existsByCompetitionIdAndUserId(competition.getId(), stakeholderUserResourceOnCompetition.getId())).thenReturn(true); assertTrue(rules.assignedStakeholderCanViewProjectStatus(projectResource1, stakeholderUserResourceOnCompetition)); assertFalse(rules.assignedStakeholderCanViewProjectStatus(projectResource1, stakeholderUser())); } |
StatusPermissionRules extends BasePermissionRules { @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Competition finance users should be able to view current status of project from competition assigned to them") public boolean assignedCompetitionFinanceUsersCanViewProjectStatus(ProjectResource project, UserResource user){ return userIsExternalFinanceInCompetition(project.getCompetition(), user.getId()); } @PermissionRule( value = "VIEW_TEAM_STATUS", description = "All partners can view team status") boolean partnersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Internal users can see a team's status") boolean internalUsersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Stakeholders can see a team's status for a project on their competitions") boolean stakeholdersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_TEAM_STATUS", description = "Monitoring officers can see a team's status for a project") boolean monitoringOfficersCanViewTeamStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "All partners can view the project status") boolean partnersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_STATUS", description = "Internal users can see the project status") boolean internalUsersCanViewStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of the competition") boolean internalAdminTeamCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Support users should be able to access the current status of the competition") boolean supportCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Innovation lead users should be able to access current status of competition that are assigned to them") boolean assignedInnovationLeadCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Stakeholders should be able to access current status of competition that are assigned to them") boolean assignedStakeholderCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_SETUP_COMPETITION_STATUS", description = "Competition finance users should be able to access current status of competition that are assigned to them") boolean assignedCompetitionFinanceCanViewCompetitionStatus(CompetitionResource competition, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Internal admin team (comp admin and project finance) users should be able to access the current status of project") boolean internalAdminTeamCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Support users should be able to view current status of project") boolean supportCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Innovation lead users should be able to view current status of project from competition assigned to them") boolean assignedInnovationLeadCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Stakeholders should be able to view current status of project from competition assigned to them") boolean assignedStakeholderCanViewProjectStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_PROJECT_STATUS", description = "Competition finance users should be able to view current status of project from competition assigned to them") boolean assignedCompetitionFinanceUsersCanViewProjectStatus(ProjectResource project, UserResource user); } | @Test public void assignedCompetitionFinanceUsersCanViewProjectStatus() { when(externalFinanceRepository.existsByCompetitionIdAndUserId(competition.getId(), competitionFinanceUserResourceOnCompetition.getId())).thenReturn(true); assertTrue(rules.assignedCompetitionFinanceUsersCanViewProjectStatus(projectResource1, competitionFinanceUserResourceOnCompetition)); assertFalse(rules.assignedCompetitionFinanceUsersCanViewProjectStatus(projectResource1, competitionFinanceUser())); } |
StatusController { @GetMapping("/competition/{competitionId}") public RestResult<ProjectStatusPageResource> getCompetitionStatus(@PathVariable final long competitionId, @RequestParam(name = "applicationSearchString", defaultValue = "") String applicationSearchString, @RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int page, @RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int size) { return internalUserProjectStatusService.getCompetitionStatus(competitionId, StringUtils.trim(applicationSearchString), page, size).toGetResponse(); } @GetMapping("/competition/{competitionId}") RestResult<ProjectStatusPageResource> getCompetitionStatus(@PathVariable final long competitionId,
@RequestParam(name = "applicationSearchString", defaultValue = "") String applicationSearchString,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int page,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int size); @GetMapping("/previous/competition/{competitionId}") RestResult<List<ProjectStatusResource>> getPreviousCompetitionStatus(@PathVariable final long competitionId); @GetMapping("/{projectId}/team-status") RestResult<ProjectTeamStatusResource> getTeamStatus(@PathVariable(value = "projectId") Long projectId,
@RequestParam(value = "filterByUserId", required = false) Long filterByUserId); @GetMapping("/{projectId}/status") RestResult<ProjectStatusResource> getStatus(@PathVariable(value = "projectId") Long projectId); } | @Test public void getCompetitionStatus() throws Exception { final Long competitionId = 123L; String applicationSearchString = "12"; ServiceResult<ProjectStatusPageResource> expected = serviceSuccess(new ProjectStatusPageResource()); when(internalUserProjectStatusService.getCompetitionStatus(competitionId, applicationSearchString, 0, 5)).thenReturn(expected); mockMvc.perform(get("/project/competition/{competitionId}?applicationSearchString=" + applicationSearchString, 123L)). andExpect(status().isOk()); verify(internalUserProjectStatusService).getCompetitionStatus(competitionId, applicationSearchString, 0, 5); } |
StatusServiceImpl extends AbstractProjectServiceImpl implements StatusService { @Override @Transactional public ServiceResult<ProjectTeamStatusResource> getProjectTeamStatus(Long projectId, Optional<Long> filterByUserId) { Project project = projectRepository.findById(projectId).get(); PartnerOrganisation lead = project.getLeadOrganisation().get(); Optional<ProjectUser> partnerUserForFilterUser = filterByUserId.flatMap( userId -> simpleFindFirst(project.getProjectUsers(), pu -> pu.getUser().getId().equals(userId) && pu.getRole().isPartner())); List<PartnerOrganisation> partnerOrganisationsToInclude = simpleFilter(project.getPartnerOrganisations(), partner -> partner.isLeadOrganisation() || (partnerUserForFilterUser.map(pu -> partner.getOrganisation().getId().equals(pu.getOrganisation().getId())) .orElse(true))); List<PartnerOrganisation> sortedOrganisationsToInclude = new PrioritySorting<>(partnerOrganisationsToInclude, lead, p -> p.getOrganisation().getName()).unwrap(); List<ProjectPartnerStatusResource> projectPartnerStatusResources = simpleMap(sortedOrganisationsToInclude, partner -> getProjectPartnerStatus(project, partner)); ProjectTeamStatusResource projectTeamStatusResource = new ProjectTeamStatusResource(); projectTeamStatusResource.setPartnerStatuses(projectPartnerStatusResources); projectTeamStatusResource.setProjectState(project.getProjectProcess().getProcessState()); projectTeamStatusResource.setProjectManagerAssigned(getProjectManager(project).isPresent()); return serviceSuccess(projectTeamStatusResource); } @Override @Transactional //Write transaction for first time creation of project finances. ServiceResult<ProjectTeamStatusResource> getProjectTeamStatus(Long projectId, Optional<Long> filterByUserId); } | @Test public void getProjectConsortiumStatus() { OrganisationType businessOrganisationType = newOrganisationType().withOrganisationType(BUSINESS).build(); OrganisationType academicOrganisationType = newOrganisationType().withOrganisationType(RESEARCH).build(); List<Organisation> organisations = new ArrayList<>(); Organisation leadOrganisation = newOrganisation() .withOrganisationType(businessOrganisationType) .build(); organisations.add(leadOrganisation); Organisation partnerOrganisation1 = newOrganisation().withOrganisationType(businessOrganisationType).build(); Organisation partnerOrganisation2 = newOrganisation().withOrganisationType(academicOrganisationType).build(); organisations.add(partnerOrganisation1); organisations.add(partnerOrganisation2); List<User> users = newUser().build(3); List<ProjectUser> projectUsers = newProjectUser() .withRole(PROJECT_PARTNER) .withUser(users.get(0), users.get(1), users.get(2)) .withOrganisation(organisations.get(0), organisations.get(1), organisations.get(2)) .build(3); Project project = newProject() .withProjectUsers(projectUsers) .withApplication(application) .withAddress(newAddress().build()) .withTargetStartDate(LocalDate.now()) .withProjectProcess(projectProcess) .build(); List<BankDetails> bankDetails = newBankDetails() .withOrganisation(organisations.get(0), organisations.get(1), organisations.get(2)) .build(3); List<PartnerOrganisation> partnerOrganisations = newPartnerOrganisation() .withProject(project) .withOrganisation(leadOrganisation, partnerOrganisation1, partnerOrganisation2) .withLeadOrganisation(true, false, false) .withPostcode(null, "TW14 9QG", " ") .withLeadOrganisation(true, false, false) .build(3); when(projectRepository.findById(project.getId())).thenReturn(Optional.of(project)); when(projectUserRepository.findByProjectId(project.getId())).thenReturn(projectUsers); when(bankDetailsRepository.findByProjectIdAndOrganisationId(project.getId(), organisations.get(0).getId())).thenReturn(Optional.of(bankDetails.get(0))); when(monitoringOfficerService.findMonitoringOfficerForProject(project.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(project.getId(), organisations.get(0).getId())).thenReturn(Optional.empty()); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(project.getId(), organisations.get(1).getId())).thenReturn(Optional.empty()); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(project.getId(), organisations.get(2).getId())).thenReturn(Optional.empty()); MonitoringOfficerResource monitoringOfficer = newMonitoringOfficerResource().build(); when(monitoringOfficerService.findMonitoringOfficerForProject(this.project.getId())).thenReturn(serviceSuccess(monitoringOfficer)); when(organisationRepository.findById(organisations.get(0).getId())).thenReturn(Optional.of(organisations.get(0))); when(organisationRepository.findById(organisations.get(1).getId())).thenReturn(Optional.of(organisations.get(1))); when(organisationRepository.findById(organisations.get(2).getId())).thenReturn(Optional.of(organisations.get(2))); List<ApplicationFinance> applicationFinances = newApplicationFinance().build(3); when(applicationFinanceRepository.findByApplicationIdAndOrganisationId(project.getApplication().getId(), organisations.get(0).getId())).thenReturn(Optional.of(applicationFinances.get(0))); when(applicationFinanceRepository.findByApplicationIdAndOrganisationId(project.getApplication().getId(), organisations.get(1).getId())).thenReturn(Optional.of(applicationFinances.get(1))); when(applicationFinanceRepository.findByApplicationIdAndOrganisationId(project.getApplication().getId(), organisations.get(2).getId())).thenReturn(Optional.of(applicationFinances.get(2))); ApplicationFinanceResource applicationFinanceResource0 = newApplicationFinanceResource().withGrantClaimPercentage(BigDecimal.valueOf(20)).withOrganisation(organisations.get(0).getId()).build(); when(applicationFinanceMapper.mapToResource(applicationFinances.get(0))).thenReturn(applicationFinanceResource0); ApplicationFinanceResource applicationFinanceResource1 = newApplicationFinanceResource().withGrantClaimPercentage(BigDecimal.valueOf(20)).withOrganisation(organisations.get(1).getId()).build(); when(applicationFinanceMapper.mapToResource(applicationFinances.get(1))).thenReturn(applicationFinanceResource1); ApplicationFinanceResource applicationFinanceResource2 = newApplicationFinanceResource().withGrantClaimPercentage(BigDecimal.valueOf(20)).withOrganisation(organisations.get(2).getId()).build(); when(applicationFinanceMapper.mapToResource(applicationFinances.get(2))).thenReturn(applicationFinanceResource2); List<ProjectUserResource> puResource = newProjectUserResource().withProject(project.getId()).withOrganisation(organisations.get(0).getId(), organisations.get(1).getId(), organisations.get(2).getId()).withRole(partnerRole.getId()).withRoleName(PROJECT_PARTNER.getName()).build(3); when(projectUserMapper.mapToResource(projectUsers.get(0))).thenReturn(puResource.get(0)); when(projectUserMapper.mapToResource(projectUsers.get(1))).thenReturn(puResource.get(1)); when(projectUserMapper.mapToResource(projectUsers.get(2))).thenReturn(puResource.get(2)); when(projectFinanceService.financeChecksDetails(project.getId(), organisations.get(0).getId())).thenReturn(serviceSuccess(newProjectFinanceResource().thatIsRequestingFunding().build())); when(projectFinanceService.financeChecksDetails(project.getId(), organisations.get(1).getId())).thenReturn(serviceSuccess(newProjectFinanceResource().thatIsNotRequestingFunding().build())); when(projectFinanceService.financeChecksDetails(project.getId(), organisations.get(2).getId())).thenReturn(serviceSuccess(newProjectFinanceResource().thatIsRequestingFunding().build())); partnerOrganisations.forEach(org -> when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(org.getProject().getId(), org.getOrganisation().getId())).thenReturn(org)); when(financeCheckService.isQueryActionRequired(partnerOrganisations.get(0).getProject().getId(), partnerOrganisations.get(0).getOrganisation().getId())).thenReturn(serviceSuccess(false)); when(financeCheckService.isQueryActionRequired(partnerOrganisations.get(1).getProject().getId(), partnerOrganisations.get(1).getOrganisation().getId())).thenReturn(serviceSuccess(false)); when(financeCheckService.isQueryActionRequired(partnerOrganisations.get(2).getProject().getId(), partnerOrganisations.get(2).getOrganisation().getId())).thenReturn(serviceSuccess(true)); when(golWorkflowHandler.getState(project)).thenReturn(GrantOfferLetterState.PENDING); GrantOfferLetterStateResource unsentGrantOfferLetterState = GrantOfferLetterStateResource.stateInformationForNonPartnersView(GrantOfferLetterState.PENDING, null); when(golWorkflowHandler.getExtendedState(project)).thenReturn(serviceSuccess(unsentGrantOfferLetterState)); ProjectPartnerStatusResource expectedLeadPartnerOrganisationStatus = newProjectPartnerStatusResource() .withName(organisations.get(0).getName()) .withOrganisationType( getFromId(organisations.get(0).getOrganisationType().getId())) .withOrganisationId(organisations.get(0).getId()) .withProjectDetailsStatus(ACTION_REQUIRED) .withProjectTeamStatus(ACTION_REQUIRED) .withFinanceContactStatus(ACTION_REQUIRED) .withPartnerProjectLocationStatus(ACTION_REQUIRED) .withMonitoringOfficerStatus(NOT_STARTED) .withBankDetailsStatus(PENDING) .withFinanceChecksStatus(PENDING) .withSpendProfileStatus(NOT_STARTED) .withDocumentsStatus(ACTION_REQUIRED) .withGrantOfferStatus(NOT_REQUIRED) .withProjectSetupCompleteStatus(NOT_REQUIRED) .withIsLeadPartner(true) .build(); List<ProjectPartnerStatusResource> expectedFullPartnerStatuses = newProjectPartnerStatusResource() .withName(organisations.get(1).getName(), organisations.get(2).getName()) .withOrganisationType( getFromId(organisations.get(1).getOrganisationType().getId()), getFromId(organisations.get(2).getOrganisationType().getId())) .withOrganisationId(organisations.get(1).getId(), organisations.get(2).getId()) .withProjectDetailsStatus(COMPLETE, ACTION_REQUIRED) .withProjectTeamStatus(ACTION_REQUIRED, ACTION_REQUIRED) .withFinanceContactStatus(ACTION_REQUIRED, ACTION_REQUIRED) .withPartnerProjectLocationStatus(COMPLETE, ACTION_REQUIRED) .withMonitoringOfficerStatus(NOT_REQUIRED, NOT_REQUIRED) .withBankDetailsStatus(NOT_REQUIRED, NOT_STARTED) .withFinanceChecksStatus(PENDING, ACTION_REQUIRED) .withSpendProfileStatus(NOT_STARTED, NOT_STARTED) .withDocumentsStatus(NOT_REQUIRED, NOT_REQUIRED) .withGrantOfferStatus(NOT_REQUIRED, NOT_REQUIRED) .withProjectSetupCompleteStatus(NOT_REQUIRED, NOT_REQUIRED) .build(2); ProjectTeamStatusResource expectedProjectTeamStatusResource = newProjectTeamStatusResource() .withProjectLeadStatus(expectedLeadPartnerOrganisationStatus) .withPartnerStatuses(expectedFullPartnerStatuses) .build(); ServiceResult<ProjectTeamStatusResource> result = service.getProjectTeamStatus(project.getId(), Optional.empty()); assertTrue(result.isSuccess()); assertEquals(expectedProjectTeamStatusResource, result.getSuccess()); List<ProjectPartnerStatusResource> expectedPartnerStatusesFilteredOnNonLead = newProjectPartnerStatusResource() .withName(organisations.get(2).getName()) .withOrganisationType( getFromId(organisations.get(2).getOrganisationType().getId())) .withOrganisationId(organisations.get(2).getId()) .withProjectDetailsStatus(ACTION_REQUIRED) .withProjectTeamStatus(ACTION_REQUIRED) .withFinanceContactStatus(ACTION_REQUIRED) .withPartnerProjectLocationStatus(ACTION_REQUIRED) .withMonitoringOfficerStatus(NOT_REQUIRED) .withBankDetailsStatus(NOT_STARTED) .withFinanceChecksStatus(ACTION_REQUIRED) .withSpendProfileStatus(NOT_STARTED) .withDocumentsStatus(NOT_REQUIRED) .withGrantOfferStatus(NOT_REQUIRED) .withProjectSetupCompleteStatus(NOT_REQUIRED) .build(1); ProjectTeamStatusResource expectedProjectTeamStatusResourceFilteredOnNonLead = newProjectTeamStatusResource(). withProjectLeadStatus(expectedLeadPartnerOrganisationStatus). withPartnerStatuses(expectedPartnerStatusesFilteredOnNonLead). build(); ServiceResult<ProjectTeamStatusResource> resultWithNonLeadFilter = service.getProjectTeamStatus(project.getId(), Optional.of(users.get(2).getId())); assertTrue(resultWithNonLeadFilter.isSuccess()); assertEquals(expectedProjectTeamStatusResourceFilteredOnNonLead, resultWithNonLeadFilter.getSuccess()); ProjectTeamStatusResource expectedProjectTeamStatusResourceFilteredOnLead = newProjectTeamStatusResource() .withProjectLeadStatus(expectedLeadPartnerOrganisationStatus) .build(); ServiceResult<ProjectTeamStatusResource> resultWithLeadFilter = service.getProjectTeamStatus(project.getId(), Optional.of(users.get(0).getId())); assertTrue(resultWithLeadFilter.isSuccess()); assertEquals(expectedProjectTeamStatusResourceFilteredOnLead, resultWithLeadFilter.getSuccess()); project.setTargetStartDate(LocalDate.now()); project.setAddress(newAddress().build()); competition.setLocationPerPartner(false); when(projectDetailsWorkflowHandler.isSubmitted(any(Project.class))).thenReturn(true); when(monitoringOfficerService.findMonitoringOfficerForProject(project.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); ProjectPartnerStatusResource expectedLeadPartnerOrganisationStatusWhenPDSubmitted = newProjectPartnerStatusResource() .withName(organisations.get(0).getName()) .withOrganisationType( getFromId(organisations.get(0).getOrganisationType().getId())) .withOrganisationId(organisations.get(0).getId()) .withProjectDetailsStatus(COMPLETE) .withProjectTeamStatus(ACTION_REQUIRED) .withFinanceContactStatus(ACTION_REQUIRED) .withPartnerProjectLocationStatus(ACTION_REQUIRED) .withMonitoringOfficerStatus(PENDING) .withBankDetailsStatus(PENDING) .withFinanceChecksStatus(PENDING) .withSpendProfileStatus(NOT_STARTED) .withDocumentsStatus(ACTION_REQUIRED) .withGrantOfferStatus(NOT_REQUIRED) .withProjectSetupCompleteStatus(NOT_REQUIRED) .withIsLeadPartner(true) .build(); ProjectTeamStatusResource expectedProjectTeamStatusResourceWhenPSSubmitted = newProjectTeamStatusResource() .withProjectLeadStatus(expectedLeadPartnerOrganisationStatusWhenPDSubmitted) .withPartnerStatuses(expectedFullPartnerStatuses) .build(); ServiceResult<ProjectTeamStatusResource> resultForPsSubmitted = service.getProjectTeamStatus(project.getId(), Optional.empty()); assertTrue(resultForPsSubmitted.isSuccess()); assertEquals(expectedProjectTeamStatusResourceWhenPSSubmitted, resultForPsSubmitted.getSuccess()); }
@Test public void isGrantOfferLetterActionRequired() { FileEntry golFile = newFileEntry().withFilesizeBytes(10).withMediaType("application/pdf").build(); List<ProjectUser> pu = newProjectUser() .withRole(PROJECT_FINANCE_CONTACT) .withUser(user).withOrganisation(organisation) .withInvite(newProjectUserInvite().build()) .build(1); List<PartnerOrganisation> po = newPartnerOrganisation() .withOrganisation(organisation) .withLeadOrganisation(true) .build(1); Project project = newProject() .withProjectUsers(pu) .withApplication(application) .withPartnerOrganisations(po) .withDateSubmitted(ZonedDateTime.now()) .withProjectProcess(projectProcess) .withGrantOfferLetter(golFile).build(); List<ProjectUserResource> puResource = newProjectUserResource() .withProject(project.getId()) .withOrganisation(organisation.getId()) .withRole(partnerRole.getId()) .withRoleName(PROJECT_PARTNER.getName()) .build(1); BankDetails bankDetails = newBankDetails().withOrganisation(organisation).withApproval(true).build(); SpendProfile spendProfile = newSpendProfile().withOrganisation(organisation).withMarkedComplete(true).build(); when(projectRepository.findById(project.getId())).thenReturn(Optional.of(project)); when(projectUserRepository.findByProjectId(project.getId())).thenReturn(pu); when(projectUserMapper.mapToResource(pu.get(0))).thenReturn(puResource.get(0)); when(organisationRepository.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(project.getId(), organisation.getId())).thenReturn(po.get(0)); when(bankDetailsRepository.findByProjectIdAndOrganisationId(project.getId(), organisation.getId())).thenReturn(Optional.of(bankDetails)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(project.getId(), organisation.getId())).thenReturn(Optional.ofNullable(spendProfile)); when(eligibilityWorkflowHandler.getState(po.get(0))).thenReturn(EligibilityState.APPROVED); when(viabilityWorkflowHandler.getState(po.get(0))).thenReturn(ViabilityState.APPROVED); when(financeCheckService.isQueryActionRequired(project.getId(), organisation.getId())).thenReturn(serviceSuccess(false)); when(golWorkflowHandler.getState(project)).thenReturn(GrantOfferLetterState.SENT); GrantOfferLetterStateResource unsentGrantOfferLetterState = GrantOfferLetterStateResource.stateInformationForNonPartnersView(GrantOfferLetterState.PENDING, null); when(monitoringOfficerService.findMonitoringOfficerForProject(project.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); when(golWorkflowHandler.getExtendedState(project)).thenReturn(serviceSuccess(unsentGrantOfferLetterState)); ServiceResult<ProjectTeamStatusResource> result = service.getProjectTeamStatus(project.getId(), Optional.ofNullable(pu.get(0).getId())); assertTrue(result.isSuccess() && ACTION_REQUIRED.equals(result.getSuccess().getLeadPartnerStatus().getGrantOfferLetterStatus())); }
@Test public void isGrantOfferLetterIsPendingLeadPartner() { FileEntry golFile = newFileEntry().withFilesizeBytes(10).withMediaType("application/pdf").build(); List<ProjectUser> pu = newProjectUser() .withRole(PROJECT_FINANCE_CONTACT) .withUser(user) .withOrganisation(organisation) .withInvite(newProjectUserInvite() .build()) .build(1); List<PartnerOrganisation> po = newPartnerOrganisation() .withOrganisation(organisation) .withLeadOrganisation(true) .build(1); Project p = newProject() .withProjectUsers(pu) .withApplication(application) .withPartnerOrganisations(po) .withDateSubmitted(ZonedDateTime.now()) .withGrantOfferLetter(golFile) .withSignedGrantOfferLetter(golFile) .withProjectProcess(projectProcess) .build(); List<ProjectUserResource> puResource = newProjectUserResource() .withProject(p.getId()) .withOrganisation(organisation.getId()) .withRole(partnerRole.getId()) .withRoleName(PROJECT_PARTNER.getName()) .build(1); BankDetails bankDetails = newBankDetails().withOrganisation(organisation).withApproval(true).build(); SpendProfile spendProfile = newSpendProfile().withOrganisation(organisation).withMarkedComplete(true).build(); when(projectRepository.findById(p.getId())).thenReturn(Optional.of(p)); when(projectUserRepository.findByProjectId(p.getId())).thenReturn(pu); when(projectUserMapper.mapToResource(pu.get(0))).thenReturn(puResource.get(0)); when(organisationRepository.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(po.get(0)); when(bankDetailsRepository.findByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.of(bankDetails)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.ofNullable(spendProfile)); when(eligibilityWorkflowHandler.getState(po.get(0))).thenReturn(EligibilityState.APPROVED); when(viabilityWorkflowHandler.getState(po.get(0))).thenReturn(ViabilityState.APPROVED); when(financeCheckService.isQueryActionRequired(p.getId(), organisation.getId())).thenReturn(serviceSuccess(false)); GrantOfferLetterStateResource unsentGrantOfferLetterState = GrantOfferLetterStateResource.stateInformationForNonPartnersView(GrantOfferLetterState.PENDING, null); when(golWorkflowHandler.getExtendedState(p)).thenReturn(serviceSuccess(unsentGrantOfferLetterState)); when(monitoringOfficerService.findMonitoringOfficerForProject(p.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); ServiceResult<ProjectTeamStatusResource> resultWhenGolIsNotSent = service.getProjectTeamStatus(p.getId(), Optional.ofNullable(pu.get(0).getId())); assertTrue(resultWhenGolIsNotSent.isSuccess() && PENDING.equals(resultWhenGolIsNotSent.getSuccess().getLeadPartnerStatus().getGrantOfferLetterStatus())); when(golWorkflowHandler.isReadyToApprove(p)).thenReturn(true); ServiceResult<ProjectTeamStatusResource> resultWhenGolIsReadyToApprove = service.getProjectTeamStatus(p.getId(), Optional.ofNullable(pu.get(0).getId())); assertTrue(resultWhenGolIsReadyToApprove.isSuccess() && PENDING.equals(resultWhenGolIsReadyToApprove.getSuccess().getLeadPartnerStatus().getGrantOfferLetterStatus())); }
@Test public void isGrantOfferLetterIsPendingNonLeadPartner() { User u = newUser().withEmailAddress("[email protected]").build(); OrganisationType businessOrganisationType = newOrganisationType().withOrganisationType(BUSINESS).build(); Organisation o = organisationRepository.findById(application.getLeadOrganisationId()).get(); o.setOrganisationType(businessOrganisationType); FileEntry golFile = newFileEntry().withFilesizeBytes(10).withMediaType("application/pdf").build(); Organisation nonLeadOrg = newOrganisation().build(); nonLeadOrg.setOrganisationType(businessOrganisationType); List<ProjectUser> pu = newProjectUser().withRole(PROJECT_FINANCE_CONTACT).withUser(u).withOrganisation(nonLeadOrg).withInvite(newProjectUserInvite().build()).build(1); List<PartnerOrganisation> po = newPartnerOrganisation().withOrganisation(nonLeadOrg).withLeadOrganisation(false).build(1); Project p = spy(newProject().withProjectUsers(pu).withApplication(application).withPartnerOrganisations(po).withGrantOfferLetter(golFile).withSignedGrantOfferLetter(golFile).withDateSubmitted(ZonedDateTime.now()).withProjectProcess(projectProcess).build()); List<ProjectUserResource> puResource = newProjectUserResource().withProject(p.getId()).withOrganisation(nonLeadOrg.getId()).withRole(partnerRole.getId()).withRoleName(PROJECT_PARTNER.getName()).build(1); when(p.getLeadOrganisation()).thenReturn(Optional.of(newPartnerOrganisation().build())); BankDetails bankDetails = newBankDetails().withOrganisation(o).withApproval(true).build(); SpendProfile spendProfile = newSpendProfile().withOrganisation(o).withMarkedComplete(true).build(); when(p.getLeadOrganisation()).thenReturn(Optional.of(newPartnerOrganisation().build())); when(projectRepository.findById(p.getId())).thenReturn(Optional.of(p)); when(projectUserRepository.findByProjectId(p.getId())).thenReturn(pu); when(projectUserMapper.mapToResource(pu.get(0))).thenReturn(puResource.get(0)); when(organisationRepository.findById(o.getId())).thenReturn(Optional.of(o)); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(p.getId(), nonLeadOrg.getId())).thenReturn(po.get(0)); when(bankDetailsRepository.findByProjectIdAndOrganisationId(anyLong(), anyLong())).thenReturn(Optional.of(bankDetails)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(p.getId(), nonLeadOrg.getId())).thenReturn(Optional.ofNullable(spendProfile)); when(eligibilityWorkflowHandler.getState(po.get(0))).thenReturn(EligibilityState.APPROVED); when(viabilityWorkflowHandler.getState(po.get(0))).thenReturn(ViabilityState.APPROVED); GrantOfferLetterStateResource sentGrantOfferLetterState = GrantOfferLetterStateResource.stateInformationForNonPartnersView(GrantOfferLetterState.SENT, null); when(golWorkflowHandler.getExtendedState(p)).thenReturn(serviceSuccess(sentGrantOfferLetterState)); when(golWorkflowHandler.isReadyToApprove(p)).thenReturn(true); when(projectFinanceService.financeChecksDetails(p.getId(), o.getId())).thenReturn(serviceSuccess(newProjectFinanceResource().thatIsRequestingFunding().build())); when(projectFinanceService.financeChecksDetails(p.getId(), nonLeadOrg.getId())).thenReturn(serviceSuccess(newProjectFinanceResource().thatIsRequestingFunding().build())); when(financeCheckService.isQueryActionRequired(anyLong(), anyLong())).thenReturn(serviceSuccess(false)); when(monitoringOfficerService.findMonitoringOfficerForProject(p.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); ServiceResult<ProjectTeamStatusResource> resultWhenGolIsReadyToApprove = service.getProjectTeamStatus(p.getId(), Optional.ofNullable(pu.get(0).getId())); assertTrue(resultWhenGolIsReadyToApprove.isSuccess() && PENDING.equals(resultWhenGolIsReadyToApprove.getSuccess().getPartnerStatuses().get(0).getGrantOfferLetterStatus())); }
@Test public void isGrantOfferLetterComplete() { FileEntry golFile = newFileEntry().withFilesizeBytes(10).withMediaType("application/pdf").build(); List<ProjectUser> pu = newProjectUser().withRole(PROJECT_FINANCE_CONTACT).withUser(user).withOrganisation(organisation).withInvite(newProjectUserInvite().build()).build(1); List<PartnerOrganisation> po = newPartnerOrganisation().withOrganisation(organisation).withLeadOrganisation(true).build(1); Project p = newProject().withProjectUsers(pu).withApplication(application).withPartnerOrganisations(po).withDateSubmitted(ZonedDateTime.now()).withGrantOfferLetter(golFile).withSignedGrantOfferLetter(golFile).withOfferSubmittedDate(ZonedDateTime.now()).withProjectProcess(projectProcess).build(); List<ProjectUserResource> puResource = newProjectUserResource().withProject(p.getId()).withOrganisation(organisation.getId()).withRole(partnerRole.getId()).withRoleName(PROJECT_PARTNER.getName()).build(1); when(projectRepository.findById(p.getId())).thenReturn(Optional.of(p)); when(projectUserRepository.findByProjectId(p.getId())).thenReturn(pu); when(projectUserMapper.mapToResource(pu.get(0))).thenReturn(puResource.get(0)); when(organisationRepository.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(po.get(0)); when(bankDetailsRepository.findByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.of(bankDetails)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.ofNullable(spendProfile)); when(eligibilityWorkflowHandler.getState(po.get(0))).thenReturn(EligibilityState.APPROVED); when(viabilityWorkflowHandler.getState(po.get(0))).thenReturn(ViabilityState.APPROVED); when(golWorkflowHandler.getState(p)).thenReturn(GrantOfferLetterState.APPROVED); when(financeCheckService.isQueryActionRequired(p.getId(), organisation.getId())).thenReturn(serviceSuccess(false)); when(monitoringOfficerService.findMonitoringOfficerForProject(p.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); GrantOfferLetterStateResource unsentGrantOfferLetterState = GrantOfferLetterStateResource.stateInformationForNonPartnersView(GrantOfferLetterState.PENDING, null); when(golWorkflowHandler.getExtendedState(p)).thenReturn(serviceSuccess(unsentGrantOfferLetterState)); ServiceResult<ProjectTeamStatusResource> result = service.getProjectTeamStatus(p.getId(), Optional.ofNullable(pu.get(0).getId())); assertTrue(result.isSuccess() && COMPLETE.equals(result.getSuccess().getLeadPartnerStatus().getGrantOfferLetterStatus())); }
@Test public void spendProfileNotComplete() { spendProfile.setMarkedAsComplete(false); when(projectRepository.findById(p.getId())).thenReturn(Optional.of(p)); when(projectUserRepository.findByProjectId(p.getId())).thenReturn(projectUsers); when(projectUserMapper.mapToResource(projectUsers.get(0))).thenReturn(projectUserResources.get(0)); when(organisationRepository.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(partnerOrganisation.get(0)); when(bankDetailsRepository.findByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.of(bankDetails)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.ofNullable(spendProfile)); when(eligibilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(EligibilityState.APPROVED); when(viabilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(ViabilityState.APPROVED); when(financeCheckService.isQueryActionRequired(p.getId(), organisation.getId())).thenReturn(serviceSuccess(false)); GrantOfferLetterStateResource unsentGrantOfferLetterState = GrantOfferLetterStateResource.stateInformationForNonPartnersView(GrantOfferLetterState.PENDING, null); when(golWorkflowHandler.getExtendedState(p)).thenReturn(serviceSuccess(unsentGrantOfferLetterState)); when(monitoringOfficerService.findMonitoringOfficerForProject(p.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); ServiceResult<ProjectTeamStatusResource> result = service.getProjectTeamStatus(p.getId(), Optional.ofNullable(projectUsers.get(0).getId())); assertTrue(result.isSuccess() && ACTION_REQUIRED.equals(result.getSuccess().getLeadPartnerStatus().getSpendProfileStatus())); }
@Test public void spendProfileRequiresEligibility() { when(projectRepository.findById(p.getId())).thenReturn(Optional.of(p)); when(projectUserRepository.findByProjectId(p.getId())).thenReturn(projectUsers); when(projectUserMapper.mapToResource(projectUsers.get(0))).thenReturn(projectUserResources.get(0)); when(organisationRepository.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(partnerOrganisation.get(0)); when(bankDetailsRepository.findByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.of(bankDetails)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.empty()); when(eligibilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(EligibilityState.REVIEW); when(monitoringOfficerService.findMonitoringOfficerForProject(p.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); when(viabilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(ViabilityState.APPROVED); when(financeCheckService.isQueryActionRequired(p.getId(), organisation.getId())).thenReturn(serviceSuccess(false)); GrantOfferLetterStateResource unsentGrantOfferLetterState = GrantOfferLetterStateResource.stateInformationForNonPartnersView(GrantOfferLetterState.PENDING, null); when(golWorkflowHandler.getExtendedState(p)).thenReturn(serviceSuccess(unsentGrantOfferLetterState)); ServiceResult<ProjectTeamStatusResource> result = service.getProjectTeamStatus(p.getId(), Optional.ofNullable(projectUsers.get(0).getId())); assertTrue(result.isSuccess() && NOT_STARTED.equals(result.getSuccess().getLeadPartnerStatus().getSpendProfileStatus())); }
@Test public void spendProfileRequiresViability() { when(projectRepository.findById(p.getId())).thenReturn(Optional.of(p)); when(projectUserRepository.findByProjectId(p.getId())).thenReturn(projectUsers); when(projectUserMapper.mapToResource(projectUsers.get(0))).thenReturn(projectUserResources.get(0)); when(organisationRepository.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(partnerOrganisation.get(0)); when(bankDetailsRepository.findByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.of(bankDetails)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.empty()); when(eligibilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(EligibilityState.APPROVED); when(viabilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(ViabilityState.REVIEW); when(financeCheckService.isQueryActionRequired(p.getId(), organisation.getId())).thenReturn(serviceSuccess(false)); when(monitoringOfficerService.findMonitoringOfficerForProject(p.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); GrantOfferLetterStateResource unsentGrantOfferLetterState = GrantOfferLetterStateResource.stateInformationForNonPartnersView(GrantOfferLetterState.PENDING, null); when(golWorkflowHandler.getExtendedState(p)).thenReturn(serviceSuccess(unsentGrantOfferLetterState)); ServiceResult<ProjectTeamStatusResource> result = service.getProjectTeamStatus(p.getId(), Optional.ofNullable(projectUsers.get(0).getId())); assertTrue(result.isSuccess() && NOT_STARTED.equals(result.getSuccess().getLeadPartnerStatus().getSpendProfileStatus())); }
@Test public void spendProfileNotSubmittedViabilityNotApplicable() { p.setSpendProfileSubmittedDate(null); when(projectRepository.findById(p.getId())).thenReturn(Optional.of(p)); when(projectUserRepository.findByProjectId(p.getId())).thenReturn(projectUsers); when(projectUserMapper.mapToResource(projectUsers.get(0))).thenReturn(projectUserResources.get(0)); when(organisationRepository.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(partnerOrganisation.get(0)); when(bankDetailsRepository.findByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.of(bankDetails)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.ofNullable(spendProfile)); when(eligibilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(EligibilityState.APPROVED); when(monitoringOfficerService.findMonitoringOfficerForProject(p.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); when(viabilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(ViabilityState.NOT_APPLICABLE); when(financeCheckService.isQueryActionRequired(p.getId(), organisation.getId())).thenReturn(serviceSuccess(false)); GrantOfferLetterStateResource unsentGrantOfferLetterState = GrantOfferLetterStateResource.stateInformationForNonPartnersView(GrantOfferLetterState.PENDING, null); when(golWorkflowHandler.getExtendedState(p)).thenReturn(serviceSuccess(unsentGrantOfferLetterState)); ServiceResult<ProjectTeamStatusResource> result = service.getProjectTeamStatus(p.getId(), Optional.ofNullable(projectUsers.get(0).getId())); assertTrue(result.isSuccess() && LEAD_ACTION_REQUIRED.equals(result.getSuccess().getLeadPartnerStatus().getSpendProfileStatus())); }
@Test public void spendProfileCompleteNotSubmitted() { p.setSpendProfileSubmittedDate(null); when(projectRepository.findById(p.getId())).thenReturn(Optional.of(p)); when(projectUserRepository.findByProjectId(p.getId())).thenReturn(projectUsers); when(projectUserMapper.mapToResource(projectUsers.get(0))).thenReturn(projectUserResources.get(0)); when(organisationRepository.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(partnerOrganisation.get(0)); when(bankDetailsRepository.findByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.of(bankDetails)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.ofNullable(spendProfile)); when(eligibilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(EligibilityState.APPROVED); when(monitoringOfficerService.findMonitoringOfficerForProject(p.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); when(viabilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(ViabilityState.APPROVED); when(financeCheckService.isQueryActionRequired(p.getId(), organisation.getId())).thenReturn(serviceSuccess(false)); GrantOfferLetterStateResource unsentGrantOfferLetterState = GrantOfferLetterStateResource.stateInformationForNonPartnersView(GrantOfferLetterState.PENDING, null); when(golWorkflowHandler.getExtendedState(p)).thenReturn(serviceSuccess(unsentGrantOfferLetterState)); ServiceResult<ProjectTeamStatusResource> result = service.getProjectTeamStatus(p.getId(), Optional.ofNullable(projectUsers.get(0).getId())); assertTrue(result.isSuccess() && LEAD_ACTION_REQUIRED.equals(result.getSuccess().getLeadPartnerStatus().getSpendProfileStatus())); }
@Test public void spendProfileCompleteSubmitted() { when(projectRepository.findById(p.getId())).thenReturn(Optional.of(p)); when(projectUserRepository.findByProjectId(p.getId())).thenReturn(projectUsers); when(projectUserMapper.mapToResource(projectUsers.get(0))).thenReturn(projectUserResources.get(0)); when(organisationRepository.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(partnerOrganisation.get(0)); when(bankDetailsRepository.findByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.of(bankDetails)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.ofNullable(spendProfile)); when(monitoringOfficerService.findMonitoringOfficerForProject(p.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); when(eligibilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(EligibilityState.APPROVED); when(viabilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(ViabilityState.APPROVED); when(financeCheckService.isQueryActionRequired(p.getId(), organisation.getId())).thenReturn(serviceSuccess(false)); GrantOfferLetterStateResource unsentGrantOfferLetterState = GrantOfferLetterStateResource.stateInformationForNonPartnersView(GrantOfferLetterState.PENDING, null); when(golWorkflowHandler.getExtendedState(p)).thenReturn(serviceSuccess(unsentGrantOfferLetterState)); ServiceResult<ProjectTeamStatusResource> result = service.getProjectTeamStatus(p.getId(), Optional.ofNullable(projectUsers.get(0).getId())); assertTrue(result.isSuccess() && PENDING.equals(result.getSuccess().getLeadPartnerStatus().getSpendProfileStatus())); }
@Test public void spendProfileCompleteRejected() { p.setSpendProfileSubmittedDate(null); when(projectRepository.findById(p.getId())).thenReturn(Optional.of(p)); when(projectUserRepository.findByProjectId(p.getId())).thenReturn(projectUsers); when(projectUserMapper.mapToResource(projectUsers.get(0))).thenReturn(projectUserResources.get(0)); when(organisationRepository.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(partnerOrganisation.get(0)); when(bankDetailsRepository.findByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.of(bankDetails)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.ofNullable(spendProfile)); when(eligibilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(EligibilityState.APPROVED); when(monitoringOfficerService.findMonitoringOfficerForProject(p.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); when(viabilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(ViabilityState.APPROVED); when(financeCheckService.isQueryActionRequired(p.getId(), organisation.getId())).thenReturn(serviceSuccess(false)); GrantOfferLetterStateResource unsentGrantOfferLetterState = GrantOfferLetterStateResource.stateInformationForNonPartnersView(GrantOfferLetterState.PENDING, null); when(golWorkflowHandler.getExtendedState(p)).thenReturn(serviceSuccess(unsentGrantOfferLetterState)); ServiceResult<ProjectTeamStatusResource> result = service.getProjectTeamStatus(p.getId(), Optional.ofNullable(projectUsers.get(0).getId())); assertTrue(result.isSuccess() && LEAD_ACTION_REQUIRED.equals(result.getSuccess().getLeadPartnerStatus().getSpendProfileStatus())); assertNull(project.getSpendProfileSubmittedDate()); }
@Test public void internationalOrganisationRequiresActionGivenMissingInternationalLocation() { organisation.setInternational(true); partnerOrganisation.get(0).setInternationalLocation(null); partnerOrganisation.get(0).setPostcode("POSTCODE"); when(projectRepository.findById(p.getId())).thenReturn(Optional.of(p)); when(projectUserRepository.findByProjectId(p.getId())).thenReturn(projectUsers); when(projectUserMapper.mapToResource(projectUsers.get(0))).thenReturn(projectUserResources.get(0)); when(organisationRepository.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(partnerOrganisation.get(0)); when(bankDetailsRepository.findByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.of(bankDetails)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.ofNullable(spendProfile)); when(eligibilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(EligibilityState.APPROVED); when(monitoringOfficerService.findMonitoringOfficerForProject(p.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); when(viabilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(ViabilityState.APPROVED); when(financeCheckService.isQueryActionRequired(p.getId(), organisation.getId())).thenReturn(serviceSuccess(false)); GrantOfferLetterStateResource unsentGrantOfferLetterState = GrantOfferLetterStateResource.stateInformationForNonPartnersView(GrantOfferLetterState.PENDING, null); when(golWorkflowHandler.getExtendedState(p)).thenReturn(serviceSuccess(unsentGrantOfferLetterState)); ServiceResult<ProjectTeamStatusResource> result = service.getProjectTeamStatus(p.getId(), Optional.ofNullable(projectUsers.get(0).getId())); assertTrue(result.isSuccess()); assertEquals(ACTION_REQUIRED, result.getSuccess().getPartnerStatusForOrganisation(organisation.getId()).get().getPartnerProjectLocationStatus()); }
@Test public void internationalOrganisationCompleteGivenPresentInternationalLocation() { organisation.setInternational(true); partnerOrganisation.get(0).setInternationalLocation("Amsterdam"); partnerOrganisation.get(0).setPostcode(null); when(projectRepository.findById(p.getId())).thenReturn(Optional.of(p)); when(projectUserRepository.findByProjectId(p.getId())).thenReturn(projectUsers); when(projectUserMapper.mapToResource(projectUsers.get(0))).thenReturn(projectUserResources.get(0)); when(organisationRepository.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(partnerOrganisation.get(0)); when(bankDetailsRepository.findByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.of(bankDetails)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.ofNullable(spendProfile)); when(eligibilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(EligibilityState.APPROVED); when(monitoringOfficerService.findMonitoringOfficerForProject(p.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); when(viabilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(ViabilityState.APPROVED); when(financeCheckService.isQueryActionRequired(p.getId(), organisation.getId())).thenReturn(serviceSuccess(false)); GrantOfferLetterStateResource unsentGrantOfferLetterState = GrantOfferLetterStateResource.stateInformationForNonPartnersView(GrantOfferLetterState.PENDING, null); when(golWorkflowHandler.getExtendedState(p)).thenReturn(serviceSuccess(unsentGrantOfferLetterState)); ServiceResult<ProjectTeamStatusResource> result = service.getProjectTeamStatus(p.getId(), Optional.ofNullable(projectUsers.get(0).getId())); assertTrue(result.isSuccess()); assertEquals(COMPLETE, result.getSuccess().getPartnerStatusForOrganisation(organisation.getId()).get().getPartnerProjectLocationStatus()); }
@Test public void nonInternationalOrganisationRequiresActionGivenMissingPostcode() { organisation.setInternational(false); partnerOrganisation.get(0).setInternationalLocation("Amsterdam"); partnerOrganisation.get(0).setPostcode(null); when(projectRepository.findById(p.getId())).thenReturn(Optional.of(p)); when(projectUserRepository.findByProjectId(p.getId())).thenReturn(projectUsers); when(projectUserMapper.mapToResource(projectUsers.get(0))).thenReturn(projectUserResources.get(0)); when(organisationRepository.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(partnerOrganisation.get(0)); when(bankDetailsRepository.findByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.of(bankDetails)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.ofNullable(spendProfile)); when(eligibilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(EligibilityState.APPROVED); when(monitoringOfficerService.findMonitoringOfficerForProject(p.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); when(viabilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(ViabilityState.APPROVED); when(financeCheckService.isQueryActionRequired(p.getId(), organisation.getId())).thenReturn(serviceSuccess(false)); GrantOfferLetterStateResource unsentGrantOfferLetterState = GrantOfferLetterStateResource.stateInformationForNonPartnersView(GrantOfferLetterState.PENDING, null); when(golWorkflowHandler.getExtendedState(p)).thenReturn(serviceSuccess(unsentGrantOfferLetterState)); ServiceResult<ProjectTeamStatusResource> result = service.getProjectTeamStatus(p.getId(), Optional.ofNullable(projectUsers.get(0).getId())); assertTrue(result.isSuccess()); assertEquals(ACTION_REQUIRED, result.getSuccess().getPartnerStatusForOrganisation(organisation.getId()).get().getPartnerProjectLocationStatus()); }
@Test public void nonInternationalOrganisationCompleteGivenPresentPostcode() { organisation.setInternational(false); partnerOrganisation.get(0).setInternationalLocation(null); partnerOrganisation.get(0).setPostcode("POSTCODE"); when(projectRepository.findById(p.getId())).thenReturn(Optional.of(p)); when(projectUserRepository.findByProjectId(p.getId())).thenReturn(projectUsers); when(projectUserMapper.mapToResource(projectUsers.get(0))).thenReturn(projectUserResources.get(0)); when(organisationRepository.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(partnerOrganisation.get(0)); when(bankDetailsRepository.findByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.of(bankDetails)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(p.getId(), organisation.getId())).thenReturn(Optional.ofNullable(spendProfile)); when(eligibilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(EligibilityState.APPROVED); when(monitoringOfficerService.findMonitoringOfficerForProject(p.getId())).thenReturn(serviceFailure(CommonErrors.notFoundError(MonitoringOfficer.class))); when(viabilityWorkflowHandler.getState(partnerOrganisation.get(0))).thenReturn(ViabilityState.APPROVED); when(financeCheckService.isQueryActionRequired(p.getId(), organisation.getId())).thenReturn(serviceSuccess(false)); GrantOfferLetterStateResource unsentGrantOfferLetterState = GrantOfferLetterStateResource.stateInformationForNonPartnersView(GrantOfferLetterState.PENDING, null); when(golWorkflowHandler.getExtendedState(p)).thenReturn(serviceSuccess(unsentGrantOfferLetterState)); ServiceResult<ProjectTeamStatusResource> result = service.getProjectTeamStatus(p.getId(), Optional.ofNullable(projectUsers.get(0).getId())); assertTrue(result.isSuccess()); assertEquals(COMPLETE, result.getSuccess().getPartnerStatusForOrganisation(organisation.getId()).get().getPartnerProjectLocationStatus()); } |
UserPermissionRules { @PermissionRule(value = "READ", description = "A user can read their own role") public boolean usersCanViewTheirOwnProcessRole(ProcessRoleResource processRole, UserResource user) { return user.getId().equals(processRole.getUser()); } @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "An internal user can invite a monitoring officer and create the pending user associated.") boolean compAdminProjectFinanceCanCreateMonitoringOfficer(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserRegistrationResource userToCreate, UserResource user); @PermissionRule(value = "VERIFY", description = "A System Registration User can send a new User a verification link by e-mail") boolean systemRegistrationUserCanSendUserVerificationEmail(UserResource userToSendVerificationEmail, UserResource user); @PermissionRule(value = "READ", description = "Any user can view themselves") boolean anyUserCanViewThemselves(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Internal users can view everyone") boolean internalUsersCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can view users in competitions they are assigned to") boolean stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Competition finance users can view users in competitions they are assigned to") boolean competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can view users in projects they are assigned to") boolean monitoringOfficersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ_USER_ORGANISATION", description = "Internal support users can view all users and associated organisations") boolean internalUsersCanViewUserOrganisation(UserOrganisationResource userToView, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "IFS admins can update all users email addresses") boolean ifsAdminCanUpdateAllEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "Support users can update external users email addresses ") boolean supportCanUpdateExternalUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "System Maintenance update all users email addresses") boolean systemMaintenanceUserCanUpdateUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ_INTERNAL", description = "Administrators can view internal users") boolean internalUsersCanViewEveryone(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Support users and administrators can view external users") boolean supportUsersCanViewExternalUsers(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "The System Registration user can view everyone") boolean systemRegistrationUserCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Comp admins and project finance can view assessors") boolean compAdminAndProjectFinanceCanViewAssessors(UserPageResource usersToView, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewOtherConsortiumMembers(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewConsortiumUsersOnApplicationsTheyAreAssessing(UserResource userToView, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "A User should be able to change their own password") boolean usersCanChangeTheirOwnPassword(UserResource userToUpdate, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "The System Registration user should be able to change passwords on behalf of other Users") boolean systemRegistrationUserCanChangePasswordsForUsers(UserResource userToUpdate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A System Registration User can activate Users") boolean systemRegistrationUserCanActivateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "UPDATE", description = "A User can update their own profile") boolean usersCanUpdateTheirOwnProfiles(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE", description = "An admin user can update user details to assign monitoring officers") boolean adminsCanUpdateUserDetails(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile skills") boolean usersCanViewTheirOwnProfileSkills(ProfileSkillsResource profileSkills, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile agreement") boolean usersCanViewTheirOwnProfileAgreement(ProfileAgreementResource profileAgreementResource, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own affiliations") boolean usersCanViewTheirOwnAffiliations(AffiliationResource affiliation, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A user can read their own profile") boolean usersCanViewTheirOwnProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A ifs admin user can read any user's profile") boolean ifsAdminCanViewAnyUsersProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as Comp Admin and Exec can read the user's profile status") boolean usersAndCompAdminCanViewProfileStatus(UserProfileStatusResource profileStatus, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own role") boolean usersCanViewTheirOwnProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the process role of others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewTheProcessRolesOfOtherConsortiumMembers(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Project managers and partners can view the process role for the same organisation") boolean projectPartnersCanViewTheProcessRolesWithinSameApplication(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as internal users can read the user's process role") boolean usersAndInternalUsersCanViewProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the process roles of members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewTheProcessRolesOfConsortiumUsersOnApplicationsTheyAreAssessing(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "CHECK_USER_APPLICATION", description = "The user can check if they have an application for the competition") boolean userCanCheckTheyHaveApplicationForCompetition(UserResource userToCheck, UserResource user); @PermissionRule(value = "EDIT_INTERNAL_USER", description = "Only an IFS Administrator can edit an internal user") boolean ifsAdminCanEditInternalUser(final UserResource userToEdit, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "IFS Administrator can deactivate Users") boolean ifsAdminCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "A Support user can deactivate external Users") boolean supportUserCanDeactivateExternalUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "System Maintenance can deactivate Users") boolean systemMaintenanceUserCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "IFS Administrator can reactivate Users") boolean ifsAdminCanReactivateUsers(UserResource userToReactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A Support user can reactivate external Users") boolean supportUserCanReactivateExternalUsers(UserResource userToActivate, UserResource user); @PermissionRule(value = "AGREE_TERMS", description = "A user can accept the site terms and conditions") boolean usersCanAgreeSiteTermsAndConditions(UserResource userToUpdate, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An assessor can request applicant role") boolean assessorCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant monitoring officer role") boolean isGrantingMonitoringOfficerRoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant a KTA role") boolean isGrantingKTARoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An stakeholder can request applicant role") boolean stakeholderCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An monitoring officer can request applicant role") boolean monitoringOfficerCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "CAN_VIEW_OWN_DASHBOARD", description = "User is requesting own dashboard") boolean isViewingOwnDashboard(UserResource userToView, UserResource user); } | @Test public void usersCanViewTheirOwnProcessRole() { UserResource user = newUserResource().build(); ProcessRoleResource processRoleResource = newProcessRoleResource().withUser(user).build(); assertTrue(rules.usersCanViewTheirOwnProcessRole(processRoleResource, user)); } |
UserPermissionRules { @PermissionRule(value = "READ", description = "The user, as well as internal users can read the user's process role") public boolean usersAndInternalUsersCanViewProcessRole(ProcessRoleResource processRole, UserResource user) { return processRole.getUser().equals(user.getId()) || isInternal(user); } @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "An internal user can invite a monitoring officer and create the pending user associated.") boolean compAdminProjectFinanceCanCreateMonitoringOfficer(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserRegistrationResource userToCreate, UserResource user); @PermissionRule(value = "VERIFY", description = "A System Registration User can send a new User a verification link by e-mail") boolean systemRegistrationUserCanSendUserVerificationEmail(UserResource userToSendVerificationEmail, UserResource user); @PermissionRule(value = "READ", description = "Any user can view themselves") boolean anyUserCanViewThemselves(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Internal users can view everyone") boolean internalUsersCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can view users in competitions they are assigned to") boolean stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Competition finance users can view users in competitions they are assigned to") boolean competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can view users in projects they are assigned to") boolean monitoringOfficersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ_USER_ORGANISATION", description = "Internal support users can view all users and associated organisations") boolean internalUsersCanViewUserOrganisation(UserOrganisationResource userToView, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "IFS admins can update all users email addresses") boolean ifsAdminCanUpdateAllEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "Support users can update external users email addresses ") boolean supportCanUpdateExternalUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "System Maintenance update all users email addresses") boolean systemMaintenanceUserCanUpdateUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ_INTERNAL", description = "Administrators can view internal users") boolean internalUsersCanViewEveryone(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Support users and administrators can view external users") boolean supportUsersCanViewExternalUsers(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "The System Registration user can view everyone") boolean systemRegistrationUserCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Comp admins and project finance can view assessors") boolean compAdminAndProjectFinanceCanViewAssessors(UserPageResource usersToView, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewOtherConsortiumMembers(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewConsortiumUsersOnApplicationsTheyAreAssessing(UserResource userToView, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "A User should be able to change their own password") boolean usersCanChangeTheirOwnPassword(UserResource userToUpdate, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "The System Registration user should be able to change passwords on behalf of other Users") boolean systemRegistrationUserCanChangePasswordsForUsers(UserResource userToUpdate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A System Registration User can activate Users") boolean systemRegistrationUserCanActivateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "UPDATE", description = "A User can update their own profile") boolean usersCanUpdateTheirOwnProfiles(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE", description = "An admin user can update user details to assign monitoring officers") boolean adminsCanUpdateUserDetails(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile skills") boolean usersCanViewTheirOwnProfileSkills(ProfileSkillsResource profileSkills, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile agreement") boolean usersCanViewTheirOwnProfileAgreement(ProfileAgreementResource profileAgreementResource, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own affiliations") boolean usersCanViewTheirOwnAffiliations(AffiliationResource affiliation, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A user can read their own profile") boolean usersCanViewTheirOwnProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A ifs admin user can read any user's profile") boolean ifsAdminCanViewAnyUsersProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as Comp Admin and Exec can read the user's profile status") boolean usersAndCompAdminCanViewProfileStatus(UserProfileStatusResource profileStatus, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own role") boolean usersCanViewTheirOwnProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the process role of others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewTheProcessRolesOfOtherConsortiumMembers(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Project managers and partners can view the process role for the same organisation") boolean projectPartnersCanViewTheProcessRolesWithinSameApplication(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as internal users can read the user's process role") boolean usersAndInternalUsersCanViewProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the process roles of members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewTheProcessRolesOfConsortiumUsersOnApplicationsTheyAreAssessing(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "CHECK_USER_APPLICATION", description = "The user can check if they have an application for the competition") boolean userCanCheckTheyHaveApplicationForCompetition(UserResource userToCheck, UserResource user); @PermissionRule(value = "EDIT_INTERNAL_USER", description = "Only an IFS Administrator can edit an internal user") boolean ifsAdminCanEditInternalUser(final UserResource userToEdit, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "IFS Administrator can deactivate Users") boolean ifsAdminCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "A Support user can deactivate external Users") boolean supportUserCanDeactivateExternalUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "System Maintenance can deactivate Users") boolean systemMaintenanceUserCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "IFS Administrator can reactivate Users") boolean ifsAdminCanReactivateUsers(UserResource userToReactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A Support user can reactivate external Users") boolean supportUserCanReactivateExternalUsers(UserResource userToActivate, UserResource user); @PermissionRule(value = "AGREE_TERMS", description = "A user can accept the site terms and conditions") boolean usersCanAgreeSiteTermsAndConditions(UserResource userToUpdate, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An assessor can request applicant role") boolean assessorCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant monitoring officer role") boolean isGrantingMonitoringOfficerRoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant a KTA role") boolean isGrantingKTARoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An stakeholder can request applicant role") boolean stakeholderCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An monitoring officer can request applicant role") boolean monitoringOfficerCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "CAN_VIEW_OWN_DASHBOARD", description = "User is requesting own dashboard") boolean isViewingOwnDashboard(UserResource userToView, UserResource user); } | @Test public void usersCanViewTheirOwnProcessRoleButNotAnotherUsersProcessRole() { UserResource user1 = newUserResource().withId(1L).build(); UserResource user2 = newUserResource().withId(2L).build(); ProcessRoleResource anotherUsersprocessRoleResource = newProcessRoleResource().withUser(user2).build(); assertFalse(rules.usersAndInternalUsersCanViewProcessRole(anotherUsersprocessRoleResource, user1)); }
@Test public void compAdminCanViewUserProcessRole() { UserResource user = newUserResource().build(); ProcessRoleResource processRoleResource = newProcessRoleResource().withUser(user).build(); assertTrue(rules.usersAndInternalUsersCanViewProcessRole(processRoleResource, compAdminUser())); }
@Test public void projectFinanceCanViewUserProcessRole() { UserResource user = newUserResource().build(); ProcessRoleResource processRoleResource = newProcessRoleResource().withUser(user).build(); assertTrue(rules.usersAndInternalUsersCanViewProcessRole(processRoleResource, projectFinanceUser())); } |
InternalUserProjectStatusServiceImpl extends AbstractProjectServiceImpl implements InternalUserProjectStatusService { @Override @Transactional public ServiceResult<ProjectStatusPageResource> getCompetitionStatus(long competitionId, String applicationSearchString, int page, int size) { Page<Project> result = projectRepository.searchByCompetitionIdAndApplicationIdLike(competitionId, applicationSearchString, PageRequest.of(page, size)); return serviceSuccess(new ProjectStatusPageResource(result.getTotalElements(), result.getTotalPages(), getProjectStatuses(result::getContent), result.getNumber(), result.getSize())); } @Override @Transactional //Write transaction for first time creation of project finances. ServiceResult<ProjectStatusPageResource> getCompetitionStatus(long competitionId,
String applicationSearchString,
int page,
int size); @Override ServiceResult<List<ProjectStatusResource>> getPreviousCompetitionStatus(long competitionId); @Override ServiceResult<ProjectStatusResource> getProjectStatusByProject(Project project); @Override ServiceResult<ProjectStatusResource> getProjectStatusByProjectId(Long projectId); } | @Test public void getCompetitionStatus() { long competitionId = 123L; String applicationSearchString = "1"; List<Project> projects = setupCompetitionStatusMocks(competitionId); Page<Project> page = new PageImpl<>(projects, PageRequest.of(0, 5), 3); when(projectRepository.searchByCompetitionIdAndApplicationIdLike(competitionId, applicationSearchString, PageRequest.of(0,5))).thenReturn(page); ServiceResult<ProjectStatusPageResource> result = service.getCompetitionStatus(competitionId, applicationSearchString, 0, 5); assertTrue(result.isSuccess()); List<ProjectStatusResource> projectStatusResources = result.getSuccess().getContent(); assertTrue(projectsGetSortedByApplicationId(projectStatusResources)); assertEquals(3, projectStatusResources.size()); assertEquals(Integer.valueOf(3), projectStatusResources.get(0).getNumberOfPartners()); assertEquals(Integer.valueOf(3), projectStatusResources.get(1).getNumberOfPartners()); assertEquals(Integer.valueOf(3), projectStatusResources.get(2).getNumberOfPartners()); } |
InternalUserProjectStatusServiceImpl extends AbstractProjectServiceImpl implements InternalUserProjectStatusService { @Override public ServiceResult<List<ProjectStatusResource>> getPreviousCompetitionStatus(long competitionId) { return serviceSuccess(getProjectStatuses(() -> projectRepository.findByApplicationCompetitionIdAndProjectProcessActivityStateIn(competitionId, COMPLETED_STATES))); } @Override @Transactional //Write transaction for first time creation of project finances. ServiceResult<ProjectStatusPageResource> getCompetitionStatus(long competitionId,
String applicationSearchString,
int page,
int size); @Override ServiceResult<List<ProjectStatusResource>> getPreviousCompetitionStatus(long competitionId); @Override ServiceResult<ProjectStatusResource> getProjectStatusByProject(Project project); @Override ServiceResult<ProjectStatusResource> getProjectStatusByProjectId(Long projectId); } | @Test public void getPreviousCompetitionStatus() { long competitionId = 123L; List<Project> projects = setupCompetitionStatusMocks(competitionId); when(projectRepository.findByApplicationCompetitionIdAndProjectProcessActivityStateIn(competitionId, COMPLETED_STATES)).thenReturn(projects); ServiceResult<List<ProjectStatusResource>> result = service.getPreviousCompetitionStatus(competitionId); assertTrue(result.isSuccess()); List<ProjectStatusResource> projectStatusResources = result.getSuccess(); assertTrue(projectsGetSortedByApplicationId(projectStatusResources)); assertEquals(3, projectStatusResources.size()); assertEquals(Integer.valueOf(3), projectStatusResources.get(0).getNumberOfPartners()); assertEquals(Integer.valueOf(3), projectStatusResources.get(1).getNumberOfPartners()); assertEquals(Integer.valueOf(3), projectStatusResources.get(2).getNumberOfPartners()); } |
InternalUserProjectStatusServiceImpl extends AbstractProjectServiceImpl implements InternalUserProjectStatusService { private ProjectStatusResource getProjectStatusResourceByProject(Project project) { boolean locationPerPartnerRequired = project.getApplication().getCompetition().isLocationPerPartner(); ProjectActivityStates partnerProjectLocationStatus = getPartnerProjectLocationStatus(project); ProjectActivityStates projectDetailsStatus = getProjectDetailsStatus(project, locationPerPartnerRequired, partnerProjectLocationStatus); ProjectActivityStates projectTeamStatus = getProjectTeamStatus(project); ProjectActivityStates financeChecksStatus = getFinanceChecksStatus(project); ProjectActivityStates bankDetailsStatus = getBankDetailsStatus(project); ProjectActivityStates spendProfileStatus = getSpendProfileStatus(project, financeChecksStatus); ProjectActivityStates documentsStatus = documentsState(project); boolean sentToIfsPa = sentToIfsPa(project); return new ProjectStatusResource( project.getName(), project.getId(), project.getId().toString(), project.getApplication().getId(), project.getApplication().getId().toString(), project.getPartnerOrganisations().size(), project.getLeadOrganisation().map(PartnerOrganisation::getOrganisation).map(Organisation::getName).orElse(""), projectDetailsStatus, projectTeamStatus, bankDetailsStatus, financeChecksStatus, spendProfileStatus, getMonitoringOfficerStatus(project, projectDetailsStatus, locationPerPartnerRequired, partnerProjectLocationStatus), documentsStatus, getGrantOfferLetterState(project, bankDetailsStatus, spendProfileStatus, documentsStatus), getProjectSetupCompleteState(project, spendProfileStatus, documentsStatus), golWorkflowHandler.isSent(project), project.getProjectState(), sentToIfsPa); } @Override @Transactional //Write transaction for first time creation of project finances. ServiceResult<ProjectStatusPageResource> getCompetitionStatus(long competitionId,
String applicationSearchString,
int page,
int size); @Override ServiceResult<List<ProjectStatusResource>> getPreviousCompetitionStatus(long competitionId); @Override ServiceResult<ProjectStatusResource> getProjectStatusByProject(Project project); @Override ServiceResult<ProjectStatusResource> getProjectStatusByProjectId(Long projectId); } | @Test public void getProjectStatusResourceByProject() { long projectId = 2345L; Project project = createProjectStatusResource(projectId, ApprovalType.EMPTY, false, false, false, false, true ); when(projectFinanceService.financeChecksDetails(anyLong(), anyLong())).thenReturn(serviceSuccess(newProjectFinanceResource().thatIsRequestingFunding().build())); ServiceResult<ProjectStatusResource> result = service.getProjectStatusByProjectId(projectId); ProjectStatusResource returnedProjectStatusResource = result.getSuccess(); assertTrue(result.isSuccess()); assertEquals(project.getName(), returnedProjectStatusResource.getProjectTitle()); assertEquals(project.getId(), returnedProjectStatusResource.getProjectNumber()); assertEquals(Integer.valueOf(1), returnedProjectStatusResource.getNumberOfPartners()); assertEquals(PENDING, returnedProjectStatusResource.getProjectDetailsStatus()); assertEquals(ACTION_REQUIRED, returnedProjectStatusResource.getBankDetailsStatus()); assertEquals(ACTION_REQUIRED, returnedProjectStatusResource.getFinanceChecksStatus()); assertEquals(NOT_STARTED, returnedProjectStatusResource.getSpendProfileStatus()); assertEquals(COMPLETE, returnedProjectStatusResource.getMonitoringOfficerStatus()); assertEquals(NOT_STARTED, returnedProjectStatusResource.getGrantOfferLetterStatus()); assertEquals(NOT_STARTED, returnedProjectStatusResource.getGrantOfferLetterStatus()); when(projectRepository.findById(projectId)).thenReturn(Optional.empty()); ServiceResult<ProjectStatusResource> resultFailure = service.getProjectStatusByProjectId(projectId); assertTrue(resultFailure.isFailure()); } |
ProjectTeamController { @PostMapping("/{projectId}/team/remove-user/{userId}") public RestResult<Void> removeUser(@PathVariable("projectId") final long projectId, @PathVariable("userId") final long userId) { ProjectUserCompositeId composite = new ProjectUserCompositeId(projectId, userId); return projectTeamService.removeUser(composite).toPostResponse(); } ProjectTeamController(ProjectTeamService projectTeamService); @PostMapping("/{projectId}/team/remove-user/{userId}") RestResult<Void> removeUser(@PathVariable("projectId") final long projectId,
@PathVariable("userId") final long userId); @PostMapping("/{projectId}/team/remove-invite/{inviteId}") RestResult<Void> removeInvite(@PathVariable("projectId") final long projectId,
@PathVariable("inviteId") final long inviteId); @PostMapping("/{projectId}/team/invite") RestResult<Void> inviteTeamMember(@PathVariable("projectId") final long projectId,
@RequestBody @Valid final ProjectUserInviteResource inviteResource); } | @Test public void removeUser() throws Exception { long projectId = 123L; long userId = 456L; ProjectUserCompositeId composite = new ProjectUserCompositeId(projectId, userId); when(projectTeamService.removeUser(composite)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/team/remove-user/{userId}", projectId, userId)) .andExpect(status().isOk()); verify(projectTeamService).removeUser(composite); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.