src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ProjectTeamController { @PostMapping("/{projectId}/team/remove-invite/{inviteId}") public RestResult<Void> removeInvite(@PathVariable("projectId") final long projectId, @PathVariable("inviteId") final long inviteId) { return projectTeamService.removeInvite(inviteId, projectId).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 removeInvite() throws Exception { long projectId = 456L; long inviteId = 789L; when(projectTeamService.removeInvite(inviteId, projectId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/team/remove-invite/{inviteId}", projectId, inviteId)) .andExpect(status().isOk()); verify(projectTeamService).removeInvite(inviteId, projectId); }
ProjectTeamController { @PostMapping("/{projectId}/team/invite") public RestResult<Void> inviteTeamMember(@PathVariable("projectId") final long projectId, @RequestBody @Valid final ProjectUserInviteResource inviteResource) { return projectTeamService.inviteTeamMember(projectId, inviteResource).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 inviteTeamMember() throws Exception { long projectId = 1L; ProjectUserInviteResource invite = newProjectUserInviteResource().build(); when(projectTeamService.inviteTeamMember(projectId, invite)).thenReturn(serviceSuccess()); mockMvc.perform(post(String.format("/project/%d/team/invite", projectId)) .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(invite))) .andExpect(status().isOk()); }
ProjectTeamServiceImpl extends AbstractProjectServiceImpl implements ProjectTeamService { @Override @Transactional public ServiceResult<Void> inviteTeamMember(long projectId, ProjectUserInviteResource inviteResource) { return getProject(projectId) .andOnSuccess(project -> validateGOLGenerated(project, PROJECT_SETUP_PROJECT_MANAGER_CANNOT_BE_UPDATED_IF_GOL_GENERATED)) .andOnSuccess(() -> saveProjectInvite(inviteResource)) .andOnSuccess(() -> inviteContact(projectId, inviteResource, Notifications.INVITE_PROJECT_MEMBER)); } ProjectTeamServiceImpl(); @Override @Transactional ServiceResult<Void> removeInvite(long inviteId, long projectId); @Override @Transactional ServiceResult<Void> removeUser(ProjectUserCompositeId composite); @Override @Transactional ServiceResult<Void> inviteTeamMember(long projectId, ProjectUserInviteResource inviteResource); }
@Test public void inviteProjectManagerWhenGOLAlreadyGenerated() { Long projectId = 1L; ProjectUserInviteResource inviteResource = newProjectUserInviteResource() .build(); FileEntry golFile = newFileEntry().withFilesizeBytes(10).withMediaType("application/pdf").build(); Project projectInDB = ProjectBuilder.newProject() .withId(projectId) .withGrantOfferLetter(golFile) .build(); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.of(projectInDB)); ServiceResult<Void> result = service.inviteTeamMember(projectId, inviteResource); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(PROJECT_SETUP_PROJECT_MANAGER_CANNOT_BE_UPDATED_IF_GOL_GENERATED)); } @Test public void inviteProjectManagerWhenUnableToSendNotification() { Project projectInDB = ProjectBuilder.newProject() .withName("Project 1") .withApplication(application) .build(); Organisation leadOrganisation = newOrganisation() .withId(89L) .withName("Lead Organisation") .build(); ProjectUserInviteResource inviteResource = newProjectUserInviteResource() .withCompetitionName("Competition 1") .withApplicationId(application.getId()) .withName("Abc Xyz") .withEmail("[email protected]") .withLeadOrganisation(leadOrganisation.getId()) .withLeadOrganisation(leadOrganisation.getName()) .withOrganisationName("Invite Organisation 1") .withHash("sample/url") .withProject(projectInDB.getId()) .withOrganisation(organisation.getId()) .build(); ProjectUserInvite projectInvite = newProjectUserInvite() .withId(333L) .withEmail("[email protected]") .withName("Abc Xyz") .withOrganisation(organisation) .withProject(projectInDB) .build(); ProjectResource projectResource = new ProjectResource(); projectResource.setName("Project 1"); projectResource.setApplication(application.getId()); when(organisationRepositoryMock.findDistinctByProcessRolesUser(any(User.class))).thenReturn(singletonList(organisation)); when(userRepositoryMock.findByEmail(user.getEmail())).thenReturn(Optional.of(user)); when(projectUserInviteRepositoryMock.findByProjectId(projectInDB.getId())).thenReturn(singletonList(projectInvite)); when(projectMapperMock.mapToResource(projectInDB)).thenReturn(projectResource); when(organisationRepositoryMock.findById(inviteResource.getLeadOrganisationId())).thenReturn(Optional.of(leadOrganisation)); when(projectServiceMock.getProjectById(projectInDB.getId())).thenReturn(serviceSuccess(projectResource)); when(projectRepositoryMock.findById(projectInDB.getId())).thenReturn(Optional.of(projectInDB)); when(projectInviteMapperMock.mapToResource(projectInvite)).thenReturn(inviteResource); when(projectInviteMapperMock.mapToDomain(inviteResource)).thenReturn(projectInvite); when(projectInviteValidator.validate(any())).thenReturn(serviceSuccess()); NotificationTarget to = new UserNotificationTarget("Abc Xyz", "[email protected]"); Map<String, Object> globalArguments = new HashMap<>(); globalArguments.put("projectName", projectInDB.getName()); globalArguments.put("applicationId", application.getId()); globalArguments.put("leadOrganisation", organisation.getName()); globalArguments.put("inviteOrganisationName", "Invite Organisation 1"); globalArguments.put("competitionName", "Competition 1"); globalArguments.put("inviteUrl", webBaseUrl + "/project-setup/accept-invite/" + inviteResource.getHash()); Notification notification = new Notification(systemNotificationSourceMock, to, ProjectTeamServiceImpl.Notifications.INVITE_PROJECT_MEMBER, globalArguments); when(notificationServiceMock.sendNotificationWithFlush(notification, EMAIL)) .thenReturn(serviceFailure(new Error(NOTIFICATIONS_UNABLE_TO_SEND_MULTIPLE))); ServiceResult<Void> result = service.inviteTeamMember(projectInDB.getId(), inviteResource); verify(notificationServiceMock).sendNotificationWithFlush(notification, EMAIL); assertTrue(result.isFailure()); assertEquals(NOTIFICATIONS_UNABLE_TO_SEND_MULTIPLE.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); verify(projectUserInviteRepositoryMock, times(1)).save(projectInvite); } @Test public void inviteProjectManagerSuccess() { Project projectInDB = ProjectBuilder.newProject() .withName("Project 1") .withApplication(application) .build(); Organisation leadOrganisation = newOrganisation() .withId(89L) .withName("Lead Organisation") .build(); ProjectUserInviteResource inviteResource = newProjectUserInviteResource() .withCompetitionName("Competition 1") .withApplicationId(application.getId()) .withName("Abc Xyz") .withEmail("[email protected]") .withLeadOrganisation(organisation.getId()) .withLeadOrganisation(leadOrganisation.getId()) .withLeadOrganisation(leadOrganisation.getName()) .withOrganisationName("Invite Organisation 1") .withHash("sample/url") .withProject(projectInDB.getId()) .withOrganisation(organisation.getId()) .build(); ProjectUserInvite projectInvite = newProjectUserInvite() .withId(333L) .withEmail("[email protected]") .withName("Abc Xyz") .withOrganisation(organisation) .withProject(projectInDB) .build(); ProjectResource projectResource = new ProjectResource(); projectResource.setName("Project 1"); projectResource.setApplication(application.getId()); when(projectRepositoryMock.findById(projectInDB.getId())).thenReturn(Optional.of(projectInDB)); ProjectUserInviteResource projectUserInviteResource = getMapper(ProjectUserInviteMapper.class).mapToResource(projectInvite); when(userRepositoryMock.findByEmail(user.getEmail())).thenReturn(Optional.of(user)); when(projectUserInviteRepositoryMock.findByProjectId(projectInDB.getId())).thenReturn(singletonList(projectInvite)); when(projectMapperMock.mapToResource(projectInDB)).thenReturn(projectResource); when(organisationRepositoryMock.findById(inviteResource.getLeadOrganisationId())).thenReturn(Optional.of(leadOrganisation)); when(projectServiceMock.getProjectById(projectInDB.getId())).thenReturn(serviceSuccess(projectResource)); when(projectInviteMapperMock.mapToResource(projectInvite)).thenReturn(inviteResource); when(projectInviteMapperMock.mapToDomain(projectUserInviteResource)).thenReturn(projectInvite); when(projectInviteValidator.validate(any())).thenReturn(serviceSuccess()); NotificationTarget to = new UserNotificationTarget("Abc Xyz", "[email protected]"); Map<String, Object> globalArguments = new HashMap<>(); globalArguments.put("projectName", projectInDB.getName()); globalArguments.put("applicationId", application.getId()); globalArguments.put("leadOrganisation", organisation.getName()); globalArguments.put("inviteOrganisationName", "Invite Organisation 1"); globalArguments.put("competitionName", "Competition 1"); globalArguments.put("inviteUrl", webBaseUrl + "/project-setup/accept-invite/" + inviteResource.getHash()); Notification notification = new Notification(systemNotificationSourceMock, to, ProjectTeamServiceImpl.Notifications.INVITE_PROJECT_MEMBER, globalArguments); when(notificationServiceMock.sendNotificationWithFlush(notification, EMAIL)).thenReturn(serviceSuccess()); when(projectInviteMapperMock.mapToDomain(inviteResource)).thenReturn(projectInvite); ServiceResult<Void> result = service.inviteTeamMember(projectInDB.getId(), inviteResource); assertTrue(result.isSuccess()); verify(notificationServiceMock).sendNotificationWithFlush(notification, EMAIL); verify(projectUserInviteRepositoryMock, times(1)).save(projectInvite); }
ProjectTeamServiceImpl extends AbstractProjectServiceImpl implements ProjectTeamService { @Override @Transactional public ServiceResult<Void> removeUser(ProjectUserCompositeId composite) { return getProject(composite.getProjectId()).andOnSuccess( project -> validateUserNotPm(project, composite.getUserId()).andOnSuccess( () -> validateUserNotFc(project, composite.getUserId()).andOnSuccess( () -> validateUserNotRemovingThemselves(composite.getUserId()).andOnSuccess( () -> migrateProcessesFromUserIfNecessary(composite.getUserId(), project).andOnSuccess( migratedProject -> removeUserFromProject(composite.getUserId(), migratedProject))) ))); } ProjectTeamServiceImpl(); @Override @Transactional ServiceResult<Void> removeInvite(long inviteId, long projectId); @Override @Transactional ServiceResult<Void> removeUser(ProjectUserCompositeId composite); @Override @Transactional ServiceResult<Void> inviteTeamMember(long projectId, ProjectUserInviteResource inviteResource); }
@Test public void removeUser() { User loggedInUser = newUser().build(); setLoggedInUser(newUserResource() .withId(loggedInUser.getId()) .withRolesGlobal(singletonList(Role.PARTNER)) .build()); User userToRemove = newUser().build(); ProjectUser projectUserToRemove = newProjectUser() .withRole(PROJECT_PARTNER) .withUser(userToRemove) .build(); Project project = newProject() .withProjectProcess(newProjectProcess() .withProjectUser(newProjectUser() .withUser(newUser().build()) .build()) .build()) .withProjectUsers(singletonList(projectUserToRemove)).build(); when(userRepositoryMock.findById(loggedInUser.getId())).thenReturn(Optional.of(loggedInUser)); when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project)); service.removeUser(new ProjectUserCompositeId(project.getId(), userToRemove.getId())); verify(projectRepositoryMock).findById(project.getId()); assertTrue(project.getProjectUsers().isEmpty()); } @Test public void removeUserFailsFinanceContact() { User loggedInUser = newUser().build(); setLoggedInUser(newUserResource() .withId(loggedInUser.getId()) .withRolesGlobal(Collections.singletonList(Role.PARTNER)) .build()); User userToRemove = newUser().build(); ProjectUser projectUserToRemove = newProjectUser() .withRole(PROJECT_FINANCE_CONTACT) .withUser(userToRemove) .build(); Project project = newProject().withProjectUsers(singletonList(projectUserToRemove)).build(); when(userRepositoryMock.findById(loggedInUser.getId())).thenReturn(Optional.of(loggedInUser)); when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project)); when(projectUserRepositoryMock.findByProjectIdAndUserId(project.getId(), userToRemove.getId())).thenReturn( singletonList(projectUserToRemove)); service.removeUser(new ProjectUserCompositeId(project.getId(), userToRemove.getId())); verify(projectRepositoryMock).findById(project.getId()); verifyZeroInteractions(projectUserRepositoryMock); assertTrue(project.getProjectUsers().contains(projectUserToRemove)); } @Test public void removeUserFailsProjectManager() { User loggedInUser = newUser().build(); setLoggedInUser(newUserResource() .withId(loggedInUser.getId()) .withRolesGlobal(Collections.singletonList(Role.PARTNER)) .build()); User userToRemove = newUser().build(); ProjectUser projectUserToRemove = newProjectUser() .withRole(PROJECT_MANAGER) .withUser(userToRemove) .build(); Project project = newProject().withProjectUsers(singletonList(projectUserToRemove)).build(); when(userRepositoryMock.findById(loggedInUser.getId())).thenReturn(Optional.of(loggedInUser)); when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project)); when(projectUserRepositoryMock.findByProjectIdAndUserId(project.getId(), userToRemove.getId())).thenReturn( singletonList(projectUserToRemove)); service.removeUser(new ProjectUserCompositeId(project.getId(), userToRemove.getId())); verify(projectRepositoryMock).findById(project.getId()); verifyZeroInteractions(projectUserRepositoryMock); assertTrue(project.getProjectUsers().contains(projectUserToRemove)); }
ProjectTeamServiceImpl extends AbstractProjectServiceImpl implements ProjectTeamService { @Override @Transactional public ServiceResult<Void> removeInvite(long inviteId, long projectId) { return getInvite(inviteId) .andOnSuccess(invite -> getProject(projectId) .andOnSuccess(project -> validateInvite(invite, project) .andOnSuccess(() -> deleteInvite(invite) ) ) ); } ProjectTeamServiceImpl(); @Override @Transactional ServiceResult<Void> removeInvite(long inviteId, long projectId); @Override @Transactional ServiceResult<Void> removeUser(ProjectUserCompositeId composite); @Override @Transactional ServiceResult<Void> inviteTeamMember(long projectId, ProjectUserInviteResource inviteResource); }
@Test public void removeInviteFailsWrongProject() { Project project = newProject().build(); Project wrongProject = newProject().build(); ProjectUserInvite invite = newProjectUserInvite() .withProject(wrongProject) .withStatus(SENT) .build(); when(projectUserInviteRepositoryMock.findById(invite.getId())).thenReturn(Optional.of(invite)); when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project)); ServiceResult<Void> result = service.removeInvite(invite.getId(), project.getId()); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(PROJECT_INVITE_NOT_FOR_CORRECT_PROJECT)); verify(projectUserInviteRepositoryMock, never()).delete(invite); } @Test public void removeInviteFailsWrongStatus() { Project project = newProject().build(); ProjectUserInvite invite = newProjectUserInvite() .withProject(project) .withStatus(OPENED) .build(); when(projectUserInviteRepositoryMock.findById(invite.getId())).thenReturn(Optional.of(invite)); when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project)); ServiceResult<Void> result = service.removeInvite(invite.getId(), project.getId()); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(PROJECT_INVITE_ALREADY_OPENED)); verify(projectUserInviteRepositoryMock, never()).delete(invite); } @Test public void removeInviteSucceeds() { Project project = newProject().build(); ProjectUserInvite invite = newProjectUserInvite() .withProject(project) .withStatus(SENT) .build(); when(projectUserInviteRepositoryMock.findById(invite.getId())).thenReturn(Optional.of(invite)); when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project)); ServiceResult<Void> result = service.removeInvite(invite.getId(), project.getId()); assertTrue(result.isSuccess()); verify(projectUserInviteRepositoryMock).delete(invite); }
PendingPartnerProgressServiceImpl extends RootTransactionalService implements PendingPartnerProgressService { @Override public ServiceResult<PendingPartnerProgressResource> getPendingPartnerProgress(ProjectOrganisationCompositeId projectOrganisationCompositeId) { return getPartnerProgress(projectOrganisationCompositeId) .andOnSuccessReturn(pendingPartnerProgressMapper::mapToResource); } @Override ServiceResult<PendingPartnerProgressResource> getPendingPartnerProgress(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourOrganisationComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourFundingComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markTermsAndConditionsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourOrganisationIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourFundingIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markTermsAndConditionsIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> completePartnerSetup(ProjectOrganisationCompositeId projectOrganisationCompositeId); }
@Test public void getPendingPartnerProgress() { PendingPartnerProgress pendingPartnerProgress = new PendingPartnerProgress(null); when(pendingPartnerProgressRepository.findByOrganisationIdAndProjectId(PROJECT_ID, ORGANISATION_ID)).thenReturn(Optional.of(pendingPartnerProgress)); PendingPartnerProgressResource resource = new PendingPartnerProgressResource(); when(pendingPartnerProgressMapper.mapToResource(pendingPartnerProgress)).thenReturn(resource); ServiceResult<PendingPartnerProgressResource> result = service.getPendingPartnerProgress(id(PROJECT_ID, ORGANISATION_ID)); assertTrue(result.isSuccess()); assertEquals(resource, result.getSuccess()); }
PendingPartnerProgressServiceImpl extends RootTransactionalService implements PendingPartnerProgressService { @Override @Transactional public ServiceResult<Void> markYourOrganisationComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId) { return getPartnerProgress(projectOrganisationCompositeId) .andOnSuccessReturnVoid(PendingPartnerProgress::markYourOrganisationComplete); } @Override ServiceResult<PendingPartnerProgressResource> getPendingPartnerProgress(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourOrganisationComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourFundingComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markTermsAndConditionsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourOrganisationIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourFundingIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markTermsAndConditionsIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> completePartnerSetup(ProjectOrganisationCompositeId projectOrganisationCompositeId); }
@Test public void markYourOrganisationComplete() { PendingPartnerProgress pendingPartnerProgress = new PendingPartnerProgress(null); when(pendingPartnerProgressRepository.findByOrganisationIdAndProjectId(PROJECT_ID, ORGANISATION_ID)).thenReturn(Optional.of(pendingPartnerProgress)); ServiceResult<Void> result = service.markYourOrganisationComplete(id(PROJECT_ID, ORGANISATION_ID)); assertTrue(result.isSuccess()); assertTrue(pendingPartnerProgress.isYourOrganisationComplete()); }
PendingPartnerProgressServiceImpl extends RootTransactionalService implements PendingPartnerProgressService { @Override @Transactional public ServiceResult<Void> markYourFundingComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId) { return getPartnerProgress(projectOrganisationCompositeId) .andOnSuccessReturnVoid(PendingPartnerProgress::markYourFundingComplete); } @Override ServiceResult<PendingPartnerProgressResource> getPendingPartnerProgress(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourOrganisationComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourFundingComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markTermsAndConditionsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourOrganisationIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourFundingIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markTermsAndConditionsIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> completePartnerSetup(ProjectOrganisationCompositeId projectOrganisationCompositeId); }
@Test public void markYourFundingComplete() { PendingPartnerProgress pendingPartnerProgress = new PendingPartnerProgress(null); when(pendingPartnerProgressRepository.findByOrganisationIdAndProjectId(PROJECT_ID, ORGANISATION_ID)).thenReturn(Optional.of(pendingPartnerProgress)); ServiceResult<Void> result = service.markYourFundingComplete(id(PROJECT_ID, ORGANISATION_ID)); assertTrue(result.isSuccess()); assertTrue(pendingPartnerProgress.isYourFundingComplete()); }
PendingPartnerProgressServiceImpl extends RootTransactionalService implements PendingPartnerProgressService { @Override @Transactional public ServiceResult<Void> markTermsAndConditionsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId) { return getPartnerProgress(projectOrganisationCompositeId) .andOnSuccessReturnVoid(PendingPartnerProgress::markTermsAndConditionsComplete); } @Override ServiceResult<PendingPartnerProgressResource> getPendingPartnerProgress(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourOrganisationComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourFundingComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markTermsAndConditionsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourOrganisationIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourFundingIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markTermsAndConditionsIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> completePartnerSetup(ProjectOrganisationCompositeId projectOrganisationCompositeId); }
@Test public void markTermsAndConditionsComplete() { PendingPartnerProgress pendingPartnerProgress = new PendingPartnerProgress(null); when(pendingPartnerProgressRepository.findByOrganisationIdAndProjectId(PROJECT_ID, ORGANISATION_ID)).thenReturn(Optional.of(pendingPartnerProgress)); ServiceResult<Void> result = service.markTermsAndConditionsComplete(id(PROJECT_ID, ORGANISATION_ID)); assertTrue(result.isSuccess()); assertTrue(pendingPartnerProgress.isTermsAndConditionsComplete()); }
PendingPartnerProgressServiceImpl extends RootTransactionalService implements PendingPartnerProgressService { @Override @Transactional public ServiceResult<Void> markYourOrganisationIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId) { return getPartnerProgress(projectOrganisationCompositeId) .andOnSuccessReturnVoid(PendingPartnerProgress::markYourOrganisationIncomplete); } @Override ServiceResult<PendingPartnerProgressResource> getPendingPartnerProgress(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourOrganisationComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourFundingComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markTermsAndConditionsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourOrganisationIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourFundingIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markTermsAndConditionsIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> completePartnerSetup(ProjectOrganisationCompositeId projectOrganisationCompositeId); }
@Test public void markYourOrganisationIncomplete() { PendingPartnerProgress pendingPartnerProgress = new PendingPartnerProgress(null); when(pendingPartnerProgressRepository.findByOrganisationIdAndProjectId(PROJECT_ID, ORGANISATION_ID)).thenReturn(Optional.of(pendingPartnerProgress)); ServiceResult<Void> result = service.markYourOrganisationIncomplete(id(PROJECT_ID, ORGANISATION_ID)); assertTrue(result.isSuccess()); assertFalse(pendingPartnerProgress.isYourOrganisationComplete()); }
PendingPartnerProgressServiceImpl extends RootTransactionalService implements PendingPartnerProgressService { @Override @Transactional public ServiceResult<Void> markYourFundingIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId) { return getPartnerProgress(projectOrganisationCompositeId) .andOnSuccessReturnVoid(PendingPartnerProgress::markYourFundingIncomplete); } @Override ServiceResult<PendingPartnerProgressResource> getPendingPartnerProgress(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourOrganisationComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourFundingComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markTermsAndConditionsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourOrganisationIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourFundingIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markTermsAndConditionsIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> completePartnerSetup(ProjectOrganisationCompositeId projectOrganisationCompositeId); }
@Test public void markYourFundingIncomplete() { PendingPartnerProgress pendingPartnerProgress = new PendingPartnerProgress(null); when(pendingPartnerProgressRepository.findByOrganisationIdAndProjectId(PROJECT_ID, ORGANISATION_ID)).thenReturn(Optional.of(pendingPartnerProgress)); ServiceResult<Void> result = service.markYourFundingIncomplete(id(PROJECT_ID, ORGANISATION_ID)); assertTrue(result.isSuccess()); assertFalse(pendingPartnerProgress.isYourFundingComplete()); }
PendingPartnerProgressServiceImpl extends RootTransactionalService implements PendingPartnerProgressService { @Override @Transactional public ServiceResult<Void> markTermsAndConditionsIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId) { return getPartnerProgress(projectOrganisationCompositeId) .andOnSuccessReturnVoid(PendingPartnerProgress::markTermsAndConditionsIncomplete); } @Override ServiceResult<PendingPartnerProgressResource> getPendingPartnerProgress(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourOrganisationComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourFundingComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markTermsAndConditionsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourOrganisationIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourFundingIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markTermsAndConditionsIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> completePartnerSetup(ProjectOrganisationCompositeId projectOrganisationCompositeId); }
@Test public void markTermsAndConditionsIncomplete() { PendingPartnerProgress pendingPartnerProgress = new PendingPartnerProgress(null); when(pendingPartnerProgressRepository.findByOrganisationIdAndProjectId(PROJECT_ID, ORGANISATION_ID)).thenReturn(Optional.of(pendingPartnerProgress)); ServiceResult<Void> result = service.markTermsAndConditionsIncomplete(id(PROJECT_ID, ORGANISATION_ID)); assertTrue(result.isSuccess()); assertFalse(pendingPartnerProgress.isTermsAndConditionsComplete()); }
PendingPartnerProgressServiceImpl extends RootTransactionalService implements PendingPartnerProgressService { @Override @Transactional public ServiceResult<Void> completePartnerSetup(ProjectOrganisationCompositeId projectOrganisationCompositeId) { return getPartnerProgress(projectOrganisationCompositeId) .andOnSuccess(this::canJoinProject) .andOnSuccess(this::sendNotification) .andOnSuccessReturnVoid(PendingPartnerProgress::complete); } @Override ServiceResult<PendingPartnerProgressResource> getPendingPartnerProgress(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourOrganisationComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourFundingComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markTermsAndConditionsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourOrganisationIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markYourFundingIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markTermsAndConditionsIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> completePartnerSetup(ProjectOrganisationCompositeId projectOrganisationCompositeId); }
@Test public void completePartnerSetup_failure_sections_not_complete() { PendingPartnerProgress pendingPartnerProgress = populatedWith(BUSINESS, false); when(pendingPartnerProgressRepository.findByOrganisationIdAndProjectId(PROJECT_ID, ORGANISATION_ID)).thenReturn(Optional.of(pendingPartnerProgress)); ServiceResult<Void> result = service.completePartnerSetup(id(PROJECT_ID, ORGANISATION_ID)); assertFalse(result.isSuccess()); assertEquals(result.getFailure().getErrors().get(0).getErrorKey(), PARTNER_NOT_READY_TO_JOIN_PROJECT.name()); }
MonitoringOfficerPermissionRules extends BasePermissionRules { @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Monitoring officers can get their own projects." ) public boolean monitoringOfficerCanSeeTheirOwnProjects(UserResource monitoringOfficerUser, UserResource user) { return user.getId().equals(monitoringOfficerUser.getId()) && user.hasRole(MONITORING_OFFICER); } @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Monitoring officers can get their own projects." ) boolean monitoringOfficerCanSeeTheirOwnProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Internal users can view monitoring officer projects." ) boolean internalUsersCanSeeMonitoringOfficerProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "IS_MONITORING_OFFICER", description = "Users can see if they are moitoring offices on any projects" ) boolean usersCanSeeIfTheyAreMonitoringOfficerOnProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Internal users can view Monitoring Officers on any Project") boolean internalUsersCanViewMonitoringOfficersForAnyProject(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Stakeholders can view Monitoring Officers on any Project in their competitions") boolean stakeholdersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Competition finance user can view Monitoring Officers on any Project in their competitions") boolean competitionFinanceUsersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Monitoring Officers can view themselves on any Project") boolean monitoringOfficersCanViewThemselves(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Partners can view Monitoring Officers on Projects that they are partners on") boolean partnersCanViewMonitoringOfficersOnTheirProjects(ProjectResource project, UserResource user); }
@Test public void monitoringOfficerCanSeeTheirOwnProjects() { UserResource monitoringOfficer = newUserResource().withRoleGlobal(MONITORING_OFFICER).build(); UserResource otherMonitoringOfficer = newUserResource().withRoleGlobal(APPLICANT).build(); UserResource nonMonitoringOfficer = newUserResource().withRoleGlobal(APPLICANT).build(); assertTrue(rules.monitoringOfficerCanSeeTheirOwnProjects(monitoringOfficer, monitoringOfficer)); assertFalse(rules.monitoringOfficerCanSeeTheirOwnProjects(monitoringOfficer, otherMonitoringOfficer)); assertFalse(rules.monitoringOfficerCanSeeTheirOwnProjects(monitoringOfficer, nonMonitoringOfficer)); }
MonitoringOfficerPermissionRules extends BasePermissionRules { @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Internal users can view monitoring officer projects." ) public boolean internalUsersCanSeeMonitoringOfficerProjects(UserResource monitoringOfficerUser, UserResource user) { return isInternal(user); } @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Monitoring officers can get their own projects." ) boolean monitoringOfficerCanSeeTheirOwnProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Internal users can view monitoring officer projects." ) boolean internalUsersCanSeeMonitoringOfficerProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "IS_MONITORING_OFFICER", description = "Users can see if they are moitoring offices on any projects" ) boolean usersCanSeeIfTheyAreMonitoringOfficerOnProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Internal users can view Monitoring Officers on any Project") boolean internalUsersCanViewMonitoringOfficersForAnyProject(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Stakeholders can view Monitoring Officers on any Project in their competitions") boolean stakeholdersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Competition finance user can view Monitoring Officers on any Project in their competitions") boolean competitionFinanceUsersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Monitoring Officers can view themselves on any Project") boolean monitoringOfficersCanViewThemselves(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Partners can view Monitoring Officers on Projects that they are partners on") boolean partnersCanViewMonitoringOfficersOnTheirProjects(ProjectResource project, UserResource user); }
@Test public void internalUsersCanSeeMonitoringOfficerProjects() { UserResource monitoringOfficer = newUserResource().withRoleGlobal(APPLICANT).build(); UserResource internal = newUserResource().withRoleGlobal(COMP_ADMIN).build(); UserResource nonInternal = newUserResource().withRoleGlobal(APPLICANT).build(); assertTrue(rules.internalUsersCanSeeMonitoringOfficerProjects(monitoringOfficer, internal)); assertFalse(rules.internalUsersCanSeeMonitoringOfficerProjects(monitoringOfficer, nonInternal)); }
MonitoringOfficerPermissionRules extends BasePermissionRules { @PermissionRule( value = "IS_MONITORING_OFFICER", description = "Users can see if they are moitoring offices on any projects" ) public boolean usersCanSeeIfTheyAreMonitoringOfficerOnProjects(UserResource monitoringOfficerUser, UserResource user) { return monitoringOfficerUser.getId().equals(user.getId()); } @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Monitoring officers can get their own projects." ) boolean monitoringOfficerCanSeeTheirOwnProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Internal users can view monitoring officer projects." ) boolean internalUsersCanSeeMonitoringOfficerProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "IS_MONITORING_OFFICER", description = "Users can see if they are moitoring offices on any projects" ) boolean usersCanSeeIfTheyAreMonitoringOfficerOnProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Internal users can view Monitoring Officers on any Project") boolean internalUsersCanViewMonitoringOfficersForAnyProject(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Stakeholders can view Monitoring Officers on any Project in their competitions") boolean stakeholdersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Competition finance user can view Monitoring Officers on any Project in their competitions") boolean competitionFinanceUsersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Monitoring Officers can view themselves on any Project") boolean monitoringOfficersCanViewThemselves(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Partners can view Monitoring Officers on Projects that they are partners on") boolean partnersCanViewMonitoringOfficersOnTheirProjects(ProjectResource project, UserResource user); }
@Test public void usersCanSeeIfTheyAreMonitoringOfficerOnProjects() { long id = 1l; UserResource monitoringOfficer = newUserResource() .withId(id) .withRoleGlobal(KNOWLEDGE_TRANSFER_ADVISER).build(); UserResource userToView = newUserResource() .withId(id) .withRoleGlobal(KNOWLEDGE_TRANSFER_ADVISER).build(); assertTrue(rules.usersCanSeeIfTheyAreMonitoringOfficerOnProjects(monitoringOfficer, userToView)); }
MonitoringOfficerPermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Internal users can view Monitoring Officers on any Project") public boolean internalUsersCanViewMonitoringOfficersForAnyProject(ProjectResource project, UserResource user) { return isInternal(user); } @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Monitoring officers can get their own projects." ) boolean monitoringOfficerCanSeeTheirOwnProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Internal users can view monitoring officer projects." ) boolean internalUsersCanSeeMonitoringOfficerProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "IS_MONITORING_OFFICER", description = "Users can see if they are moitoring offices on any projects" ) boolean usersCanSeeIfTheyAreMonitoringOfficerOnProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Internal users can view Monitoring Officers on any Project") boolean internalUsersCanViewMonitoringOfficersForAnyProject(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Stakeholders can view Monitoring Officers on any Project in their competitions") boolean stakeholdersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Competition finance user can view Monitoring Officers on any Project in their competitions") boolean competitionFinanceUsersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Monitoring Officers can view themselves on any Project") boolean monitoringOfficersCanViewThemselves(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Partners can view Monitoring Officers on Projects that they are partners on") boolean partnersCanViewMonitoringOfficersOnTheirProjects(ProjectResource project, UserResource user); }
@Test public void internalUsersCanViewMonitoringOfficersOnProjects() { ProjectResource project = newProjectResource().build(); allGlobalRoleUsers.forEach(user -> { if (allInternalUsers.contains(user)) { assertTrue(rules.internalUsersCanViewMonitoringOfficersForAnyProject(project, user)); } else { assertFalse(rules.internalUsersCanViewMonitoringOfficersForAnyProject(project, user)); } }); }
MonitoringOfficerPermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Stakeholders can view Monitoring Officers on any Project in their competitions") public boolean stakeholdersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user) { return userIsStakeholderInCompetition(project.getCompetition(), user.getId()); } @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Monitoring officers can get their own projects." ) boolean monitoringOfficerCanSeeTheirOwnProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Internal users can view monitoring officer projects." ) boolean internalUsersCanSeeMonitoringOfficerProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "IS_MONITORING_OFFICER", description = "Users can see if they are moitoring offices on any projects" ) boolean usersCanSeeIfTheyAreMonitoringOfficerOnProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Internal users can view Monitoring Officers on any Project") boolean internalUsersCanViewMonitoringOfficersForAnyProject(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Stakeholders can view Monitoring Officers on any Project in their competitions") boolean stakeholdersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Competition finance user can view Monitoring Officers on any Project in their competitions") boolean competitionFinanceUsersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Monitoring Officers can view themselves on any Project") boolean monitoringOfficersCanViewThemselves(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Partners can view Monitoring Officers on Projects that they are partners on") boolean partnersCanViewMonitoringOfficersOnTheirProjects(ProjectResource project, UserResource user); }
@Test public void stakeholdersCanViewMonitoringOfficersForAProjectOnTheirCompetitions() { User stakeholderUserOnCompetition = newUser().withRoles(singleton(STAKEHOLDER)).build(); UserResource stakeholderUserResourceOnCompetition = newUserResource().withId(stakeholderUserOnCompetition.getId()).withRolesGlobal(singletonList(STAKEHOLDER)).build(); Competition competition = newCompetition().build(); ProjectResource project = newProjectResource() .withCompetition(competition.getId()) .build(); when(stakeholderRepository.existsByCompetitionIdAndUserId(competition.getId(), stakeholderUserResourceOnCompetition.getId())).thenReturn(true); assertTrue(rules.stakeholdersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(project, stakeholderUserResourceOnCompetition)); allInternalUsers.forEach(user -> assertFalse(rules.stakeholdersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(newProjectResource().build(), user))); }
MonitoringOfficerPermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Competition finance user can view Monitoring Officers on any Project in their competitions") public boolean competitionFinanceUsersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user) { return userIsExternalFinanceInCompetition(project.getCompetition(), user.getId()); } @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Monitoring officers can get their own projects." ) boolean monitoringOfficerCanSeeTheirOwnProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Internal users can view monitoring officer projects." ) boolean internalUsersCanSeeMonitoringOfficerProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "IS_MONITORING_OFFICER", description = "Users can see if they are moitoring offices on any projects" ) boolean usersCanSeeIfTheyAreMonitoringOfficerOnProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Internal users can view Monitoring Officers on any Project") boolean internalUsersCanViewMonitoringOfficersForAnyProject(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Stakeholders can view Monitoring Officers on any Project in their competitions") boolean stakeholdersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Competition finance user can view Monitoring Officers on any Project in their competitions") boolean competitionFinanceUsersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Monitoring Officers can view themselves on any Project") boolean monitoringOfficersCanViewThemselves(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Partners can view Monitoring Officers on Projects that they are partners on") boolean partnersCanViewMonitoringOfficersOnTheirProjects(ProjectResource project, UserResource user); }
@Test public void competitionFinanceUsersCanViewMonitoringOfficersForAProjectOnTheirCompetitions() { User competitionFinanceUserOnCompetition = newUser().withRoles(singleton(EXTERNAL_FINANCE)).build(); UserResource competitionFinanceUserResourceOnCompetition = newUserResource().withId(competitionFinanceUserOnCompetition.getId()).withRolesGlobal(singletonList(EXTERNAL_FINANCE)).build(); Competition competition = newCompetition().build(); ProjectResource project = newProjectResource() .withCompetition(competition.getId()) .build(); when(externalFinanceRepository.existsByCompetitionIdAndUserId(competition.getId(), competitionFinanceUserResourceOnCompetition.getId())).thenReturn(true); assertTrue(rules.competitionFinanceUsersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(project, competitionFinanceUserResourceOnCompetition)); allInternalUsers.forEach(user -> assertFalse(rules.competitionFinanceUsersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(newProjectResource().build(), user))); }
UserPermissionRules { @PermissionRule(value = "READ", description = "Project managers and partners can view the process role for the same organisation") public boolean projectPartnersCanViewTheProcessRolesWithinSameApplication(ProcessRoleResource processRole, UserResource user) { return getFilteredProjectUsers(user, projectUserFilter).stream().anyMatch(projectUser -> projectUser.getProject().getApplication().getId().equals(processRole.getApplicationId())); } @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 allUsersWithProjectUserRolesCanAccessProcessRolesWithinConsortium() { final long userId = 11L; final long applicationId = 1L; ProjectParticipantRole.DISPLAY_PROJECT_TEAM_ROLES .forEach(roleType -> { UserResource userResource = newUserResource().withId(userId).build(); ProjectUser projectUser = newProjectUser().withUser(newUser().withId(userId).build()).withRole(roleType).withProject(newProject().withApplication(newApplication().withId(applicationId).build()).build()).build(); when(projectUserRepository.findByUserId(userId)).thenReturn(singletonList(projectUser)); ProcessRoleResource processRoleResource = newProcessRoleResource().withUser(userResource).withApplication(applicationId).build(); assertTrue(rules.projectPartnersCanViewTheProcessRolesWithinSameApplication(processRoleResource, userResource)); }); } @Test public void allUsersWithMonitoringOfficersCannotAccessProcessRolesWithinConsortium() { final long userId = 11L; final long applicationId = 1L; UserResource userResource = newUserResource().withId(userId).build(); List<MonitoringOfficer> projectMonitoringOfficers = newMonitoringOfficer().withUser(newUser().withId(userId).build()).withProject(newProject().withApplication(newApplication().withId(applicationId).build()).build()).build(1); when(projectMonitoringOfficerRepository.findByUserId(userId)).thenReturn(projectMonitoringOfficers); ProcessRoleResource processRoleResource = newProcessRoleResource().withUser(userResource).withApplication(applicationId).build(); assertFalse(rules.projectPartnersCanViewTheProcessRolesWithinSameApplication(processRoleResource, userResource)); } @Test public void allUsersWithProjectRolesCanNotAccessProcessRolesWhenNotInConsortium() { final long userId = 11L; final long applicationId = 1L; ProjectParticipantRole.PROJECT_USER_ROLES .forEach(roleType -> { UserResource userResource = newUserResource().withId(userId).build(); ProjectUser projectUser = newProjectUser().withUser(newUser().withId(userId).build()).withRole(roleType).withProject(newProject().withApplication(newApplication().withId(applicationId).build()).build()).build(); when(projectUserRepository.findByUserId(userId)).thenReturn(singletonList(projectUser)); ProcessRoleResource processRoleResource = newProcessRoleResource().withUser(userResource).withApplication(123L).build(); assertFalse(rules.projectPartnersCanViewTheProcessRolesWithinSameApplication(processRoleResource, userResource)); }); }
MonitoringOfficerPermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Partners can view Monitoring Officers on Projects that they are partners on") public boolean partnersCanViewMonitoringOfficersOnTheirProjects(ProjectResource project, UserResource user) { return isPartner(project.getId(), user.getId()); } @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Monitoring officers can get their own projects." ) boolean monitoringOfficerCanSeeTheirOwnProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Internal users can view monitoring officer projects." ) boolean internalUsersCanSeeMonitoringOfficerProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "IS_MONITORING_OFFICER", description = "Users can see if they are moitoring offices on any projects" ) boolean usersCanSeeIfTheyAreMonitoringOfficerOnProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Internal users can view Monitoring Officers on any Project") boolean internalUsersCanViewMonitoringOfficersForAnyProject(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Stakeholders can view Monitoring Officers on any Project in their competitions") boolean stakeholdersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Competition finance user can view Monitoring Officers on any Project in their competitions") boolean competitionFinanceUsersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Monitoring Officers can view themselves on any Project") boolean monitoringOfficersCanViewThemselves(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Partners can view Monitoring Officers on Projects that they are partners on") boolean partnersCanViewMonitoringOfficersOnTheirProjects(ProjectResource project, UserResource user); }
@Test public void partnersCanViewMonitoringOfficersOnTheirOwnProjects() { UserResource user = newUserResource().build(); ProjectResource project = newProjectResource().build(); setupUserAsPartner(project, user); assertTrue(rules.partnersCanViewMonitoringOfficersOnTheirProjects(project, user)); } @Test public void partnersCanViewMonitoringOfficersOnTheirOwnProjectsButUserNotPartner() { UserResource user = newUserResource().build(); ProjectResource project = newProjectResource().build(); when(projectUserRepository.findByProjectIdAndUserIdAndRole(project.getId(), user.getId(), PROJECT_PARTNER)).thenReturn(emptyList()); assertFalse(rules.partnersCanViewMonitoringOfficersOnTheirProjects(project, user)); }
MonitoringOfficerPermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Monitoring Officers can view themselves on any Project") public boolean monitoringOfficersCanViewThemselves(ProjectResource project, UserResource user) { return isMonitoringOfficer(project.getId(), user.getId()); } @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Monitoring officers can get their own projects." ) boolean monitoringOfficerCanSeeTheirOwnProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "GET_MONITORING_OFFICER_PROJECTS", description = "Internal users can view monitoring officer projects." ) boolean internalUsersCanSeeMonitoringOfficerProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "IS_MONITORING_OFFICER", description = "Users can see if they are moitoring offices on any projects" ) boolean usersCanSeeIfTheyAreMonitoringOfficerOnProjects(UserResource monitoringOfficerUser, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Internal users can view Monitoring Officers on any Project") boolean internalUsersCanViewMonitoringOfficersForAnyProject(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Stakeholders can view Monitoring Officers on any Project in their competitions") boolean stakeholdersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Competition finance user can view Monitoring Officers on any Project in their competitions") boolean competitionFinanceUsersCanViewMonitoringOfficersForAProjectOnTheirCompetitions(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Monitoring Officers can view themselves on any Project") boolean monitoringOfficersCanViewThemselves(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_MONITORING_OFFICER", description = "Partners can view Monitoring Officers on Projects that they are partners on") boolean partnersCanViewMonitoringOfficersOnTheirProjects(ProjectResource project, UserResource user); }
@Test public void monitoringOfficersCanViewThemselves() { UserResource user = newUserResource().build(); ProjectResource project = newProjectResource().build(); setupUserAsMonitoringOfficer(project, user); when(projectMonitoringOfficerRepository.existsByProjectIdAndUserId(project.getId(), user.getId())).thenReturn(true); assertTrue(rules.monitoringOfficersCanViewThemselves(project, user)); }
MonitoringOfficerInviteController { @GetMapping("/open-monitoring-officer-invite/{inviteHash}") public RestResult<MonitoringOfficerInviteResource> openInvite(@PathVariable("inviteHash") String inviteHash) { return monitoringOfficerInviteService.openInvite(inviteHash).toGetResponse(); } MonitoringOfficerInviteController(MonitoringOfficerInviteService monitoringOfficerInviteService, RegistrationService registrationService, CrmService crmService, UserService userService); @GetMapping("/get-monitoring-officer-invite/{inviteHash}") RestResult<MonitoringOfficerInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @GetMapping("/open-monitoring-officer-invite/{inviteHash}") RestResult<MonitoringOfficerInviteResource> openInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/create-pending-monitoring-officer") RestResult<Void> createPendingMonitoringOfficer(@RequestBody MonitoringOfficerCreateResource resource); @PostMapping("/monitoring-officer/create/{inviteHash}") RestResult<Void> createMonitoringOfficer(@PathVariable("inviteHash") String inviteHash, @RequestBody MonitoringOfficerRegistrationResource monitoringOfficerRegistrationResource); @GetMapping("/monitoring-officer/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable("inviteHash") String hash); @PostMapping("/monitoring-officer/add-monitoring-officer-role/{inviteHash}") RestResult<Void> addMonitoringOfficerRole(@PathVariable("inviteHash") String hash); }
@Test public void openInvite() throws Exception { String hash = "hash"; MonitoringOfficerInviteResource invite = newMonitoringOfficerInviteResource() .withHash(hash) .build(); when(monitoringOfficerInviteServiceMock.openInvite(hash)).thenReturn(serviceSuccess(invite)); mockMvc.perform(get("/monitoring-officer-registration/open-monitoring-officer-invite/{hash}", hash)) .andExpect(status().isOk()); verify(monitoringOfficerInviteServiceMock, only()).openInvite(hash); }
MonitoringOfficerInviteController { @GetMapping("/get-monitoring-officer-invite/{inviteHash}") public RestResult<MonitoringOfficerInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash) { return monitoringOfficerInviteService.getInviteByHash(inviteHash).toGetResponse(); } MonitoringOfficerInviteController(MonitoringOfficerInviteService monitoringOfficerInviteService, RegistrationService registrationService, CrmService crmService, UserService userService); @GetMapping("/get-monitoring-officer-invite/{inviteHash}") RestResult<MonitoringOfficerInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @GetMapping("/open-monitoring-officer-invite/{inviteHash}") RestResult<MonitoringOfficerInviteResource> openInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/create-pending-monitoring-officer") RestResult<Void> createPendingMonitoringOfficer(@RequestBody MonitoringOfficerCreateResource resource); @PostMapping("/monitoring-officer/create/{inviteHash}") RestResult<Void> createMonitoringOfficer(@PathVariable("inviteHash") String inviteHash, @RequestBody MonitoringOfficerRegistrationResource monitoringOfficerRegistrationResource); @GetMapping("/monitoring-officer/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable("inviteHash") String hash); @PostMapping("/monitoring-officer/add-monitoring-officer-role/{inviteHash}") RestResult<Void> addMonitoringOfficerRole(@PathVariable("inviteHash") String hash); }
@Test public void getInvite() throws Exception { String hash = "hash"; MonitoringOfficerInviteResource invite = newMonitoringOfficerInviteResource() .withHash(hash) .build(); when(monitoringOfficerInviteServiceMock.getInviteByHash(hash)).thenReturn(serviceSuccess(invite)); mockMvc.perform(get("/monitoring-officer-registration/get-monitoring-officer-invite/{hash}", hash)) .andExpect(status().isOk()); verify(monitoringOfficerInviteServiceMock, only()).getInviteByHash(hash); }
MonitoringOfficerInviteController { @PostMapping("/monitoring-officer/create/{inviteHash}") public RestResult<Void> createMonitoringOfficer(@PathVariable("inviteHash") String inviteHash, @RequestBody MonitoringOfficerRegistrationResource monitoringOfficerRegistrationResource) { return monitoringOfficerInviteService .activateUserByHash(inviteHash, monitoringOfficerRegistrationResource) .andOnSuccess(user -> crmService.syncCrmContact(user.getId())) .toPostResponse(); } MonitoringOfficerInviteController(MonitoringOfficerInviteService monitoringOfficerInviteService, RegistrationService registrationService, CrmService crmService, UserService userService); @GetMapping("/get-monitoring-officer-invite/{inviteHash}") RestResult<MonitoringOfficerInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @GetMapping("/open-monitoring-officer-invite/{inviteHash}") RestResult<MonitoringOfficerInviteResource> openInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/create-pending-monitoring-officer") RestResult<Void> createPendingMonitoringOfficer(@RequestBody MonitoringOfficerCreateResource resource); @PostMapping("/monitoring-officer/create/{inviteHash}") RestResult<Void> createMonitoringOfficer(@PathVariable("inviteHash") String inviteHash, @RequestBody MonitoringOfficerRegistrationResource monitoringOfficerRegistrationResource); @GetMapping("/monitoring-officer/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable("inviteHash") String hash); @PostMapping("/monitoring-officer/add-monitoring-officer-role/{inviteHash}") RestResult<Void> addMonitoringOfficerRole(@PathVariable("inviteHash") String hash); }
@Test public void createMonitoringOfficer() throws Exception { String hash = "hash"; MonitoringOfficerRegistrationResource registrationResource = new MonitoringOfficerRegistrationResource( "tom", "baldwin", "0114 286 6356", "password" ); User user = newUser().build(); when(monitoringOfficerInviteServiceMock.activateUserByHash(anyString(), any())).thenReturn(serviceSuccess(user)); when(crmServiceMock.syncCrmContact(user.getId())).thenReturn(serviceSuccess()); mockMvc.perform(post("/monitoring-officer-registration/monitoring-officer/create/{hash}", hash) .contentType(APPLICATION_JSON) .content(toJson(registrationResource))) .andExpect(status().is2xxSuccessful()); InOrder inOrder = inOrder(monitoringOfficerInviteServiceMock, crmServiceMock); inOrder.verify(monitoringOfficerInviteServiceMock).activateUserByHash(hash, registrationResource); inOrder.verify(crmServiceMock).syncCrmContact(user.getId()); inOrder.verifyNoMoreInteractions(); }
MonitoringOfficerInviteController { @GetMapping("/monitoring-officer/check-existing-user/{inviteHash}") public RestResult<Boolean> checkExistingUser(@PathVariable("inviteHash") String hash) { return monitoringOfficerInviteService.checkUserExistsForInvite(hash).toGetResponse(); } MonitoringOfficerInviteController(MonitoringOfficerInviteService monitoringOfficerInviteService, RegistrationService registrationService, CrmService crmService, UserService userService); @GetMapping("/get-monitoring-officer-invite/{inviteHash}") RestResult<MonitoringOfficerInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @GetMapping("/open-monitoring-officer-invite/{inviteHash}") RestResult<MonitoringOfficerInviteResource> openInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/create-pending-monitoring-officer") RestResult<Void> createPendingMonitoringOfficer(@RequestBody MonitoringOfficerCreateResource resource); @PostMapping("/monitoring-officer/create/{inviteHash}") RestResult<Void> createMonitoringOfficer(@PathVariable("inviteHash") String inviteHash, @RequestBody MonitoringOfficerRegistrationResource monitoringOfficerRegistrationResource); @GetMapping("/monitoring-officer/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable("inviteHash") String hash); @PostMapping("/monitoring-officer/add-monitoring-officer-role/{inviteHash}") RestResult<Void> addMonitoringOfficerRole(@PathVariable("inviteHash") String hash); }
@Test public void checkExistingUser() throws Exception { String hash = "hash"; when(monitoringOfficerInviteServiceMock.checkUserExistsForInvite(hash)).thenReturn(serviceSuccess(true)); mockMvc.perform(get("/monitoring-officer-registration/monitoring-officer/check-existing-user/{hash}", hash)) .andExpect(status().isOk()); verify(monitoringOfficerInviteServiceMock, only()).checkUserExistsForInvite(hash); }
MonitoringOfficerInviteController { @PostMapping("/monitoring-officer/add-monitoring-officer-role/{inviteHash}") public RestResult<Void> addMonitoringOfficerRole(@PathVariable("inviteHash") String hash) { return monitoringOfficerInviteService.addMonitoringOfficerRole(hash) .andOnSuccess(user -> crmService.syncCrmContact(user.getId())) .toPostResponse(); } MonitoringOfficerInviteController(MonitoringOfficerInviteService monitoringOfficerInviteService, RegistrationService registrationService, CrmService crmService, UserService userService); @GetMapping("/get-monitoring-officer-invite/{inviteHash}") RestResult<MonitoringOfficerInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @GetMapping("/open-monitoring-officer-invite/{inviteHash}") RestResult<MonitoringOfficerInviteResource> openInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/create-pending-monitoring-officer") RestResult<Void> createPendingMonitoringOfficer(@RequestBody MonitoringOfficerCreateResource resource); @PostMapping("/monitoring-officer/create/{inviteHash}") RestResult<Void> createMonitoringOfficer(@PathVariable("inviteHash") String inviteHash, @RequestBody MonitoringOfficerRegistrationResource monitoringOfficerRegistrationResource); @GetMapping("/monitoring-officer/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable("inviteHash") String hash); @PostMapping("/monitoring-officer/add-monitoring-officer-role/{inviteHash}") RestResult<Void> addMonitoringOfficerRole(@PathVariable("inviteHash") String hash); }
@Test public void addMonitoringOfficerRole() throws Exception { String hash = "hash"; User user = newUser().build(); when(monitoringOfficerInviteServiceMock.addMonitoringOfficerRole(hash)).thenReturn(serviceSuccess(user)); when(crmServiceMock.syncCrmContact(user.getId())).thenReturn(serviceSuccess()); mockMvc.perform(post("/monitoring-officer-registration/monitoring-officer/add-monitoring-officer-role/{hash}", hash)) .andExpect(status().is2xxSuccessful()); InOrder inOrder = inOrder(monitoringOfficerInviteServiceMock, crmServiceMock); inOrder.verify(monitoringOfficerInviteServiceMock).addMonitoringOfficerRole(hash); inOrder.verify(crmServiceMock).syncCrmContact(user.getId()); inOrder.verifyNoMoreInteractions(); }
MonitoringOfficerInviteController { @PostMapping("/create-pending-monitoring-officer") public RestResult<Void> createPendingMonitoringOfficer(@RequestBody MonitoringOfficerCreateResource resource) { boolean userAlreadyExists = userService.findByEmail(resource.getEmailAddress()).isSuccess(); if (userAlreadyExists) { return restSuccess(); } return registrationService.createUser(anUserCreationResource() .withFirstName(resource.getFirstName()) .withLastName(resource.getLastName()) .withEmail(resource.getEmailAddress()) .withRole(Role.MONITORING_OFFICER) .build()) .andOnSuccessReturnVoid() .toPostCreateResponse(); } MonitoringOfficerInviteController(MonitoringOfficerInviteService monitoringOfficerInviteService, RegistrationService registrationService, CrmService crmService, UserService userService); @GetMapping("/get-monitoring-officer-invite/{inviteHash}") RestResult<MonitoringOfficerInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @GetMapping("/open-monitoring-officer-invite/{inviteHash}") RestResult<MonitoringOfficerInviteResource> openInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/create-pending-monitoring-officer") RestResult<Void> createPendingMonitoringOfficer(@RequestBody MonitoringOfficerCreateResource resource); @PostMapping("/monitoring-officer/create/{inviteHash}") RestResult<Void> createMonitoringOfficer(@PathVariable("inviteHash") String inviteHash, @RequestBody MonitoringOfficerRegistrationResource monitoringOfficerRegistrationResource); @GetMapping("/monitoring-officer/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable("inviteHash") String hash); @PostMapping("/monitoring-officer/add-monitoring-officer-role/{inviteHash}") RestResult<Void> addMonitoringOfficerRole(@PathVariable("inviteHash") String hash); }
@Test public void createPendingMonitoringOfficer() throws Exception { UserResource user = newUserResource() .withFirstName("Steve") .withLastName("Smith") .withEmail("[email protected]") .withPhoneNumber("01142356565") .build(); MonitoringOfficerCreateResource resource = new MonitoringOfficerCreateResource( user.getFirstName(), user.getLastName(), user.getPhoneNumber(), user.getEmail()); when(userServiceMock.findByEmail(user.getEmail())) .thenReturn(serviceFailure(notFoundError(User.class, user.getEmail()))); when(registrationServiceMock.createUser(any())) .thenReturn(serviceSuccess(user)); mockMvc.perform(post("/monitoring-officer-registration/create-pending-monitoring-officer") .content(toJson(resource)) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isCreated()); verify(userServiceMock).findByEmail(user.getEmail()); verify(registrationServiceMock).createUser(any()); }
MonitoringOfficerController { @GetMapping("/find-all") public RestResult<List<SimpleUserResource>> findAll() { return monitoringOfficerService.findAll().toGetResponse(); } MonitoringOfficerController(MonitoringOfficerService monitoringOfficerService); @GetMapping("/find-all") RestResult<List<SimpleUserResource>> findAll(); @GetMapping("/{userId}") RestResult<MonitoringOfficerAssignmentResource> getProjectMonitoringOfficer(@PathVariable long userId); @PostMapping("/{userId}/assign/{projectId}") RestResult<Void> assignProjectToMonitoringOfficer(@PathVariable long userId, @PathVariable long projectId); @PostMapping("/{userId}/unassign/{projectId}") RestResult<Void> unassignProjectFromMonitoringOfficer(@PathVariable long userId, @PathVariable long projectId); @GetMapping("{userId}/projects") RestResult<List<ProjectResource>> getMonitoringOfficerProjects(@PathVariable final long userId); @GetMapping("/project/{projectId}") RestResult<MonitoringOfficerResource> findMonitoringOfficerForProject(@PathVariable final long projectId); @GetMapping("/project/{projectId}/is-monitoring-officer/{userId}") RestResult<Boolean> isMonitoringOfficerOnProject(@PathVariable final long projectId, @PathVariable final long userId); @GetMapping("/is-monitoring-officer/{userId}") RestResult<Boolean> isMonitoringOfficer(@PathVariable final long userId); }
@Test public void findAll() throws Exception { List<SimpleUserResource> expected = newSimpleUserResource().build(1); when(projectMonitoringOfficerServiceMock.findAll()).thenReturn(serviceSuccess(expected)); mockMvc.perform(get("/monitoring-officer/find-all")) .andExpect(status().isOk()) .andExpect(content().json(toJson(expected))); verify(projectMonitoringOfficerServiceMock).findAll(); }
MonitoringOfficerController { @GetMapping("/{userId}") public RestResult<MonitoringOfficerAssignmentResource> getProjectMonitoringOfficer(@PathVariable long userId) { return monitoringOfficerService.getProjectMonitoringOfficer(userId).toGetResponse(); } MonitoringOfficerController(MonitoringOfficerService monitoringOfficerService); @GetMapping("/find-all") RestResult<List<SimpleUserResource>> findAll(); @GetMapping("/{userId}") RestResult<MonitoringOfficerAssignmentResource> getProjectMonitoringOfficer(@PathVariable long userId); @PostMapping("/{userId}/assign/{projectId}") RestResult<Void> assignProjectToMonitoringOfficer(@PathVariable long userId, @PathVariable long projectId); @PostMapping("/{userId}/unassign/{projectId}") RestResult<Void> unassignProjectFromMonitoringOfficer(@PathVariable long userId, @PathVariable long projectId); @GetMapping("{userId}/projects") RestResult<List<ProjectResource>> getMonitoringOfficerProjects(@PathVariable final long userId); @GetMapping("/project/{projectId}") RestResult<MonitoringOfficerResource> findMonitoringOfficerForProject(@PathVariable final long projectId); @GetMapping("/project/{projectId}/is-monitoring-officer/{userId}") RestResult<Boolean> isMonitoringOfficerOnProject(@PathVariable final long projectId, @PathVariable final long userId); @GetMapping("/is-monitoring-officer/{userId}") RestResult<Boolean> isMonitoringOfficer(@PathVariable final long userId); }
@Test public void getProjectMonitoringOfficer() throws Exception { long userId = 7; MonitoringOfficerAssignmentResource expected = new MonitoringOfficerAssignmentResource(); when(projectMonitoringOfficerServiceMock.getProjectMonitoringOfficer(userId)).thenReturn(serviceSuccess(expected)); mockMvc.perform(get("/monitoring-officer/{userId}", userId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(expected))); verify(projectMonitoringOfficerServiceMock, only()).getProjectMonitoringOfficer(userId); }
MonitoringOfficerController { @PostMapping("/{userId}/assign/{projectId}") public RestResult<Void> assignProjectToMonitoringOfficer(@PathVariable long userId, @PathVariable long projectId) { return monitoringOfficerService.assignProjectToMonitoringOfficer(userId, projectId).toPostResponse(); } MonitoringOfficerController(MonitoringOfficerService monitoringOfficerService); @GetMapping("/find-all") RestResult<List<SimpleUserResource>> findAll(); @GetMapping("/{userId}") RestResult<MonitoringOfficerAssignmentResource> getProjectMonitoringOfficer(@PathVariable long userId); @PostMapping("/{userId}/assign/{projectId}") RestResult<Void> assignProjectToMonitoringOfficer(@PathVariable long userId, @PathVariable long projectId); @PostMapping("/{userId}/unassign/{projectId}") RestResult<Void> unassignProjectFromMonitoringOfficer(@PathVariable long userId, @PathVariable long projectId); @GetMapping("{userId}/projects") RestResult<List<ProjectResource>> getMonitoringOfficerProjects(@PathVariable final long userId); @GetMapping("/project/{projectId}") RestResult<MonitoringOfficerResource> findMonitoringOfficerForProject(@PathVariable final long projectId); @GetMapping("/project/{projectId}/is-monitoring-officer/{userId}") RestResult<Boolean> isMonitoringOfficerOnProject(@PathVariable final long projectId, @PathVariable final long userId); @GetMapping("/is-monitoring-officer/{userId}") RestResult<Boolean> isMonitoringOfficer(@PathVariable final long userId); }
@Test public void assignProjectToMonitoringOfficer() throws Exception { long userId = 11; long projectId = 13; when(projectMonitoringOfficerServiceMock.assignProjectToMonitoringOfficer(userId, projectId)).thenReturn(serviceSuccess()); mockMvc.perform(MockMvcRequestBuilders.post("/monitoring-officer/{userId}/assign/{projectId}", userId, projectId)) .andExpect(status().is2xxSuccessful()); verify(projectMonitoringOfficerServiceMock, only()).assignProjectToMonitoringOfficer(userId, projectId); }
MonitoringOfficerController { @PostMapping("/{userId}/unassign/{projectId}") public RestResult<Void> unassignProjectFromMonitoringOfficer(@PathVariable long userId, @PathVariable long projectId) { return monitoringOfficerService.unassignProjectFromMonitoringOfficer(userId, projectId).toPostResponse(); } MonitoringOfficerController(MonitoringOfficerService monitoringOfficerService); @GetMapping("/find-all") RestResult<List<SimpleUserResource>> findAll(); @GetMapping("/{userId}") RestResult<MonitoringOfficerAssignmentResource> getProjectMonitoringOfficer(@PathVariable long userId); @PostMapping("/{userId}/assign/{projectId}") RestResult<Void> assignProjectToMonitoringOfficer(@PathVariable long userId, @PathVariable long projectId); @PostMapping("/{userId}/unassign/{projectId}") RestResult<Void> unassignProjectFromMonitoringOfficer(@PathVariable long userId, @PathVariable long projectId); @GetMapping("{userId}/projects") RestResult<List<ProjectResource>> getMonitoringOfficerProjects(@PathVariable final long userId); @GetMapping("/project/{projectId}") RestResult<MonitoringOfficerResource> findMonitoringOfficerForProject(@PathVariable final long projectId); @GetMapping("/project/{projectId}/is-monitoring-officer/{userId}") RestResult<Boolean> isMonitoringOfficerOnProject(@PathVariable final long projectId, @PathVariable final long userId); @GetMapping("/is-monitoring-officer/{userId}") RestResult<Boolean> isMonitoringOfficer(@PathVariable final long userId); }
@Test public void unassignProjectFromMonitoringOfficer() throws Exception { long userId = 11; long projectId = 13; when(projectMonitoringOfficerServiceMock.unassignProjectFromMonitoringOfficer(userId, projectId)).thenReturn(serviceSuccess()); mockMvc.perform(MockMvcRequestBuilders.post("/monitoring-officer/{userId}/unassign/{projectId}", userId, projectId)) .andExpect(status().is2xxSuccessful()); verify(projectMonitoringOfficerServiceMock, only()).unassignProjectFromMonitoringOfficer(userId, projectId); }
MonitoringOfficerController { @GetMapping("{userId}/projects") public RestResult<List<ProjectResource>> getMonitoringOfficerProjects(@PathVariable final long userId) { return monitoringOfficerService.getMonitoringOfficerProjects(userId).toGetResponse(); } MonitoringOfficerController(MonitoringOfficerService monitoringOfficerService); @GetMapping("/find-all") RestResult<List<SimpleUserResource>> findAll(); @GetMapping("/{userId}") RestResult<MonitoringOfficerAssignmentResource> getProjectMonitoringOfficer(@PathVariable long userId); @PostMapping("/{userId}/assign/{projectId}") RestResult<Void> assignProjectToMonitoringOfficer(@PathVariable long userId, @PathVariable long projectId); @PostMapping("/{userId}/unassign/{projectId}") RestResult<Void> unassignProjectFromMonitoringOfficer(@PathVariable long userId, @PathVariable long projectId); @GetMapping("{userId}/projects") RestResult<List<ProjectResource>> getMonitoringOfficerProjects(@PathVariable final long userId); @GetMapping("/project/{projectId}") RestResult<MonitoringOfficerResource> findMonitoringOfficerForProject(@PathVariable final long projectId); @GetMapping("/project/{projectId}/is-monitoring-officer/{userId}") RestResult<Boolean> isMonitoringOfficerOnProject(@PathVariable final long projectId, @PathVariable final long userId); @GetMapping("/is-monitoring-officer/{userId}") RestResult<Boolean> isMonitoringOfficer(@PathVariable final long userId); }
@Test public void getMonitoringOfficerProjects() throws Exception { long userId = 11; when(projectMonitoringOfficerServiceMock.getMonitoringOfficerProjects(userId)).thenReturn(serviceSuccess(emptyList())); mockMvc.perform(get("/monitoring-officer/{userId}/projects", userId)) .andExpect(status().is2xxSuccessful()); verify(projectMonitoringOfficerServiceMock, only()).getMonitoringOfficerProjects(userId); }
MonitoringOfficerController { @GetMapping("/is-monitoring-officer/{userId}") public RestResult<Boolean> isMonitoringOfficer(@PathVariable final long userId) { return monitoringOfficerService.isMonitoringOfficer(userId).toGetResponse(); } MonitoringOfficerController(MonitoringOfficerService monitoringOfficerService); @GetMapping("/find-all") RestResult<List<SimpleUserResource>> findAll(); @GetMapping("/{userId}") RestResult<MonitoringOfficerAssignmentResource> getProjectMonitoringOfficer(@PathVariable long userId); @PostMapping("/{userId}/assign/{projectId}") RestResult<Void> assignProjectToMonitoringOfficer(@PathVariable long userId, @PathVariable long projectId); @PostMapping("/{userId}/unassign/{projectId}") RestResult<Void> unassignProjectFromMonitoringOfficer(@PathVariable long userId, @PathVariable long projectId); @GetMapping("{userId}/projects") RestResult<List<ProjectResource>> getMonitoringOfficerProjects(@PathVariable final long userId); @GetMapping("/project/{projectId}") RestResult<MonitoringOfficerResource> findMonitoringOfficerForProject(@PathVariable final long projectId); @GetMapping("/project/{projectId}/is-monitoring-officer/{userId}") RestResult<Boolean> isMonitoringOfficerOnProject(@PathVariable final long projectId, @PathVariable final long userId); @GetMapping("/is-monitoring-officer/{userId}") RestResult<Boolean> isMonitoringOfficer(@PathVariable final long userId); }
@Test public void isMonitoringOfficer() throws Exception { long userId = 11; when(projectMonitoringOfficerServiceMock.isMonitoringOfficer(userId)).thenReturn(serviceSuccess(true)); mockMvc.perform(get("/monitoring-officer/is-monitoring-officer/{userId}", userId)) .andExpect(status().is2xxSuccessful()); verify(projectMonitoringOfficerServiceMock, only()).isMonitoringOfficer(userId); }
MonitoringOfficerServiceImpl extends RootTransactionalService implements MonitoringOfficerService { @Override public ServiceResult<List<SimpleUserResource>> findAll() { return serviceSuccess(userRepository.findByRolesAndStatusIn(MONITORING_OFFICER, EnumSet.of(PENDING, ACTIVE)) .stream() .map(user -> new SimpleUserResource(user.getId(), user.getFirstName(), user.getLastName(), user.getEmail())) .collect(Collectors.toList())); } @Override ServiceResult<List<SimpleUserResource>> findAll(); @Override @Transactional ServiceResult<MonitoringOfficerAssignmentResource> getProjectMonitoringOfficer(long userId); @Override @Transactional ServiceResult<Void> assignProjectToMonitoringOfficer(long userId, long projectId); @Override @Transactional ServiceResult<Void> unassignProjectFromMonitoringOfficer(long userId, long projectId); @Override ServiceResult<List<ProjectResource>> getMonitoringOfficerProjects(long userId); @Override ServiceResult<MonitoringOfficerResource> findMonitoringOfficerForProject(long projectId); @Override ServiceResult<Boolean> isMonitoringOfficerOnProject(long projectId, long userId); @Override ServiceResult<Boolean> isMonitoringOfficer(long userId); }
@Test public void findAll() { User user = newUser().build(); when(userRepositoryMock.findByRolesAndStatusIn(Role.MONITORING_OFFICER, EnumSet.of(PENDING, ACTIVE))).thenReturn(singletonList(user)); List<SimpleUserResource> result = service.findAll().getSuccess(); assertEquals(result.size(), 1); assertEquals(result.get(0).getId(), (long) user.getId()); }
MonitoringOfficerServiceImpl extends RootTransactionalService implements MonitoringOfficerService { @Override @Transactional public ServiceResult<MonitoringOfficerAssignmentResource> getProjectMonitoringOfficer(long userId) { return getMonitoringOfficerUser(userId) .andOnSuccessReturn(this::mapToProjectMonitoringOfficerResource); } @Override ServiceResult<List<SimpleUserResource>> findAll(); @Override @Transactional ServiceResult<MonitoringOfficerAssignmentResource> getProjectMonitoringOfficer(long userId); @Override @Transactional ServiceResult<Void> assignProjectToMonitoringOfficer(long userId, long projectId); @Override @Transactional ServiceResult<Void> unassignProjectFromMonitoringOfficer(long userId, long projectId); @Override ServiceResult<List<ProjectResource>> getMonitoringOfficerProjects(long userId); @Override ServiceResult<MonitoringOfficerResource> findMonitoringOfficerForProject(long projectId); @Override ServiceResult<Boolean> isMonitoringOfficerOnProject(long projectId, long userId); @Override ServiceResult<Boolean> isMonitoringOfficer(long userId); }
@Test public void getProjectMonitoringOfficer() { User user = newUser().withFirstName("Tom").withLastName("Baldwin").build(); MonitoringOfficerAssignedProjectResource assigned = new MonitoringOfficerAssignedProjectResource(1L, 1L, 1L, "assigned", "LeadyMcLeadFace"); MonitoringOfficerUnassignedProjectResource unassigned = new MonitoringOfficerUnassignedProjectResource(2L, 2L, "unassigned"); when(userRepositoryMock.findByIdAndRoles(user.getId(), Role.MONITORING_OFFICER)).thenReturn(Optional.of(user)); when(projectMonitoringOfficerRepositoryMock.findAssignedProjects(user.getId())).thenReturn(singletonList(assigned)); when(projectMonitoringOfficerRepositoryMock.findUnassignedProject()).thenReturn(singletonList(unassigned)); MonitoringOfficerAssignmentResource projectMonitoringOfficer = service.getProjectMonitoringOfficer(user.getId()).getSuccess(); assertEquals((long) user.getId(), projectMonitoringOfficer.getUserId()); assertEquals(user.getFirstName(), projectMonitoringOfficer.getFirstName()); assertEquals(user.getLastName(), projectMonitoringOfficer.getLastName()); assertEquals(assigned, projectMonitoringOfficer.getAssignedProjects().get(0)); assertEquals(unassigned, projectMonitoringOfficer.getUnassignedProjects().get(0)); }
MonitoringOfficerServiceImpl extends RootTransactionalService implements MonitoringOfficerService { @Override @Transactional public ServiceResult<Void> assignProjectToMonitoringOfficer(long userId, long projectId) { return getMonitoringOfficerUser(userId) .andOnSuccess(user -> find(projectRepository.findById(projectId), notFoundError(Project.class)) .andOnSuccess(project -> (monitoringOfficerInviteService.inviteMonitoringOfficer(user, project)) .andOnSuccessReturnVoid(() -> monitoringOfficerRepository.save(new MonitoringOfficer(user, project))) ) ); } @Override ServiceResult<List<SimpleUserResource>> findAll(); @Override @Transactional ServiceResult<MonitoringOfficerAssignmentResource> getProjectMonitoringOfficer(long userId); @Override @Transactional ServiceResult<Void> assignProjectToMonitoringOfficer(long userId, long projectId); @Override @Transactional ServiceResult<Void> unassignProjectFromMonitoringOfficer(long userId, long projectId); @Override ServiceResult<List<ProjectResource>> getMonitoringOfficerProjects(long userId); @Override ServiceResult<MonitoringOfficerResource> findMonitoringOfficerForProject(long projectId); @Override ServiceResult<Boolean> isMonitoringOfficerOnProject(long projectId, long userId); @Override ServiceResult<Boolean> isMonitoringOfficer(long userId); }
@Test public void assignProjectToMonitoringOfficer() { User moUser = newUser().build(); Project project = newProject().build(); when(userRepositoryMock.findByIdAndRoles(moUser.getId(), Role.MONITORING_OFFICER)).thenReturn(Optional.of(moUser)); when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project)); when(monitoringOfficerInviteServiceMock.inviteMonitoringOfficer(moUser, project)).thenReturn(serviceSuccess()); service.assignProjectToMonitoringOfficer(moUser.getId(), project.getId()).getSuccess(); InOrder inOrder = inOrder(userRepositoryMock, projectRepositoryMock, monitoringOfficerInviteServiceMock, projectMonitoringOfficerRepositoryMock); inOrder.verify(userRepositoryMock).findByIdAndRoles(moUser.getId(), Role.MONITORING_OFFICER); inOrder.verify(projectRepositoryMock).findById(project.getId()); inOrder.verify(monitoringOfficerInviteServiceMock).inviteMonitoringOfficer(moUser, project); inOrder.verify(projectMonitoringOfficerRepositoryMock).save(new MonitoringOfficer(moUser, project)); inOrder.verifyNoMoreInteractions(); }
MonitoringOfficerServiceImpl extends RootTransactionalService implements MonitoringOfficerService { @Override @Transactional public ServiceResult<Void> unassignProjectFromMonitoringOfficer(long userId, long projectId) { monitoringOfficerRepository.deleteByUserIdAndProjectId(userId, projectId); return serviceSuccess(); } @Override ServiceResult<List<SimpleUserResource>> findAll(); @Override @Transactional ServiceResult<MonitoringOfficerAssignmentResource> getProjectMonitoringOfficer(long userId); @Override @Transactional ServiceResult<Void> assignProjectToMonitoringOfficer(long userId, long projectId); @Override @Transactional ServiceResult<Void> unassignProjectFromMonitoringOfficer(long userId, long projectId); @Override ServiceResult<List<ProjectResource>> getMonitoringOfficerProjects(long userId); @Override ServiceResult<MonitoringOfficerResource> findMonitoringOfficerForProject(long projectId); @Override ServiceResult<Boolean> isMonitoringOfficerOnProject(long projectId, long userId); @Override ServiceResult<Boolean> isMonitoringOfficer(long userId); }
@Test public void unassignProjectFromMonitoringOfficer() { User moUser = newUser().build(); Project project = newProject().build(); service.unassignProjectFromMonitoringOfficer(moUser.getId(), project.getId()); verify(projectMonitoringOfficerRepositoryMock, only()).deleteByUserIdAndProjectId(moUser.getId(), project.getId()); }
MonitoringOfficerServiceImpl extends RootTransactionalService implements MonitoringOfficerService { @Override public ServiceResult<List<ProjectResource>> getMonitoringOfficerProjects(long userId) { List<MonitoringOfficer> monitoringOfficers = monitoringOfficerRepository.findByUserId(userId); return serviceSuccess(monitoringOfficers.stream() .map(MonitoringOfficer::getProcess) .map(projectMapper::mapToResource) .collect(toList())); } @Override ServiceResult<List<SimpleUserResource>> findAll(); @Override @Transactional ServiceResult<MonitoringOfficerAssignmentResource> getProjectMonitoringOfficer(long userId); @Override @Transactional ServiceResult<Void> assignProjectToMonitoringOfficer(long userId, long projectId); @Override @Transactional ServiceResult<Void> unassignProjectFromMonitoringOfficer(long userId, long projectId); @Override ServiceResult<List<ProjectResource>> getMonitoringOfficerProjects(long userId); @Override ServiceResult<MonitoringOfficerResource> findMonitoringOfficerForProject(long projectId); @Override ServiceResult<Boolean> isMonitoringOfficerOnProject(long projectId, long userId); @Override ServiceResult<Boolean> isMonitoringOfficer(long userId); }
@Test public void getMonitoringOfficerProjects() { long userId = 1L; when(projectMonitoringOfficerRepositoryMock.findByUserId(userId)).thenReturn(newMonitoringOfficer() .withProject(newProject().build()) .build(1)); when(projectMapper.mapToResource(any(Project.class))).thenReturn(newProjectResource().build()); ServiceResult<List<ProjectResource>> result = service.getMonitoringOfficerProjects(userId); assertTrue(result.isSuccess()); assertEquals(result.getSuccess().size(), 1); }
MonitoringOfficerServiceImpl extends RootTransactionalService implements MonitoringOfficerService { @Override public ServiceResult<MonitoringOfficerResource> findMonitoringOfficerForProject(long projectId) { Optional<MonitoringOfficer> monitoringOfficer = monitoringOfficerRepository.findOneByProjectIdAndRole(projectId, ProjectParticipantRole.MONITORING_OFFICER); if (monitoringOfficer.isPresent()) { return toMonitoringOfficerResource(monitoringOfficer.get(), projectId); } else { return legacyMonitoringOfficer(projectId); } } @Override ServiceResult<List<SimpleUserResource>> findAll(); @Override @Transactional ServiceResult<MonitoringOfficerAssignmentResource> getProjectMonitoringOfficer(long userId); @Override @Transactional ServiceResult<Void> assignProjectToMonitoringOfficer(long userId, long projectId); @Override @Transactional ServiceResult<Void> unassignProjectFromMonitoringOfficer(long userId, long projectId); @Override ServiceResult<List<ProjectResource>> getMonitoringOfficerProjects(long userId); @Override ServiceResult<MonitoringOfficerResource> findMonitoringOfficerForProject(long projectId); @Override ServiceResult<Boolean> isMonitoringOfficerOnProject(long projectId, long userId); @Override ServiceResult<Boolean> isMonitoringOfficer(long userId); }
@Test public void findMonitoringOfficerForProject_monitoringOfficerFound() { long projectId = 1L; String firstName = "firstName"; String lastName = "lastName"; String email = "[email protected]"; String phoneNumber = "012345678"; MonitoringOfficer monitoringOfficer = newMonitoringOfficer() .withUser(newUser() .withFirstName(firstName) .withLastName(lastName) .withEmailAddress(email) .withPhoneNumber(phoneNumber) .build() ) .build(); when(projectMonitoringOfficerRepositoryMock.findOneByProjectIdAndRole(projectId, ProjectParticipantRole.MONITORING_OFFICER)).thenReturn(Optional.of(monitoringOfficer)); ServiceResult<MonitoringOfficerResource> result = service.findMonitoringOfficerForProject(projectId); MonitoringOfficerResource resource = result.getSuccess(); assertEquals(resource.getEmail(), email); assertEquals(resource.getFirstName(), firstName); assertEquals(resource.getLastName(), lastName); assertEquals(resource.getPhoneNumber(), phoneNumber); assertEquals(resource.getId(), monitoringOfficer.getId()); assertEquals(resource.getProject(), (Long) projectId); } @Test public void findMonitoringOfficerForProject_legacyOfficerFound() { long projectId = 1L; String firstName = "firstName"; String lastName = "lastName"; String email = "[email protected]"; String phoneNumber = "012345678"; MonitoringOfficer monitoringOfficer = newMonitoringOfficer().build(); when(legacyMonitoringOfficerService.getMonitoringOfficer(projectId)).thenReturn(serviceSuccess(newLegacyMonitoringOfficerResource() .withEmail(email) .withFirstName(firstName) .withLastName(lastName) .withPhoneNumber(phoneNumber) .withProject(projectId) .build())); ServiceResult<MonitoringOfficerResource> result = service.findMonitoringOfficerForProject(projectId); MonitoringOfficerResource resource = result.getSuccess(); assertEquals(resource.getEmail(), email); assertEquals(resource.getFirstName(), firstName); assertEquals(resource.getLastName(), lastName); assertEquals(resource.getPhoneNumber(), phoneNumber); assertEquals(resource.getProject(), (Long) projectId); } @Test public void findMonitoringOfficerForProject_notFound() { long projectId = 1L; when(legacyMonitoringOfficerService.getMonitoringOfficer(projectId)).thenReturn(serviceFailure(CommonErrors.notFoundError(LegacyMonitoringOfficer.class))); ServiceResult<MonitoringOfficerResource> result = service.findMonitoringOfficerForProject(projectId); assertTrue(result.isFailure()); }
MonitoringOfficerInviteServiceImpl extends InviteService<MonitoringOfficerInvite> implements MonitoringOfficerInviteService { @Override public ServiceResult<MonitoringOfficerInviteResource> getInviteByHash(String hash) { return getByHash(hash).andOnSuccessReturn(monitoringOfficerInviteMapper::mapToResource); } @Override @Transactional ServiceResult<Void> inviteMonitoringOfficer(User invitedUser, Project project); @Override ServiceResult<MonitoringOfficerInviteResource> getInviteByHash(String hash); @Override @Transactional ServiceResult<MonitoringOfficerInviteResource> openInvite(String hash); @Override @Transactional ServiceResult<User> activateUserByHash(String inviteHash, MonitoringOfficerRegistrationResource resource); @Override ServiceResult<Boolean> checkUserExistsForInvite(String hash); @Override @Transactional ServiceResult<User> addMonitoringOfficerRole(String hash); }
@Test public void getInviteByHash() { String hash = "hash"; MonitoringOfficerInvite invite = new MonitoringOfficerInvite("name", "email", hash, InviteStatus.SENT); MonitoringOfficerInviteResource inviteResource = newMonitoringOfficerInviteResource().build(); when(monitoringOfficerInviteRepositoryMock.getByHash(hash)).thenReturn(invite); when(monitoringOfficerInviteMapperMock.mapToResource(invite)).thenReturn(inviteResource); MonitoringOfficerInviteResource actualInviteResource = service.getInviteByHash(hash).getSuccess(); assertEquals(inviteResource, actualInviteResource); InOrder inOrder = inOrder(monitoringOfficerInviteRepositoryMock, monitoringOfficerInviteMapperMock); inOrder.verify(monitoringOfficerInviteRepositoryMock).getByHash(hash); inOrder.verify(monitoringOfficerInviteMapperMock).mapToResource(invite); inOrder.verifyNoMoreInteractions(); }
MonitoringOfficerInviteServiceImpl extends InviteService<MonitoringOfficerInvite> implements MonitoringOfficerInviteService { @Override @Transactional public ServiceResult<MonitoringOfficerInviteResource> openInvite(String hash) { return getByHash(hash) .andOnSuccessReturn(Invite::open) .andOnSuccessReturn(monitoringOfficerInviteMapper::mapToResource); } @Override @Transactional ServiceResult<Void> inviteMonitoringOfficer(User invitedUser, Project project); @Override ServiceResult<MonitoringOfficerInviteResource> getInviteByHash(String hash); @Override @Transactional ServiceResult<MonitoringOfficerInviteResource> openInvite(String hash); @Override @Transactional ServiceResult<User> activateUserByHash(String inviteHash, MonitoringOfficerRegistrationResource resource); @Override ServiceResult<Boolean> checkUserExistsForInvite(String hash); @Override @Transactional ServiceResult<User> addMonitoringOfficerRole(String hash); }
@Test public void openInvite() { String hash = "hash"; MonitoringOfficerInvite invite = new MonitoringOfficerInvite("name", "email", hash, InviteStatus.SENT); MonitoringOfficerInviteResource inviteResource = newMonitoringOfficerInviteResource().build(); when(monitoringOfficerInviteRepositoryMock.getByHash(hash)).thenReturn(invite); when(monitoringOfficerInviteMapperMock.mapToResource(invite)).thenReturn(inviteResource); MonitoringOfficerInviteResource actualInviteResource = service.openInvite(hash).getSuccess(); assertEquals(inviteResource, actualInviteResource); assertEquals(InviteStatus.OPENED, invite.getStatus()); InOrder inOrder = inOrder(monitoringOfficerInviteRepositoryMock, monitoringOfficerInviteMapperMock); inOrder.verify(monitoringOfficerInviteRepositoryMock).getByHash(hash); inOrder.verify(monitoringOfficerInviteMapperMock).mapToResource(invite); inOrder.verifyNoMoreInteractions(); } @Test public void openInvite_notFound() { String hash = "hash"; when(monitoringOfficerInviteRepositoryMock.getByHash(hash)).thenReturn(null); ServiceResult<MonitoringOfficerInviteResource> result = service.openInvite(hash); assertTrue(result.isFailure()); verify(monitoringOfficerInviteRepositoryMock, only()).getByHash(hash); }
MonitoringOfficerInviteServiceImpl extends InviteService<MonitoringOfficerInvite> implements MonitoringOfficerInviteService { @Override @Transactional public ServiceResult<Void> inviteMonitoringOfficer(User invitedUser, Project project) { return validateInvite(invitedUser) .andOnSuccess(this::validateUserExists) .andOnSuccess(this::validateUserIsNotInternal) .andOnSuccess(user -> sendEmailToRegisteredOrUnregistered(user, project)); } @Override @Transactional ServiceResult<Void> inviteMonitoringOfficer(User invitedUser, Project project); @Override ServiceResult<MonitoringOfficerInviteResource> getInviteByHash(String hash); @Override @Transactional ServiceResult<MonitoringOfficerInviteResource> openInvite(String hash); @Override @Transactional ServiceResult<User> activateUserByHash(String inviteHash, MonitoringOfficerRegistrationResource resource); @Override ServiceResult<Boolean> checkUserExistsForInvite(String hash); @Override @Transactional ServiceResult<User> addMonitoringOfficerRole(String hash); }
@Test public void inviteUnregisteredMonitoringOfficer() { User user = newUser() .withFirstName("Donald") .withLastName("Tusk") .withEmailAddress("[email protected]") .withStatus(PENDING) .build(); Project project = newProject() .withApplication(newApplication() .withCompetition(newCompetition().build()) .build()) .build(); when(userRepositoryMock.existsById(user.getId())).thenReturn(true); when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user)); when(monitoringOfficerInviteRepositoryMock.save(any(MonitoringOfficerInvite.class))) .thenReturn(new MonitoringOfficerInvite()); when(notificationServiceMock.sendNotificationWithFlush(any(Notification.class), any(NotificationMedium.class))) .thenReturn(serviceSuccess()); when(loggedInUserSupplierMock.get()).thenReturn(newUser().build()); ServiceResult<Void> result = service.inviteMonitoringOfficer(user, project); assertTrue(result.isSuccess()); InOrder inOrder = inOrder(monitoringOfficerInviteRepositoryMock, notificationServiceMock, loggedInUserSupplierMock); inOrder.verify(monitoringOfficerInviteRepositoryMock).save(any(MonitoringOfficerInvite.class)); inOrder.verify(notificationServiceMock).sendNotificationWithFlush(any(Notification.class), any(NotificationMedium.class)); inOrder.verify(loggedInUserSupplierMock).get(); inOrder.verify(monitoringOfficerInviteRepositoryMock).save(any(MonitoringOfficerInvite.class)); inOrder.verifyNoMoreInteractions(); } @Test public void inviteRegisteredMonitoringOfficer() { User user = newUser() .withFirstName("Michel") .withLastName("Barnier") .withEmailAddress("[email protected]") .build(); Project project = newProject() .withApplication(newApplication() .withCompetition(newCompetition().build()) .build()) .build(); when(userRepositoryMock.existsById(user.getId())).thenReturn(true); when(notificationServiceMock.sendNotificationWithFlush(any(Notification.class), any(NotificationMedium.class))) .thenReturn(serviceSuccess()); ServiceResult<Void> result = service.inviteMonitoringOfficer(user, project); assertTrue(result.isSuccess()); InOrder inOrder = inOrder(monitoringOfficerInviteRepositoryMock, notificationServiceMock); inOrder.verify(notificationServiceMock).sendNotificationWithFlush(any(Notification.class), any(NotificationMedium.class)); inOrder.verifyNoMoreInteractions(); }
ProjectStateController { @PostMapping("/{projectId}/withdraw") public RestResult<Void> withdrawProject(@PathVariable("projectId") final long projectId) { return projectStateService.withdrawProject(projectId).toPostWithBodyResponse(); } @Autowired ProjectStateController(ProjectStateService projectStateService); @PostMapping("/{projectId}/withdraw") RestResult<Void> withdrawProject(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/handle-offline") RestResult<Void> handleProjectOffline(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/complete-offline") RestResult<Void> completeProjectOffline(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/on-hold") RestResult<Void> putProjectOnHold(@PathVariable("projectId") final long projectId, @RequestBody OnHoldReasonResource reason); @PostMapping("/{projectId}/resume") RestResult<Void> resumeProject(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/successful") RestResult<Void> markAsSuccessful(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/unsuccessful") RestResult<Void> markAsUnsuccessful(@PathVariable("projectId") final long projectId); }
@Test public void testWithdrawProject() throws Exception { long projectId = 456L; when(projectStateService.withdrawProject(projectId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/withdraw", projectId)) .andExpect(status().isOk()); verify(projectStateService).withdrawProject(projectId); } @Test public void testWithdrawProjectFails() throws Exception { long projectId = 789L; when(projectStateService.withdrawProject(projectId)).thenReturn(serviceFailure(PROJECT_CANNOT_BE_WITHDRAWN)); mockMvc.perform(post("/project/{projectId}/withdraw", projectId)) .andExpect(status().isBadRequest()); verify(projectStateService, only()).withdrawProject(projectId); } @Test public void testWithdrawProjectWhenProjectDoesntExist() throws Exception { long projectId = 432L; when(projectStateService.withdrawProject(projectId)).thenReturn(serviceFailure(GENERAL_NOT_FOUND)); mockMvc.perform(post("/project/{projectId}/withdraw", projectId)) .andExpect(status().isNotFound()); verify(projectStateService, only()).withdrawProject(projectId); }
UserPermissionRules { @PermissionRule(value = "CHECK_USER_APPLICATION", description = "The user can check if they have an application for the competition") public boolean userCanCheckTheyHaveApplicationForCompetition(UserResource userToCheck, UserResource user) { return userToCheck.getId().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 userCanCheckTheyHaveApplicationForCompetition() { UserResource user = newUserResource().build(); assertTrue(rules.userCanCheckTheyHaveApplicationForCompetition(user, user)); } @Test public void userCanCheckTheyHaveApplicationForCompetitionButAttemptingToCheckAnotherUser() { UserResource user = newUserResource().build(); UserResource anotherUser = newUserResource().build(); assertFalse(rules.userCanCheckTheyHaveApplicationForCompetition(user, anotherUser)); }
ProjectStateController { @PostMapping("/{projectId}/handle-offline") public RestResult<Void> handleProjectOffline(@PathVariable("projectId") final long projectId) { return projectStateService.handleProjectOffline(projectId).toPostWithBodyResponse(); } @Autowired ProjectStateController(ProjectStateService projectStateService); @PostMapping("/{projectId}/withdraw") RestResult<Void> withdrawProject(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/handle-offline") RestResult<Void> handleProjectOffline(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/complete-offline") RestResult<Void> completeProjectOffline(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/on-hold") RestResult<Void> putProjectOnHold(@PathVariable("projectId") final long projectId, @RequestBody OnHoldReasonResource reason); @PostMapping("/{projectId}/resume") RestResult<Void> resumeProject(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/successful") RestResult<Void> markAsSuccessful(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/unsuccessful") RestResult<Void> markAsUnsuccessful(@PathVariable("projectId") final long projectId); }
@Test public void handleProjectOffline() throws Exception { long projectId = 456L; when(projectStateService.handleProjectOffline(projectId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/handle-offline", projectId)) .andExpect(status().isOk()); verify(projectStateService, only()).handleProjectOffline(projectId); }
ProjectStateController { @PostMapping("/{projectId}/complete-offline") public RestResult<Void> completeProjectOffline(@PathVariable("projectId") final long projectId) { return projectStateService.completeProjectOffline(projectId).toPostWithBodyResponse(); } @Autowired ProjectStateController(ProjectStateService projectStateService); @PostMapping("/{projectId}/withdraw") RestResult<Void> withdrawProject(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/handle-offline") RestResult<Void> handleProjectOffline(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/complete-offline") RestResult<Void> completeProjectOffline(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/on-hold") RestResult<Void> putProjectOnHold(@PathVariable("projectId") final long projectId, @RequestBody OnHoldReasonResource reason); @PostMapping("/{projectId}/resume") RestResult<Void> resumeProject(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/successful") RestResult<Void> markAsSuccessful(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/unsuccessful") RestResult<Void> markAsUnsuccessful(@PathVariable("projectId") final long projectId); }
@Test public void completeProjectOffline() throws Exception { long projectId = 456L; when(projectStateService.completeProjectOffline(projectId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/complete-offline", projectId)) .andExpect(status().isOk()); verify(projectStateService, only()).completeProjectOffline(projectId); }
ProjectStateController { @PostMapping("/{projectId}/on-hold") public RestResult<Void> putProjectOnHold(@PathVariable("projectId") final long projectId, @RequestBody OnHoldReasonResource reason) { return projectStateService.putProjectOnHold(projectId, reason).toPostWithBodyResponse(); } @Autowired ProjectStateController(ProjectStateService projectStateService); @PostMapping("/{projectId}/withdraw") RestResult<Void> withdrawProject(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/handle-offline") RestResult<Void> handleProjectOffline(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/complete-offline") RestResult<Void> completeProjectOffline(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/on-hold") RestResult<Void> putProjectOnHold(@PathVariable("projectId") final long projectId, @RequestBody OnHoldReasonResource reason); @PostMapping("/{projectId}/resume") RestResult<Void> resumeProject(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/successful") RestResult<Void> markAsSuccessful(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/unsuccessful") RestResult<Void> markAsUnsuccessful(@PathVariable("projectId") final long projectId); }
@Test public void putProjectOnHold() throws Exception { long projectId = 456L; OnHoldReasonResource reason = new OnHoldReasonResource("Title", "Body"); when(projectStateService.putProjectOnHold(projectId, reason)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/on-hold", projectId) .contentType(APPLICATION_JSON) .content(objectMapper.writeValueAsString(reason))) .andExpect(status().isOk()); verify(projectStateService).putProjectOnHold(projectId, reason); }
ProjectStateController { @PostMapping("/{projectId}/resume") public RestResult<Void> resumeProject(@PathVariable("projectId") final long projectId) { return projectStateService.resumeProject(projectId).toPostWithBodyResponse(); } @Autowired ProjectStateController(ProjectStateService projectStateService); @PostMapping("/{projectId}/withdraw") RestResult<Void> withdrawProject(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/handle-offline") RestResult<Void> handleProjectOffline(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/complete-offline") RestResult<Void> completeProjectOffline(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/on-hold") RestResult<Void> putProjectOnHold(@PathVariable("projectId") final long projectId, @RequestBody OnHoldReasonResource reason); @PostMapping("/{projectId}/resume") RestResult<Void> resumeProject(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/successful") RestResult<Void> markAsSuccessful(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/unsuccessful") RestResult<Void> markAsUnsuccessful(@PathVariable("projectId") final long projectId); }
@Test public void resumeProject() throws Exception { long projectId = 456L; when(projectStateService.resumeProject(projectId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/resume", projectId)) .andExpect(status().isOk()); verify(projectStateService).resumeProject(projectId); }
ProjectStateController { @PostMapping("/{projectId}/successful") public RestResult<Void> markAsSuccessful(@PathVariable("projectId") final long projectId) { return projectStateService.markAsSuccessful(projectId).toPostWithBodyResponse(); } @Autowired ProjectStateController(ProjectStateService projectStateService); @PostMapping("/{projectId}/withdraw") RestResult<Void> withdrawProject(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/handle-offline") RestResult<Void> handleProjectOffline(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/complete-offline") RestResult<Void> completeProjectOffline(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/on-hold") RestResult<Void> putProjectOnHold(@PathVariable("projectId") final long projectId, @RequestBody OnHoldReasonResource reason); @PostMapping("/{projectId}/resume") RestResult<Void> resumeProject(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/successful") RestResult<Void> markAsSuccessful(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/unsuccessful") RestResult<Void> markAsUnsuccessful(@PathVariable("projectId") final long projectId); }
@Test public void markAsSuccessful() throws Exception { long projectId = 456L; when(projectStateService.markAsSuccessful(projectId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/successful", projectId)) .andExpect(status().isOk()); verify(projectStateService).markAsSuccessful(projectId); }
ProjectStateController { @PostMapping("/{projectId}/unsuccessful") public RestResult<Void> markAsUnsuccessful(@PathVariable("projectId") final long projectId) { return projectStateService.markAsUnsuccessful(projectId).toPostWithBodyResponse(); } @Autowired ProjectStateController(ProjectStateService projectStateService); @PostMapping("/{projectId}/withdraw") RestResult<Void> withdrawProject(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/handle-offline") RestResult<Void> handleProjectOffline(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/complete-offline") RestResult<Void> completeProjectOffline(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/on-hold") RestResult<Void> putProjectOnHold(@PathVariable("projectId") final long projectId, @RequestBody OnHoldReasonResource reason); @PostMapping("/{projectId}/resume") RestResult<Void> resumeProject(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/successful") RestResult<Void> markAsSuccessful(@PathVariable("projectId") final long projectId); @PostMapping("/{projectId}/unsuccessful") RestResult<Void> markAsUnsuccessful(@PathVariable("projectId") final long projectId); }
@Test public void markAsUnsuccessful() throws Exception { long projectId = 456L; when(projectStateService.markAsUnsuccessful(projectId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/unsuccessful", projectId)) .andExpect(status().isOk()); verify(projectStateService).markAsUnsuccessful(projectId); }
ProjectStateServiceImpl extends BaseTransactionalService implements ProjectStateService { @Override @Transactional public ServiceResult<Void> withdrawProject(long projectId) { return getProject(projectId).andOnSuccess( project -> getCurrentlyLoggedInUser().andOnSuccess(user -> projectWorkflowHandler.projectWithdrawn(project, user) ? serviceSuccess() : serviceFailure(PROJECT_CANNOT_BE_WITHDRAWN)) ).andOnSuccessReturnVoid(() -> projectStateCommentsService.create(projectId, ProjectState.WITHDRAWN)); } @Override @Transactional ServiceResult<Void> withdrawProject(long projectId); @Override @Transactional ServiceResult<Void> handleProjectOffline(long projectId); @Override @Transactional ServiceResult<Void> completeProjectOffline(long projectId); @Override @Transactional ServiceResult<Void> putProjectOnHold(long projectId, OnHoldReasonResource reason); @Override @Transactional ServiceResult<Void> resumeProject(long projectId); @Override @Transactional ServiceResult<Void> markAsSuccessful(long projectId); @Override @Transactional ServiceResult<Void> markAsUnsuccessful(long projectId); }
@Test public void withdrawProject() { long projectId = 123L; long userId = 456L; Project project = newProject().withId(projectId).build(); UserResource loggedInUser = newUserResource() .withRoleGlobal(IFS_ADMINISTRATOR) .withId(userId) .build(); User user = newUser() .withId(userId) .build(); setLoggedInUser(loggedInUser); when(userRepositoryMock.findById(userId)).thenReturn(Optional.of(user)); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.of(project)); when(projectWorkflowHandlerMock.projectWithdrawn(eq(project), any())).thenReturn(true); ServiceResult<Void> result = service.withdrawProject(projectId); assertTrue(result.isSuccess()); verify(projectRepositoryMock).findById(projectId); verify(userRepositoryMock).findById(userId); verify(projectWorkflowHandlerMock).projectWithdrawn(eq(project), any()); verify(projectStateCommentsService).create(projectId, ProjectState.WITHDRAWN); } @Test public void withdrawProject_fails() { long projectId = 321L; long userId = 987L; Project project = newProject().withId(projectId).build(); UserResource loggedInUser = newUserResource() .withRoleGlobal(IFS_ADMINISTRATOR) .withId(userId) .build(); User user = newUser() .withId(userId) .build(); when(userRepositoryMock.findById(userId)).thenReturn(Optional.of(user)); setLoggedInUser(loggedInUser); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.of(project)); when(projectWorkflowHandlerMock.projectWithdrawn(eq(project), any())).thenReturn(false); ServiceResult<Void> result = service.withdrawProject(projectId); assertTrue(result.isFailure()); assertEquals(PROJECT_CANNOT_BE_WITHDRAWN.getErrorKey(), result.getErrors().get(0).getErrorKey()); verify(projectRepositoryMock).findById(projectId); verify(userRepositoryMock).findById(userId); verify(projectWorkflowHandlerMock).projectWithdrawn(eq(project), any()); verifyZeroInteractions(projectStateCommentsService); } @Test public void withdrawProject_cannotFindIdFails() { long projectId = 456L; Project project = newProject().withId(projectId).build(); UserResource user = newUserResource() .withRoleGlobal(IFS_ADMINISTRATOR) .build(); setLoggedInUser(user); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.empty()); when(projectWorkflowHandlerMock.projectWithdrawn(eq(project), any())).thenReturn(false); ServiceResult<Void> result = service.withdrawProject(projectId); assertTrue(result.isFailure()); verify(projectRepositoryMock).findById(projectId); verifyZeroInteractions(projectWorkflowHandlerMock); verifyZeroInteractions(projectStateCommentsService); }
ProjectStateServiceImpl extends BaseTransactionalService implements ProjectStateService { @Override @Transactional public ServiceResult<Void> handleProjectOffline(long projectId) { return getProject(projectId).andOnSuccess( project -> getCurrentlyLoggedInUser().andOnSuccess(user -> projectWorkflowHandler.handleProjectOffline(project, user) ? serviceSuccess() : serviceFailure(PROJECT_CANNOT_BE_HANDLED_OFFLINE)) ).andOnSuccessReturnVoid(() -> projectStateCommentsService.create(projectId, ProjectState.HANDLED_OFFLINE)); } @Override @Transactional ServiceResult<Void> withdrawProject(long projectId); @Override @Transactional ServiceResult<Void> handleProjectOffline(long projectId); @Override @Transactional ServiceResult<Void> completeProjectOffline(long projectId); @Override @Transactional ServiceResult<Void> putProjectOnHold(long projectId, OnHoldReasonResource reason); @Override @Transactional ServiceResult<Void> resumeProject(long projectId); @Override @Transactional ServiceResult<Void> markAsSuccessful(long projectId); @Override @Transactional ServiceResult<Void> markAsUnsuccessful(long projectId); }
@Test public void handleProjectOffline() { long projectId = 123L; long userId = 456L; Project project = newProject().withId(projectId).build(); UserResource loggedInUser = newUserResource() .withRoleGlobal(IFS_ADMINISTRATOR) .withId(userId) .build(); User user = newUser() .withId(userId) .build(); setLoggedInUser(loggedInUser); when(userRepositoryMock.findById(userId)).thenReturn(Optional.ofNullable(user)); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.ofNullable(project)); when(projectWorkflowHandlerMock.handleProjectOffline(eq(project), any())).thenReturn(true); ServiceResult<Void> result = service.handleProjectOffline(projectId); assertTrue(result.isSuccess()); verify(projectRepositoryMock).findById(projectId); verify(userRepositoryMock).findById(userId); verify(projectWorkflowHandlerMock).handleProjectOffline(eq(project), any()); verify(projectStateCommentsService).create(projectId, ProjectState.HANDLED_OFFLINE); }
ProjectStateServiceImpl extends BaseTransactionalService implements ProjectStateService { @Override @Transactional public ServiceResult<Void> completeProjectOffline(long projectId) { return getProject(projectId).andOnSuccess( project -> getCurrentlyLoggedInUser().andOnSuccess(user -> projectWorkflowHandler.completeProjectOffline(project, user) ? serviceSuccess() : serviceFailure(PROJECT_CANNOT_BE_COMPLETED_OFFLINE)) ).andOnSuccessReturnVoid(() -> projectStateCommentsService.create(projectId, ProjectState.COMPLETED_OFFLINE)); } @Override @Transactional ServiceResult<Void> withdrawProject(long projectId); @Override @Transactional ServiceResult<Void> handleProjectOffline(long projectId); @Override @Transactional ServiceResult<Void> completeProjectOffline(long projectId); @Override @Transactional ServiceResult<Void> putProjectOnHold(long projectId, OnHoldReasonResource reason); @Override @Transactional ServiceResult<Void> resumeProject(long projectId); @Override @Transactional ServiceResult<Void> markAsSuccessful(long projectId); @Override @Transactional ServiceResult<Void> markAsUnsuccessful(long projectId); }
@Test public void completeProjectOffline() { long projectId = 123L; long userId = 456L; Project project = newProject().withId(projectId).build(); UserResource loggedInUser = newUserResource() .withRoleGlobal(IFS_ADMINISTRATOR) .withId(userId) .build(); User user = newUser() .withId(userId) .build(); setLoggedInUser(loggedInUser); when(userRepositoryMock.findById(userId)).thenReturn(Optional.ofNullable(user)); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.ofNullable(project)); when(projectWorkflowHandlerMock.completeProjectOffline(eq(project), any())).thenReturn(true); ServiceResult<Void> result = service.completeProjectOffline(projectId); assertTrue(result.isSuccess()); verify(projectRepositoryMock).findById(projectId); verify(userRepositoryMock).findById(userId); verify(projectWorkflowHandlerMock).completeProjectOffline(eq(project), any()); verify(projectStateCommentsService).create(projectId, ProjectState.COMPLETED_OFFLINE); }
ProjectStateServiceImpl extends BaseTransactionalService implements ProjectStateService { @Override @Transactional public ServiceResult<Void> putProjectOnHold(long projectId, OnHoldReasonResource reason) { return getProject(projectId).andOnSuccess( project -> getCurrentlyLoggedInUser().andOnSuccess(user -> projectWorkflowHandler.putProjectOnHold(project, user) ? serviceSuccess() : serviceFailure(PROJECT_CANNOT_BE_PUT_ON_HOLD)) ).andOnSuccessReturnVoid(() -> projectStateCommentsService.create(projectId, ProjectState.ON_HOLD, reason)); } @Override @Transactional ServiceResult<Void> withdrawProject(long projectId); @Override @Transactional ServiceResult<Void> handleProjectOffline(long projectId); @Override @Transactional ServiceResult<Void> completeProjectOffline(long projectId); @Override @Transactional ServiceResult<Void> putProjectOnHold(long projectId, OnHoldReasonResource reason); @Override @Transactional ServiceResult<Void> resumeProject(long projectId); @Override @Transactional ServiceResult<Void> markAsSuccessful(long projectId); @Override @Transactional ServiceResult<Void> markAsUnsuccessful(long projectId); }
@Test public void putProjectOnHold() { long projectId = 123L; long userId = 456L; OnHoldReasonResource onHoldReasonResource = new OnHoldReasonResource("Title", "Body"); Project project = newProject().withId(projectId).build(); UserResource loggedInUser = newUserResource() .withRoleGlobal(PROJECT_FINANCE) .withId(userId) .build(); User user = newUser() .withId(userId) .build(); setLoggedInUser(loggedInUser); when(userRepositoryMock.findById(userId)).thenReturn(Optional.ofNullable(user)); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.ofNullable(project)); when(projectWorkflowHandlerMock.putProjectOnHold(eq(project), any())).thenReturn(true); ServiceResult<Void> result = service.putProjectOnHold(projectId, onHoldReasonResource); assertTrue(result.isSuccess()); verify(projectRepositoryMock).findById(projectId); verify(userRepositoryMock).findById(userId); verify(projectWorkflowHandlerMock).putProjectOnHold(eq(project), any()); verify(projectStateCommentsService).create(projectId, ProjectState.ON_HOLD, onHoldReasonResource); }
ProjectStateServiceImpl extends BaseTransactionalService implements ProjectStateService { @Override @Transactional public ServiceResult<Void> resumeProject(long projectId) { return getProject(projectId).andOnSuccess( project -> getCurrentlyLoggedInUser().andOnSuccess(user -> projectWorkflowHandler.resumeProject(project, user) ? serviceSuccess() : serviceFailure(PROJECT_CANNOT_BE_RESUMED)) ).andOnSuccessReturnVoid(() -> projectStateCommentsService.create(projectId, ProjectState.SETUP)); } @Override @Transactional ServiceResult<Void> withdrawProject(long projectId); @Override @Transactional ServiceResult<Void> handleProjectOffline(long projectId); @Override @Transactional ServiceResult<Void> completeProjectOffline(long projectId); @Override @Transactional ServiceResult<Void> putProjectOnHold(long projectId, OnHoldReasonResource reason); @Override @Transactional ServiceResult<Void> resumeProject(long projectId); @Override @Transactional ServiceResult<Void> markAsSuccessful(long projectId); @Override @Transactional ServiceResult<Void> markAsUnsuccessful(long projectId); }
@Test public void resumeProject() { long projectId = 123L; long userId = 456L; Project project = newProject().withId(projectId).build(); UserResource loggedInUser = newUserResource() .withRoleGlobal(PROJECT_FINANCE) .withId(userId) .build(); User user = newUser() .withId(userId) .build(); setLoggedInUser(loggedInUser); when(userRepositoryMock.findById(userId)).thenReturn(Optional.ofNullable(user)); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.ofNullable(project)); when(projectWorkflowHandlerMock.resumeProject(eq(project), any())).thenReturn(true); ServiceResult<Void> result = service.resumeProject(projectId); assertTrue(result.isSuccess()); verify(projectRepositoryMock).findById(projectId); verify(userRepositoryMock).findById(userId); verify(projectWorkflowHandlerMock).resumeProject(eq(project), any()); verify(projectStateCommentsService).create(projectId, ProjectState.SETUP); }
ProjectStateServiceImpl extends BaseTransactionalService implements ProjectStateService { @Override @Transactional public ServiceResult<Void> markAsSuccessful(long projectId) { return getProject(projectId).andOnSuccess( project -> getCurrentlyLoggedInUser().andOnSuccess(user -> projectWorkflowHandler.markAsSuccessful(project, user) ? serviceSuccess() : serviceFailure(PROJECT_CANNOT_BE_MARKED_AS_SUCCESSFUL)) ).andOnSuccessReturnVoid(() -> projectStateCommentsService.create(projectId, ProjectState.LIVE)); } @Override @Transactional ServiceResult<Void> withdrawProject(long projectId); @Override @Transactional ServiceResult<Void> handleProjectOffline(long projectId); @Override @Transactional ServiceResult<Void> completeProjectOffline(long projectId); @Override @Transactional ServiceResult<Void> putProjectOnHold(long projectId, OnHoldReasonResource reason); @Override @Transactional ServiceResult<Void> resumeProject(long projectId); @Override @Transactional ServiceResult<Void> markAsSuccessful(long projectId); @Override @Transactional ServiceResult<Void> markAsUnsuccessful(long projectId); }
@Test public void markAsSuccessful() { long projectId = 123L; long userId = 456L; Project project = newProject().withId(projectId).build(); UserResource loggedInUser = newUserResource() .withRoleGlobal(PROJECT_FINANCE) .withId(userId) .build(); User user = newUser() .withId(userId) .build(); setLoggedInUser(loggedInUser); when(userRepositoryMock.findById(userId)).thenReturn(Optional.ofNullable(user)); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.ofNullable(project)); when(projectWorkflowHandlerMock.markAsSuccessful(eq(project), any())).thenReturn(true); ServiceResult<Void> result = service.markAsSuccessful(projectId); assertTrue(result.isSuccess()); verify(projectRepositoryMock).findById(projectId); verify(userRepositoryMock).findById(userId); verify(projectWorkflowHandlerMock).markAsSuccessful(eq(project), any()); verify(projectStateCommentsService).create(projectId, ProjectState.LIVE); }
ProjectStateServiceImpl extends BaseTransactionalService implements ProjectStateService { @Override @Transactional public ServiceResult<Void> markAsUnsuccessful(long projectId) { return getProject(projectId).andOnSuccess( project -> getCurrentlyLoggedInUser().andOnSuccess(user -> projectWorkflowHandler.markAsUnsuccessful(project, user) ? serviceSuccess() : serviceFailure(PROJECT_CANNOT_BE_MARKED_AS_UNSUCCESSFUL)) ).andOnSuccessReturnVoid(() -> projectStateCommentsService.create(projectId, ProjectState.UNSUCCESSFUL)); } @Override @Transactional ServiceResult<Void> withdrawProject(long projectId); @Override @Transactional ServiceResult<Void> handleProjectOffline(long projectId); @Override @Transactional ServiceResult<Void> completeProjectOffline(long projectId); @Override @Transactional ServiceResult<Void> putProjectOnHold(long projectId, OnHoldReasonResource reason); @Override @Transactional ServiceResult<Void> resumeProject(long projectId); @Override @Transactional ServiceResult<Void> markAsSuccessful(long projectId); @Override @Transactional ServiceResult<Void> markAsUnsuccessful(long projectId); }
@Test public void markAsUnsuccessful() { long projectId = 123L; long userId = 456L; Project project = newProject().withId(projectId).build(); UserResource loggedInUser = newUserResource() .withRoleGlobal(PROJECT_FINANCE) .withId(userId) .build(); User user = newUser() .withId(userId) .build(); setLoggedInUser(loggedInUser); when(userRepositoryMock.findById(userId)).thenReturn(Optional.ofNullable(user)); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.ofNullable(project)); when(projectWorkflowHandlerMock.markAsUnsuccessful(eq(project), any())).thenReturn(true); ServiceResult<Void> result = service.markAsUnsuccessful(projectId); assertTrue(result.isSuccess()); verify(projectRepositoryMock).findById(projectId); verify(userRepositoryMock).findById(userId); verify(projectWorkflowHandlerMock).markAsUnsuccessful(eq(project), any()); verify(projectStateCommentsService).create(projectId, ProjectState.UNSUCCESSFUL); }
ProjectDetailsPermissionRules extends BasePermissionRules { @PermissionRule( value = "UPDATE_BASIC_PROJECT_SETUP_DETAILS", description = "The lead partners can update the basic project details, address, Project Manager") public boolean leadPartnersCanUpdateTheBasicProjectDetails(ProjectResource project, UserResource user) { return isLeadPartner(project.getId(), user.getId()) && isProjectActive(project.getId()); } @PermissionRule( value = "UPDATE_BASIC_PROJECT_SETUP_DETAILS", description = "The lead partners can update the basic project details, address, Project Manager") boolean leadPartnersCanUpdateTheBasicProjectDetails(ProjectResource project, UserResource user); @PermissionRule( value = "UPDATE_START_DATE", description = "The IFS Administrator can update the project start date") boolean ifsAdministratorCanUpdateTheProjectStartDate(ProjectResource project, UserResource user); @PermissionRule( value = "UPDATE_FINANCE_CONTACT", description = "A partner can update the finance contact for their own organisation") boolean partnersCanUpdateTheirOwnOrganisationsFinanceContacts(ProjectOrganisationCompositeId composite, UserResource user); @PermissionRule(value = "UPDATE_PARTNER_PROJECT_LOCATION", description = "A partner can update the project location for their own organisation") boolean partnersCanUpdateProjectLocationForTheirOwnOrganisation(ProjectOrganisationCompositeId composite, UserResource user); }
@Test public void leadPartnersCanUpdateTheBasicProjectDetails() { UserResource user = newUserResource().build(); setupUserAsLeadPartner(project, user); when(projectProcessRepository.findOneByTargetId(project.getId())).thenReturn(projectProcess); assertTrue(rules.leadPartnersCanUpdateTheBasicProjectDetails(project, user)); } @Test public void leadPartnersCanUpdateTheBasicProjectDetailsButUserNotLeadPartner() { Application originalApplication = newApplication().build(); Project projectEntity = newProject().withApplication(originalApplication).build(); UserResource user = newUserResource().build(); Organisation leadOrganisation = newOrganisation().build(); ProcessRole leadApplicantProcessRole = newProcessRole().withOrganisationId(leadOrganisation.getId()).build(); when(projectRepository.findById(project.getId())).thenReturn(Optional.of(projectEntity)); when(processRoleRepository.findOneByApplicationIdAndRole(projectEntity.getApplication().getId(), LEADAPPLICANT)).thenReturn(leadApplicantProcessRole); when(organisationRepository.findById(leadOrganisation.getId())).thenReturn(Optional.of(leadOrganisation)); when(projectUserRepository.findOneByProjectIdAndUserIdAndOrganisationIdAndRole( project.getId(), user.getId(), leadOrganisation.getId(), PROJECT_PARTNER)).thenReturn(null); assertFalse(rules.leadPartnersCanUpdateTheBasicProjectDetails(project, user)); }
ProjectDetailsPermissionRules extends BasePermissionRules { @PermissionRule( value = "UPDATE_START_DATE", description = "The IFS Administrator can update the project start date") public boolean ifsAdministratorCanUpdateTheProjectStartDate(ProjectResource project, UserResource user) { return isIFSAdmin(user) && isProjectActive(project.getId()); } @PermissionRule( value = "UPDATE_BASIC_PROJECT_SETUP_DETAILS", description = "The lead partners can update the basic project details, address, Project Manager") boolean leadPartnersCanUpdateTheBasicProjectDetails(ProjectResource project, UserResource user); @PermissionRule( value = "UPDATE_START_DATE", description = "The IFS Administrator can update the project start date") boolean ifsAdministratorCanUpdateTheProjectStartDate(ProjectResource project, UserResource user); @PermissionRule( value = "UPDATE_FINANCE_CONTACT", description = "A partner can update the finance contact for their own organisation") boolean partnersCanUpdateTheirOwnOrganisationsFinanceContacts(ProjectOrganisationCompositeId composite, UserResource user); @PermissionRule(value = "UPDATE_PARTNER_PROJECT_LOCATION", description = "A partner can update the project location for their own organisation") boolean partnersCanUpdateProjectLocationForTheirOwnOrganisation(ProjectOrganisationCompositeId composite, UserResource user); }
@Test public void ifsAdministratorCanUpdateTheProjectStartDate() { UserResource user = newUserResource().withRoleGlobal(IFS_ADMINISTRATOR).build(); when(projectProcessRepository.findOneByTargetId(project.getId())).thenReturn(projectProcess); assertTrue(rules.ifsAdministratorCanUpdateTheProjectStartDate(project, user)); }
ProjectDetailsPermissionRules extends BasePermissionRules { @PermissionRule( value = "UPDATE_FINANCE_CONTACT", description = "A partner can update the finance contact for their own organisation") public boolean partnersCanUpdateTheirOwnOrganisationsFinanceContacts(ProjectOrganisationCompositeId composite, UserResource user) { return isPartner(composite.getProjectId(), user.getId()) && isProjectActive(composite.getProjectId()) && partnerBelongsToOrganisation(composite.getProjectId(), user.getId(), composite.getOrganisationId()); } @PermissionRule( value = "UPDATE_BASIC_PROJECT_SETUP_DETAILS", description = "The lead partners can update the basic project details, address, Project Manager") boolean leadPartnersCanUpdateTheBasicProjectDetails(ProjectResource project, UserResource user); @PermissionRule( value = "UPDATE_START_DATE", description = "The IFS Administrator can update the project start date") boolean ifsAdministratorCanUpdateTheProjectStartDate(ProjectResource project, UserResource user); @PermissionRule( value = "UPDATE_FINANCE_CONTACT", description = "A partner can update the finance contact for their own organisation") boolean partnersCanUpdateTheirOwnOrganisationsFinanceContacts(ProjectOrganisationCompositeId composite, UserResource user); @PermissionRule(value = "UPDATE_PARTNER_PROJECT_LOCATION", description = "A partner can update the project location for their own organisation") boolean partnersCanUpdateProjectLocationForTheirOwnOrganisation(ProjectOrganisationCompositeId composite, UserResource user); }
@Test public void partnersCanUpdateTheirOwnOrganisationsFinanceContacts() { Organisation organisation = newOrganisation().build(); ProjectOrganisationCompositeId composite = new ProjectOrganisationCompositeId(project.getId(), organisation.getId()); UserResource user = newUserResource().build(); setupUserAsPartner(project, user); when(projectUserRepository.findFirstByProjectIdAndUserIdAndOrganisationIdAndRoleIn(project.getId(), user.getId(), organisation.getId(), PROJECT_USER_ROLES.stream().collect(Collectors.toList()))).thenReturn(new ProjectUser()); when(projectProcessRepository.findOneByTargetId(project.getId())).thenReturn(projectProcess); assertTrue(rules.partnersCanUpdateTheirOwnOrganisationsFinanceContacts(composite, user)); } @Test public void partnersCanUpdateTheirOwnOrganisationsFinanceContactsButUserNotPartner() { Organisation organisation = newOrganisation().build(); ProjectOrganisationCompositeId composite = new ProjectOrganisationCompositeId(project.getId(), organisation.getId()); UserResource user = newUserResource().build(); when(projectUserRepository.findByProjectIdAndUserIdAndRoleIsIn(project.getId(), user.getId(), PROJECT_USER_ROLES.stream().collect(Collectors.toList()))).thenReturn(emptyList()); assertFalse(rules.partnersCanUpdateTheirOwnOrganisationsFinanceContacts(composite, user)); } @Test public void partnersCanUpdateTheirOwnOrganisationsFinanceContactsButUserNotMemberOfOrganisation() { Organisation organisation = newOrganisation().build(); ProjectOrganisationCompositeId composite = new ProjectOrganisationCompositeId(project.getId(), organisation.getId()); UserResource user = newUserResource().build(); setupUserAsPartner(project, user); when(projectUserRepository.findOneByProjectIdAndUserIdAndOrganisationIdAndRole(project.getId(), user.getId(), organisation.getId(), PROJECT_PARTNER)).thenReturn(null); when(projectProcessRepository.findOneByTargetId(project.getId())).thenReturn(projectProcess); assertFalse(rules.partnersCanUpdateTheirOwnOrganisationsFinanceContacts(composite, user)); }
UserPermissionRules { @PermissionRule(value = "CAN_VIEW_OWN_DASHBOARD", description = "User is requesting own dashboard") public boolean isViewingOwnDashboard(UserResource userToView, UserResource user) { return userToView.getId().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 isViewingOwnDashboard() { UserResource user = newUserResource().build(); assertTrue(rules.isViewingOwnDashboard(user, user)); } @Test public void isNotViewingOwnDashboard() { UserResource user = newUserResource().build(); UserResource anotherUser = newUserResource().build(); assertFalse(rules.isViewingOwnDashboard(user, anotherUser)); }
ProjectDetailsPermissionRules extends BasePermissionRules { @PermissionRule(value = "UPDATE_PARTNER_PROJECT_LOCATION", description = "A partner can update the project location for their own organisation") public boolean partnersCanUpdateProjectLocationForTheirOwnOrganisation(ProjectOrganisationCompositeId composite, UserResource user) { return partnerBelongsToOrganisation(composite.getProjectId(), user.getId(), composite.getOrganisationId()); } @PermissionRule( value = "UPDATE_BASIC_PROJECT_SETUP_DETAILS", description = "The lead partners can update the basic project details, address, Project Manager") boolean leadPartnersCanUpdateTheBasicProjectDetails(ProjectResource project, UserResource user); @PermissionRule( value = "UPDATE_START_DATE", description = "The IFS Administrator can update the project start date") boolean ifsAdministratorCanUpdateTheProjectStartDate(ProjectResource project, UserResource user); @PermissionRule( value = "UPDATE_FINANCE_CONTACT", description = "A partner can update the finance contact for their own organisation") boolean partnersCanUpdateTheirOwnOrganisationsFinanceContacts(ProjectOrganisationCompositeId composite, UserResource user); @PermissionRule(value = "UPDATE_PARTNER_PROJECT_LOCATION", description = "A partner can update the project location for their own organisation") boolean partnersCanUpdateProjectLocationForTheirOwnOrganisation(ProjectOrganisationCompositeId composite, UserResource user); }
@Test public void partnersCanUpdateProjectLocationForTheirOwnOrganisationWhenUserDoesNotBelongToGivenOrganisation() { long projectId = 1L; long organisationId = 2L; ProjectOrganisationCompositeId composite = new ProjectOrganisationCompositeId(projectId, organisationId); UserResource user = newUserResource().build(); when(projectUserRepository.findFirstByProjectIdAndUserIdAndOrganisationIdAndRoleIn(projectId, user.getId(), organisationId, PROJECT_USER_ROLES.stream().collect(Collectors.toList()))).thenReturn(null); assertFalse(rules.partnersCanUpdateProjectLocationForTheirOwnOrganisation(composite, user)); } @Test public void partnersCanUpdateProjectLocationForTheirOwnOrganisationSuccess() { long projectId = 1L; long organisationId = 2L; ProjectOrganisationCompositeId composite = new ProjectOrganisationCompositeId(projectId, organisationId); UserResource user = newUserResource().build(); when(projectUserRepository.findFirstByProjectIdAndUserIdAndOrganisationIdAndRoleIn(projectId, user.getId(), organisationId, PROJECT_USER_ROLES.stream().collect(Collectors.toList()))).thenReturn(new ProjectUser()); assertTrue(rules.partnersCanUpdateProjectLocationForTheirOwnOrganisation(composite, user)); }
ProjectDetailsController { @GetMapping("/{projectId}/project-manager") public RestResult<ProjectUserResource> getProjectManager(@PathVariable(value = "projectId") Long projectId) { return projectDetailsService.getProjectManager(projectId).toGetResponse(); } @GetMapping("/{projectId}/project-manager") RestResult<ProjectUserResource> getProjectManager(@PathVariable(value = "projectId") Long projectId); @PostMapping(value="/{id}/project-manager/{projectManagerId}") RestResult<Void> setProjectManager(@PathVariable("id") final Long id, @PathVariable("projectManagerId") final Long projectManagerId); @PostMapping("/{projectId}/startdate") RestResult<Void> updateProjectStartDate(@PathVariable("projectId") final Long projectId, @RequestParam("projectStartDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate projectStartDate); @PostMapping("/{projectId}/duration/{durationInMonths}") RestResult<Void> updateProjectDuration(@PathVariable("projectId") final long projectId, @PathVariable("durationInMonths") final long durationInMonths); @PostMapping("/{projectId}/address") RestResult<Void> updateProjectAddress(@PathVariable("projectId") final Long projectId, @RequestBody AddressResource addressResource); @PostMapping("/{projectId}/organisation/{organisation}/finance-contact") RestResult<Void> updateFinanceContact(@PathVariable("projectId") final Long projectId, @PathVariable("organisation") final Long organisationId, @RequestParam("financeContact") Long financeContactUserId); @PostMapping(value = "/{projectId}/organisation/{organisationId}/partner-project-location") RestResult<Void> updatePartnerProjectLocation(@PathVariable("projectId") final long projectId, @PathVariable("organisationId") final long organisationId, @RequestBody PostcodeAndTownResource postcodeAndTown); @PostMapping("/{projectId}/invite-finance-contact") RestResult<Void> inviteFinanceContact(@PathVariable("projectId") final Long projectId, @RequestBody @Valid final ProjectUserInviteResource inviteResource); @PostMapping("/{projectId}/invite-project-manager") RestResult<Void> inviteProjectManager(@PathVariable("projectId") final Long projectId, @RequestBody @Valid final ProjectUserInviteResource inviteResource); }
@Test public void getProjectManager() throws Exception { Long project1Id = 1L; ProjectUserResource projectManager = newProjectUserResource().withId(project1Id).build(); when(projectDetailsService.getProjectManager(project1Id)).thenReturn(serviceSuccess(projectManager)); mockMvc.perform(get("/project/{id}/project-manager", project1Id)) .andExpect(status().isOk()) .andExpect(content().json(toJson(projectManager))); verify(projectDetailsService).getProjectManager(project1Id); verifyNoMoreInteractions(projectDetailsService); } @Test public void getProjectManagerNotFound() throws Exception { Long project1Id = -1L; when(projectDetailsService.getProjectManager(project1Id)).thenReturn(serviceFailure(GENERAL_NOT_FOUND)); mockMvc.perform(get("/project/{id}/project-manager", project1Id)) .andExpect(status().isNotFound()); verify(projectDetailsService).getProjectManager(project1Id); verifyNoMoreInteractions(projectDetailsService); }
ProjectDetailsController { @PostMapping(value="/{id}/project-manager/{projectManagerId}") public RestResult<Void> setProjectManager(@PathVariable("id") final Long id, @PathVariable("projectManagerId") final Long projectManagerId) { return projectDetailsService.setProjectManager(id, projectManagerId).toPostResponse(); } @GetMapping("/{projectId}/project-manager") RestResult<ProjectUserResource> getProjectManager(@PathVariable(value = "projectId") Long projectId); @PostMapping(value="/{id}/project-manager/{projectManagerId}") RestResult<Void> setProjectManager(@PathVariable("id") final Long id, @PathVariable("projectManagerId") final Long projectManagerId); @PostMapping("/{projectId}/startdate") RestResult<Void> updateProjectStartDate(@PathVariable("projectId") final Long projectId, @RequestParam("projectStartDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate projectStartDate); @PostMapping("/{projectId}/duration/{durationInMonths}") RestResult<Void> updateProjectDuration(@PathVariable("projectId") final long projectId, @PathVariable("durationInMonths") final long durationInMonths); @PostMapping("/{projectId}/address") RestResult<Void> updateProjectAddress(@PathVariable("projectId") final Long projectId, @RequestBody AddressResource addressResource); @PostMapping("/{projectId}/organisation/{organisation}/finance-contact") RestResult<Void> updateFinanceContact(@PathVariable("projectId") final Long projectId, @PathVariable("organisation") final Long organisationId, @RequestParam("financeContact") Long financeContactUserId); @PostMapping(value = "/{projectId}/organisation/{organisationId}/partner-project-location") RestResult<Void> updatePartnerProjectLocation(@PathVariable("projectId") final long projectId, @PathVariable("organisationId") final long organisationId, @RequestBody PostcodeAndTownResource postcodeAndTown); @PostMapping("/{projectId}/invite-finance-contact") RestResult<Void> inviteFinanceContact(@PathVariable("projectId") final Long projectId, @RequestBody @Valid final ProjectUserInviteResource inviteResource); @PostMapping("/{projectId}/invite-project-manager") RestResult<Void> inviteProjectManager(@PathVariable("projectId") final Long projectId, @RequestBody @Valid final ProjectUserInviteResource inviteResource); }
@Test public void setProjectManager() throws Exception { when(projectDetailsService.setProjectManager(3L, 5L)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/3/project-manager/5").contentType(APPLICATION_JSON).accept(APPLICATION_JSON)) .andExpect(status().isOk()); verify(projectDetailsService).setProjectManager(3L, 5L); verifyNoMoreInteractions(projectDetailsService); }
ProjectDetailsController { @PostMapping("/{projectId}/duration/{durationInMonths}") public RestResult<Void> updateProjectDuration(@PathVariable("projectId") final long projectId, @PathVariable("durationInMonths") final long durationInMonths) { return projectDetailsService.updateProjectDuration(projectId, durationInMonths).toPostResponse(); } @GetMapping("/{projectId}/project-manager") RestResult<ProjectUserResource> getProjectManager(@PathVariable(value = "projectId") Long projectId); @PostMapping(value="/{id}/project-manager/{projectManagerId}") RestResult<Void> setProjectManager(@PathVariable("id") final Long id, @PathVariable("projectManagerId") final Long projectManagerId); @PostMapping("/{projectId}/startdate") RestResult<Void> updateProjectStartDate(@PathVariable("projectId") final Long projectId, @RequestParam("projectStartDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate projectStartDate); @PostMapping("/{projectId}/duration/{durationInMonths}") RestResult<Void> updateProjectDuration(@PathVariable("projectId") final long projectId, @PathVariable("durationInMonths") final long durationInMonths); @PostMapping("/{projectId}/address") RestResult<Void> updateProjectAddress(@PathVariable("projectId") final Long projectId, @RequestBody AddressResource addressResource); @PostMapping("/{projectId}/organisation/{organisation}/finance-contact") RestResult<Void> updateFinanceContact(@PathVariable("projectId") final Long projectId, @PathVariable("organisation") final Long organisationId, @RequestParam("financeContact") Long financeContactUserId); @PostMapping(value = "/{projectId}/organisation/{organisationId}/partner-project-location") RestResult<Void> updatePartnerProjectLocation(@PathVariable("projectId") final long projectId, @PathVariable("organisationId") final long organisationId, @RequestBody PostcodeAndTownResource postcodeAndTown); @PostMapping("/{projectId}/invite-finance-contact") RestResult<Void> inviteFinanceContact(@PathVariable("projectId") final Long projectId, @RequestBody @Valid final ProjectUserInviteResource inviteResource); @PostMapping("/{projectId}/invite-project-manager") RestResult<Void> inviteProjectManager(@PathVariable("projectId") final Long projectId, @RequestBody @Valid final ProjectUserInviteResource inviteResource); }
@Test public void updateProjectDuration() throws Exception { long projectId = 3L; long durationInMonths = 18L; when(projectDetailsService.updateProjectDuration(projectId, durationInMonths)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/" + projectId + "/duration/" + durationInMonths) .contentType(APPLICATION_JSON) .accept(APPLICATION_JSON)) .andExpect(status().isOk()); verify(projectDetailsService).updateProjectDuration(projectId, durationInMonths); verifyNoMoreInteractions(projectDetailsService); }
ProjectDetailsController { @PostMapping("/{projectId}/organisation/{organisation}/finance-contact") public RestResult<Void> updateFinanceContact(@PathVariable("projectId") final Long projectId, @PathVariable("organisation") final Long organisationId, @RequestParam("financeContact") Long financeContactUserId) { ProjectOrganisationCompositeId composite = new ProjectOrganisationCompositeId(projectId, organisationId); return projectDetailsService.updateFinanceContact(composite, financeContactUserId).toPostResponse(); } @GetMapping("/{projectId}/project-manager") RestResult<ProjectUserResource> getProjectManager(@PathVariable(value = "projectId") Long projectId); @PostMapping(value="/{id}/project-manager/{projectManagerId}") RestResult<Void> setProjectManager(@PathVariable("id") final Long id, @PathVariable("projectManagerId") final Long projectManagerId); @PostMapping("/{projectId}/startdate") RestResult<Void> updateProjectStartDate(@PathVariable("projectId") final Long projectId, @RequestParam("projectStartDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate projectStartDate); @PostMapping("/{projectId}/duration/{durationInMonths}") RestResult<Void> updateProjectDuration(@PathVariable("projectId") final long projectId, @PathVariable("durationInMonths") final long durationInMonths); @PostMapping("/{projectId}/address") RestResult<Void> updateProjectAddress(@PathVariable("projectId") final Long projectId, @RequestBody AddressResource addressResource); @PostMapping("/{projectId}/organisation/{organisation}/finance-contact") RestResult<Void> updateFinanceContact(@PathVariable("projectId") final Long projectId, @PathVariable("organisation") final Long organisationId, @RequestParam("financeContact") Long financeContactUserId); @PostMapping(value = "/{projectId}/organisation/{organisationId}/partner-project-location") RestResult<Void> updatePartnerProjectLocation(@PathVariable("projectId") final long projectId, @PathVariable("organisationId") final long organisationId, @RequestBody PostcodeAndTownResource postcodeAndTown); @PostMapping("/{projectId}/invite-finance-contact") RestResult<Void> inviteFinanceContact(@PathVariable("projectId") final Long projectId, @RequestBody @Valid final ProjectUserInviteResource inviteResource); @PostMapping("/{projectId}/invite-project-manager") RestResult<Void> inviteProjectManager(@PathVariable("projectId") final Long projectId, @RequestBody @Valid final ProjectUserInviteResource inviteResource); }
@Test public void updateFinanceContact() throws Exception { long projectId = 123L; long organisationId = 456L; long financeContactUserId = 789L; when(projectDetailsService.updateFinanceContact(new ProjectOrganisationCompositeId(projectId, organisationId), financeContactUserId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/organisation/{organisationId}/finance-contact?financeContact=789", 123L, 456L)) .andExpect(status().isOk()); verify(projectDetailsService).updateFinanceContact(new ProjectOrganisationCompositeId(projectId, organisationId), financeContactUserId); verifyNoMoreInteractions(projectDetailsService); }
ProjectDetailsController { @PostMapping(value = "/{projectId}/organisation/{organisationId}/partner-project-location") public RestResult<Void> updatePartnerProjectLocation(@PathVariable("projectId") final long projectId, @PathVariable("organisationId") final long organisationId, @RequestBody PostcodeAndTownResource postcodeAndTown) { ProjectOrganisationCompositeId composite = new ProjectOrganisationCompositeId(projectId, organisationId); return projectDetailsService.updatePartnerProjectLocation(composite, postcodeAndTown).toPostResponse(); } @GetMapping("/{projectId}/project-manager") RestResult<ProjectUserResource> getProjectManager(@PathVariable(value = "projectId") Long projectId); @PostMapping(value="/{id}/project-manager/{projectManagerId}") RestResult<Void> setProjectManager(@PathVariable("id") final Long id, @PathVariable("projectManagerId") final Long projectManagerId); @PostMapping("/{projectId}/startdate") RestResult<Void> updateProjectStartDate(@PathVariable("projectId") final Long projectId, @RequestParam("projectStartDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate projectStartDate); @PostMapping("/{projectId}/duration/{durationInMonths}") RestResult<Void> updateProjectDuration(@PathVariable("projectId") final long projectId, @PathVariable("durationInMonths") final long durationInMonths); @PostMapping("/{projectId}/address") RestResult<Void> updateProjectAddress(@PathVariable("projectId") final Long projectId, @RequestBody AddressResource addressResource); @PostMapping("/{projectId}/organisation/{organisation}/finance-contact") RestResult<Void> updateFinanceContact(@PathVariable("projectId") final Long projectId, @PathVariable("organisation") final Long organisationId, @RequestParam("financeContact") Long financeContactUserId); @PostMapping(value = "/{projectId}/organisation/{organisationId}/partner-project-location") RestResult<Void> updatePartnerProjectLocation(@PathVariable("projectId") final long projectId, @PathVariable("organisationId") final long organisationId, @RequestBody PostcodeAndTownResource postcodeAndTown); @PostMapping("/{projectId}/invite-finance-contact") RestResult<Void> inviteFinanceContact(@PathVariable("projectId") final Long projectId, @RequestBody @Valid final ProjectUserInviteResource inviteResource); @PostMapping("/{projectId}/invite-project-manager") RestResult<Void> inviteProjectManager(@PathVariable("projectId") final Long projectId, @RequestBody @Valid final ProjectUserInviteResource inviteResource); }
@Test public void updatePartnerProjectLocation() throws Exception { long projectId = 1L; long organisationId = 2L; PostcodeAndTownResource postcodeAndTown = new PostcodeAndTownResource("TW14 9QG", null); when(projectDetailsService.updatePartnerProjectLocation(new ProjectOrganisationCompositeId(projectId, organisationId), postcodeAndTown)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/organisation/{organisationId}/partner-project-location", projectId, organisationId) .contentType(APPLICATION_JSON) .content(toJson(postcodeAndTown))) .andExpect(status().isOk()); verify(projectDetailsService).updatePartnerProjectLocation(new ProjectOrganisationCompositeId(projectId, organisationId), postcodeAndTown); verifyNoMoreInteractions(projectDetailsService); }
ProjectDetailsController { @PostMapping("/{projectId}/address") public RestResult<Void> updateProjectAddress(@PathVariable("projectId") final Long projectId, @RequestBody AddressResource addressResource) { return projectDetailsService.updateProjectAddress(projectId, addressResource).toPostResponse(); } @GetMapping("/{projectId}/project-manager") RestResult<ProjectUserResource> getProjectManager(@PathVariable(value = "projectId") Long projectId); @PostMapping(value="/{id}/project-manager/{projectManagerId}") RestResult<Void> setProjectManager(@PathVariable("id") final Long id, @PathVariable("projectManagerId") final Long projectManagerId); @PostMapping("/{projectId}/startdate") RestResult<Void> updateProjectStartDate(@PathVariable("projectId") final Long projectId, @RequestParam("projectStartDate") @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate projectStartDate); @PostMapping("/{projectId}/duration/{durationInMonths}") RestResult<Void> updateProjectDuration(@PathVariable("projectId") final long projectId, @PathVariable("durationInMonths") final long durationInMonths); @PostMapping("/{projectId}/address") RestResult<Void> updateProjectAddress(@PathVariable("projectId") final Long projectId, @RequestBody AddressResource addressResource); @PostMapping("/{projectId}/organisation/{organisation}/finance-contact") RestResult<Void> updateFinanceContact(@PathVariable("projectId") final Long projectId, @PathVariable("organisation") final Long organisationId, @RequestParam("financeContact") Long financeContactUserId); @PostMapping(value = "/{projectId}/organisation/{organisationId}/partner-project-location") RestResult<Void> updatePartnerProjectLocation(@PathVariable("projectId") final long projectId, @PathVariable("organisationId") final long organisationId, @RequestBody PostcodeAndTownResource postcodeAndTown); @PostMapping("/{projectId}/invite-finance-contact") RestResult<Void> inviteFinanceContact(@PathVariable("projectId") final Long projectId, @RequestBody @Valid final ProjectUserInviteResource inviteResource); @PostMapping("/{projectId}/invite-project-manager") RestResult<Void> inviteProjectManager(@PathVariable("projectId") final Long projectId, @RequestBody @Valid final ProjectUserInviteResource inviteResource); }
@Test public void updateProjectAddress() throws Exception { long projectId = 456L; AddressResource addressResource = newAddressResource().build(); when(projectDetailsService.updateProjectAddress(projectId, addressResource)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/address", projectId) .contentType(APPLICATION_JSON) .content(toJson(addressResource))) .andExpect(status().isOk()) .andExpect(content().string("")); verify(projectDetailsService).updateProjectAddress(projectId, addressResource); verifyNoMoreInteractions(projectDetailsService); }
ProjectDetailsCompleteAction extends BaseProjectDetailsAction { @Override protected void doExecute(Project project, ProjectUser projectUserFromContext, ProjectDetailsState newState) { activityLogService.recordActivityByProjectId(project.getId(), ActivityType.PROJECT_DETAILS_COMPLETE); } }
@Test public void doExecute() { Project project = newProject().build(); ProjectUser projectUser = newProjectUser().build(); ProjectDetailsState state = ProjectDetailsState.SUBMITTED; projectDetailsCompleteAction.doExecute(project, projectUser, state); verify(activityLogService).recordActivityByProjectId(project.getId(), ActivityType.PROJECT_DETAILS_COMPLETE); }
ProjectDetailsServiceImpl extends AbstractProjectServiceImpl implements ProjectDetailsService { @Override public ServiceResult<ProjectUserResource> getProjectManager(Long projectId) { return find(projectUserRepository.findByProjectIdAndRole(projectId, PROJECT_MANAGER), notFoundError(ProjectUserResource.class, projectId)).andOnSuccessReturn(projectUserMapper::mapToResource); } @Override ServiceResult<ProjectUserResource> getProjectManager(Long projectId); @Override @Transactional ServiceResult<Void> setProjectManager(Long projectId, Long projectManagerUserId); @Override @Transactional ServiceResult<Void> updateProjectStartDate(Long projectId, LocalDate projectStartDate); @Override @Transactional ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths); @Override @Transactional ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId); @Override @Transactional ServiceResult<Void> updatePartnerProjectLocation(ProjectOrganisationCompositeId composite, PostcodeAndTownResource postcodeAndTown); @Override @Transactional ServiceResult<Void> updateProjectAddress(Long projectId, AddressResource address); @Override @Transactional ServiceResult<Void> inviteFinanceContact(Long projectId, ProjectUserInviteResource inviteResource); @Override @Transactional ServiceResult<Void> inviteProjectManager(Long projectId, ProjectUserInviteResource inviteResource); }
@Test public void getProjectManager() { final Long projectId = 123L; final Project project = newProject().withId(projectId).build(); final ProjectUser projectManager = newProjectUser().withProject(project).withRole(PROJECT_MANAGER).build(); final ProjectUserResource projectManagerResource = newProjectUserResource().withProject(projectId).withRoleName(PROJECT_MANAGER.getName()).build(); when(projectUserMapperMock.mapToResource(projectManager)).thenReturn(projectManagerResource); when(projectUserRepositoryMock.findByProjectIdAndRole(projectId, PROJECT_MANAGER)).thenReturn(Optional.of(projectManager)); ServiceResult<ProjectUserResource> foundProjectManager = service.getProjectManager(projectId); assertTrue(foundProjectManager.isSuccess()); assertTrue(foundProjectManager.getSuccess().getRoleName().equals(PROJECT_MANAGER.getName())); assertTrue(foundProjectManager.getSuccess().getProject().equals(projectId)); }
ProjectDetailsServiceImpl extends AbstractProjectServiceImpl implements ProjectDetailsService { @Override @Transactional public ServiceResult<Void> setProjectManager(Long projectId, Long projectManagerUserId) { return getProject(projectId). andOnSuccess(project -> validateGOLGenerated(project, PROJECT_SETUP_PROJECT_MANAGER_CANNOT_BE_UPDATED_IF_GOL_GENERATED)). andOnSuccess(project -> validateProjectManager(project, projectManagerUserId). andOnSuccess(leadPartner -> createOrUpdateProjectManagerForProject(project, leadPartner))); } @Override ServiceResult<ProjectUserResource> getProjectManager(Long projectId); @Override @Transactional ServiceResult<Void> setProjectManager(Long projectId, Long projectManagerUserId); @Override @Transactional ServiceResult<Void> updateProjectStartDate(Long projectId, LocalDate projectStartDate); @Override @Transactional ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths); @Override @Transactional ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId); @Override @Transactional ServiceResult<Void> updatePartnerProjectLocation(ProjectOrganisationCompositeId composite, PostcodeAndTownResource postcodeAndTown); @Override @Transactional ServiceResult<Void> updateProjectAddress(Long projectId, AddressResource address); @Override @Transactional ServiceResult<Void> inviteFinanceContact(Long projectId, ProjectUserInviteResource inviteResource); @Override @Transactional ServiceResult<Void> inviteProjectManager(Long projectId, ProjectUserInviteResource inviteResource); }
@Test public void invalidProjectManagerProvided() { ServiceResult<Void> result = service.setProjectManager(projectId, otherUserId); assertFalse(result.isSuccess()); assertTrue(result.getFailure().is(PROJECT_SETUP_PROJECT_MANAGER_MUST_BE_LEAD_PARTNER)); } @Test public void setProjectManagerWhenGOLAlreadyGenerated() { FileEntry golFile = newFileEntry().withFilesizeBytes(10).withMediaType("application/pdf").build(); Project existingProject = newProject().withId(projectId).withGrantOfferLetter(golFile).build(); assertTrue(existingProject.getProjectUsers().isEmpty()); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.of(existingProject)); ServiceResult<Void> result = service.setProjectManager(projectId, userId); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(PROJECT_SETUP_PROJECT_MANAGER_CANNOT_BE_UPDATED_IF_GOL_GENERATED)); assertTrue(existingProject.getProjectUsers().isEmpty()); } @Test public void validProjectManagerProvided() { ServiceResult<Void> result = service.setProjectManager(projectId, userId); assertTrue(result.isSuccess()); ProjectUser expectedProjectManager = newProjectUser(). withId(). withProject(project). withOrganisation(organisation). withRole(PROJECT_MANAGER). withUser(user). build(); assertEquals(expectedProjectManager, project.getProjectUsers().get(project.getProjectUsers().size() - 1)); } @Test public void validProjectManagerProvidedWithExistingProjectManager() { User differentUser = newUser().build(); Organisation differentOrganisation = newOrganisation().build(); @SuppressWarnings("unused") ProjectUser existingProjectManager = newProjectUser(). withId(456L). withProject(project). withRole(PROJECT_MANAGER). withOrganisation(differentOrganisation). withUser(differentUser). build(); ServiceResult<Void> result = service.setProjectManager(projectId, userId); assertTrue(result.isSuccess()); ProjectUser expectedProjectManager = newProjectUser(). withId(456L). withProject(project). withOrganisation(organisation). withRole(PROJECT_MANAGER). withUser(user). build(); assertEquals(expectedProjectManager, project.getProjectUsers().get(project.getProjectUsers().size() - 1)); }
ProjectDetailsServiceImpl extends AbstractProjectServiceImpl implements ProjectDetailsService { @Override @Transactional public ServiceResult<Void> updateProjectStartDate(Long projectId, LocalDate projectStartDate) { return validateProjectStartDate(projectStartDate). andOnSuccess(() -> validateIfStartDateCanBeChanged(projectId)). andOnSuccess(() -> getProject(projectId)). andOnSuccessReturnVoid(project -> project.setTargetStartDate(projectStartDate)); } @Override ServiceResult<ProjectUserResource> getProjectManager(Long projectId); @Override @Transactional ServiceResult<Void> setProjectManager(Long projectId, Long projectManagerUserId); @Override @Transactional ServiceResult<Void> updateProjectStartDate(Long projectId, LocalDate projectStartDate); @Override @Transactional ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths); @Override @Transactional ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId); @Override @Transactional ServiceResult<Void> updatePartnerProjectLocation(ProjectOrganisationCompositeId composite, PostcodeAndTownResource postcodeAndTown); @Override @Transactional ServiceResult<Void> updateProjectAddress(Long projectId, AddressResource address); @Override @Transactional ServiceResult<Void> inviteFinanceContact(Long projectId, ProjectUserInviteResource inviteResource); @Override @Transactional ServiceResult<Void> inviteProjectManager(Long projectId, ProjectUserInviteResource inviteResource); }
@Test public void updateProjectStartDateButStartDateDoesntBeginOnFirstDayOfMonth() { LocalDate now = LocalDate.now(); LocalDate dateNotOnFirstDayOfMonth = LocalDate.of(now.getYear(), now.getMonthValue(), 2).plusMonths(1); Project existingProject = newProject().build(); assertNull(existingProject.getTargetStartDate()); when(projectRepositoryMock.findById(123L)).thenReturn(Optional.of(existingProject)); ServiceResult<Void> updateResult = service.updateProjectStartDate(123L, dateNotOnFirstDayOfMonth); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(PROJECT_SETUP_DATE_MUST_START_ON_FIRST_DAY_OF_MONTH)); verify(projectRepositoryMock, never()).findById(123L); assertNull(existingProject.getTargetStartDate()); } @Test public void updateProjectStartDateButStartDateNotInFuture() { LocalDate now = LocalDate.now(); LocalDate pastDate = LocalDate.of(now.getYear(), now.getMonthValue(), 1).minusMonths(1); Project existingProject = newProject().build(); assertNull(existingProject.getTargetStartDate()); when(projectRepositoryMock.findById(123L)).thenReturn(Optional.of(existingProject)); ServiceResult<Void> updateResult = service.updateProjectStartDate(123L, pastDate); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(PROJECT_SETUP_DATE_MUST_BE_IN_THE_FUTURE)); verify(projectRepositoryMock, never()).findById(123L); assertNull(existingProject.getTargetStartDate()); } @Test public void updateProjectStartDateWhenSpendProfileHasAlreadyBeenGenerated() { LocalDate now = LocalDate.now(); LocalDate validDate = LocalDate.of(now.getYear(), now.getMonthValue(), 1).plusMonths(1); Project existingProject = newProject().build(); assertNull(existingProject.getTargetStartDate()); List<SpendProfile> spendProfiles = SpendProfileBuilder.newSpendProfile().build(2); when(projectRepositoryMock.findById(123L)).thenReturn(Optional.of(existingProject)); when(spendProfileRepositoryMock.findByProjectId(123L)).thenReturn(spendProfiles); ServiceResult<Void> updateResult = service.updateProjectStartDate(123L, validDate); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(PROJECT_SETUP_START_DATE_CANNOT_BE_CHANGED_ONCE_SPEND_PROFILE_HAS_BEEN_GENERATED)); verify(projectRepositoryMock, never()).findById(123L); verify(spendProfileRepositoryMock).findByProjectId(123L); assertNull(existingProject.getTargetStartDate()); } @Test public void updateProjectStartDateButProjectDoesntExist() { LocalDate now = LocalDate.now(); LocalDate validDate = LocalDate.of(now.getYear(), now.getMonthValue(), 1).plusMonths(1); when(projectRepositoryMock.findById(123L)).thenReturn(Optional.empty()); ServiceResult<Void> updateResult = service.updateProjectStartDate(123L, validDate); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(notFoundError(Project.class, 123L))); } @Test public void updateProjectStartDateSuccess() { LocalDate now = LocalDate.now(); LocalDate validDate = LocalDate.of(now.getYear(), now.getMonthValue(), 1).plusMonths(1); Project existingProject = newProject().build(); assertNull(existingProject.getTargetStartDate()); when(projectRepositoryMock.findById(123L)).thenReturn(Optional.of(existingProject)); ServiceResult<Void> updateResult = service.updateProjectStartDate(123L, validDate); assertTrue(updateResult.isSuccess()); verify(projectRepositoryMock).findById(123L); assertEquals(validDate, existingProject.getTargetStartDate()); }
UserPermissionRules { @PermissionRule(value = "READ_USER_PROFILE", description = "A ifs admin user can read any user's profile") public boolean ifsAdminCanViewAnyUsersProfile(UserProfileResource profileDetails, UserResource user) { return user.hasRole(Role.IFS_ADMINISTRATOR); } @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 ifsAdminCanViewAnyUsersProfile() { allGlobalRoleUsers.forEach(user -> { if (user.equals(ifsAdminUser())) { assertTrue(rules.ifsAdminCanViewAnyUsersProfile(newUserProfileResource().build(), user)); } else { assertFalse(rules.ifsAdminCanViewAnyUsersProfile(newUserProfileResource().build(), user)); } }); }
ProjectDetailsServiceImpl extends AbstractProjectServiceImpl implements ProjectDetailsService { @Override @Transactional public ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths) { return getProject(projectId).andOnSuccess(project -> validateProjectDuration(durationInMonths). andOnSuccess(() -> validateIfProjectDurationCanBeChanged(project)). andOnSuccessReturnVoid(() -> project.setDurationInMonths(durationInMonths))); } @Override ServiceResult<ProjectUserResource> getProjectManager(Long projectId); @Override @Transactional ServiceResult<Void> setProjectManager(Long projectId, Long projectManagerUserId); @Override @Transactional ServiceResult<Void> updateProjectStartDate(Long projectId, LocalDate projectStartDate); @Override @Transactional ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths); @Override @Transactional ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId); @Override @Transactional ServiceResult<Void> updatePartnerProjectLocation(ProjectOrganisationCompositeId composite, PostcodeAndTownResource postcodeAndTown); @Override @Transactional ServiceResult<Void> updateProjectAddress(Long projectId, AddressResource address); @Override @Transactional ServiceResult<Void> inviteFinanceContact(Long projectId, ProjectUserInviteResource inviteResource); @Override @Transactional ServiceResult<Void> inviteProjectManager(Long projectId, ProjectUserInviteResource inviteResource); }
@Test public void updateProjectDurationWhenDurationLessThanAMonth() { long projectId = 123L; ServiceResult<Void> updateResult = service.updateProjectDuration(projectId, 0L); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(PROJECT_SETUP_PROJECT_DURATION_MUST_BE_MINIMUM_ONE_MONTH)); ServiceResult<Void> updateResult2 = service.updateProjectDuration(projectId, -3L); assertTrue(updateResult2.isFailure()); assertTrue(updateResult2.getFailure().is(PROJECT_SETUP_PROJECT_DURATION_MUST_BE_MINIMUM_ONE_MONTH)); } @Test public void updateProjectDurationWhenProjectDoesNotExist() { long projectId = 123L; when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.empty()); ServiceResult<Void> updateResult = service.updateProjectDuration(projectId, 36L); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(notFoundError(Project.class, 123L))); } @Test public void updateProjectDurationWhenSpendProfileAlreadyGenerated() { long projectId = 123L; List<SpendProfile> spendProfiles = SpendProfileBuilder.newSpendProfile().build(2); when(spendProfileRepositoryMock.findByProjectId(projectId)).thenReturn(spendProfiles); ServiceResult<Void> updateResult = service.updateProjectDuration(projectId, 36L); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(PROJECT_SETUP_PROJECT_DURATION_CANNOT_BE_CHANGED_ONCE_SPEND_PROFILE_HAS_BEEN_GENERATED)); } @Test public void updateProjectDurationWhenProjectIsAlreadyWithdrawn() { long projectId = 123L; Project existingProject = newProject().build(); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.of(existingProject)); when(projectWorkflowHandlerMock.getState(existingProject)).thenReturn(WITHDRAWN); ServiceResult<Void> updateResult = service.updateProjectDuration(projectId, 36L); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(GENERAL_FORBIDDEN)); } @Test public void updateProjectDurationSuccess() { long projectId = 123L; long durationInMonths = 36L; Project existingProject = newProject().build(); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.of(existingProject)); ServiceResult<Void> updateResult = service.updateProjectDuration(projectId, durationInMonths); assertTrue(updateResult.isSuccess()); assertEquals(durationInMonths, (long) existingProject.getDurationInMonths()); }
ProjectDetailsServiceImpl extends AbstractProjectServiceImpl implements ProjectDetailsService { @Override @Transactional public ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId) { return getProject(composite.getProjectId()). andOnSuccess(project -> validateGOLGenerated(project, PROJECT_SETUP_FINANCE_CONTACT_CANNOT_BE_UPDATED_IF_GOL_GENERATED)). andOnSuccess(project -> validateProjectOrganisationFinanceContact(project, composite.getOrganisationId(), financeContactUserId). andOnSuccess(projectUser -> createFinanceContactProjectUser(projectUser.getUser(), project, projectUser.getOrganisation()). andOnSuccessReturnVoid(financeContact -> addFinanceContactToProject(project, financeContact)))); } @Override ServiceResult<ProjectUserResource> getProjectManager(Long projectId); @Override @Transactional ServiceResult<Void> setProjectManager(Long projectId, Long projectManagerUserId); @Override @Transactional ServiceResult<Void> updateProjectStartDate(Long projectId, LocalDate projectStartDate); @Override @Transactional ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths); @Override @Transactional ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId); @Override @Transactional ServiceResult<Void> updatePartnerProjectLocation(ProjectOrganisationCompositeId composite, PostcodeAndTownResource postcodeAndTown); @Override @Transactional ServiceResult<Void> updateProjectAddress(Long projectId, AddressResource address); @Override @Transactional ServiceResult<Void> inviteFinanceContact(Long projectId, ProjectUserInviteResource inviteResource); @Override @Transactional ServiceResult<Void> inviteProjectManager(Long projectId, ProjectUserInviteResource inviteResource); }
@Test public void updateFinanceContact() { Project project = newProject().withId(123L).build(); Organisation organisation = newOrganisation().withId(5L).build(); User user = newUser().withId(7L).build(); newProjectUser().withOrganisation(organisation).withUser(user).withProject(project).withRole(PROJECT_PARTNER).build(); when(projectRepositoryMock.findById(123L)).thenReturn(Optional.of(project)); when(projectWorkflowHandlerMock.getState(project)).thenReturn(ProjectState.SETUP); when(organisationRepositoryMock.findById(5L)).thenReturn(Optional.of(organisation)); setLoggedInUser(newUserResource().withId(user.getId()).build()); ServiceResult<Void> updateResult = service.updateFinanceContact(new ProjectOrganisationCompositeId(123L, 5L), 7L); assertTrue(updateResult.isSuccess()); List<ProjectUser> foundFinanceContacts = simpleFilter(project.getProjectUsers(), projectUser -> projectUser.getOrganisation().equals(organisation) && projectUser.getUser().equals(user) && projectUser.getProcess().equals(project) && projectUser.getRole().equals(PROJECT_FINANCE_CONTACT)); assertEquals(1, foundFinanceContacts.size()); } @Test public void updateFinanceContactWhenGOLAlreadyGenerated() { FileEntry golFileEntry = newFileEntry().withFilesizeBytes(10).withMediaType("application/pdf").build(); Project project = newProject() .withId(123L) .withGrantOfferLetter(golFileEntry) .build(); when(projectRepositoryMock.findById(123L)).thenReturn(Optional.of(project)); ServiceResult<Void> updateResult = service.updateFinanceContact(new ProjectOrganisationCompositeId(123L, 5L), 7L); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(PROJECT_SETUP_FINANCE_CONTACT_CANNOT_BE_UPDATED_IF_GOL_GENERATED)); verify(processRoleRepositoryMock, never()).save(isA(ProcessRole.class)); } @Test public void updateFinanceContactButUserIsNotExistingPartner() { Project project = newProject().withId(123L).build(); Organisation organisation = newOrganisation().withId(5L).build(); User user = newUser().withId(7L).build(); newProjectUser().withOrganisation(organisation).withUser(user).withProject(project).withRole(PROJECT_MANAGER).build(); when(projectRepositoryMock.findById(123L)).thenReturn(Optional.of(project)); when(projectWorkflowHandlerMock.getState(project)).thenReturn(ProjectState.SETUP); when(organisationRepositoryMock.findById(5L)).thenReturn(Optional.of(organisation)); ServiceResult<Void> updateResult = service.updateFinanceContact(new ProjectOrganisationCompositeId(123L, 5L), 7L); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(PROJECT_SETUP_FINANCE_CONTACT_MUST_BE_A_PARTNER_ON_THE_PROJECT_FOR_THE_ORGANISATION)); verify(processRoleRepositoryMock, never()).save(isA(ProcessRole.class)); } @Test public void updateFinanceContactWhenNotPresentOnTheProject() { long userIdForUserNotOnProject = 6L; Project existingProject = newProject().withId(123L).build(); Project anotherProject = newProject().withId(9999L).build(); when(projectRepositoryMock.findById(123L)).thenReturn(Optional.of(existingProject)); when(projectWorkflowHandlerMock.getState(existingProject)).thenReturn(ProjectState.SETUP); Organisation organisation = newOrganisation().withId(5L).build(); when(organisationRepositoryMock.findById(5L)).thenReturn(Optional.of(organisation)); User user = newUser().withId(7L).build(); newProjectUser().withOrganisation(organisation).withUser(user).withProject(anotherProject).withRole(PROJECT_PARTNER).build(); ServiceResult<Void> updateResult = service.updateFinanceContact(new ProjectOrganisationCompositeId(123L, 5L), userIdForUserNotOnProject); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(PROJECT_SETUP_FINANCE_CONTACT_MUST_BE_A_USER_ON_THE_PROJECT_FOR_THE_ORGANISATION)); } @Test public void updateFinanceContactAllowedWhenFinanceContactAlreadySet() { User anotherUser = newUser().build(); Project existingProject = newProject().build(); when(projectRepositoryMock.findById(existingProject.getId())).thenReturn(Optional.of(existingProject)); when(projectWorkflowHandlerMock.getState(existingProject)).thenReturn(ProjectState.SETUP); Organisation organisation = newOrganisation().build(); when(organisationRepositoryMock.findById(organisation.getId())).thenReturn(Optional.of(organisation)); newProjectUser(). withOrganisation(organisation). withUser(user, anotherUser). withProject(existingProject). withRole(PROJECT_FINANCE_CONTACT, PROJECT_PARTNER).build(2); setLoggedInUser(newUserResource().withId(user.getId()).build()); ServiceResult<Void> updateResult = service.updateFinanceContact(new ProjectOrganisationCompositeId(existingProject.getId(), organisation.getId()), anotherUser.getId()); assertTrue(updateResult.isSuccess()); List<ProjectUser> organisationFinanceContacts = existingProject.getProjectUsers(pu -> pu.getRole().equals(PROJECT_FINANCE_CONTACT) && pu.getOrganisation().equals(organisation)); assertEquals(1, organisationFinanceContacts.size()); assertEquals(anotherUser, organisationFinanceContacts.get(0).getUser()); }
UserPermissionRules { @PermissionRule(value = "EDIT_INTERNAL_USER", description = "Only an IFS Administrator can edit an internal user") public boolean ifsAdminCanEditInternalUser(final UserResource userToEdit, UserResource user) { return user.hasRole(Role.IFS_ADMINISTRATOR); } @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 ifsAdminCanEditInternalUser() { UserResource userToEdit = UserResourceBuilder.newUserResource().build(); allGlobalRoleUsers.forEach(user -> { if (user.equals(ifsAdminUser())) { assertTrue(rules.ifsAdminCanEditInternalUser(userToEdit, user)); } else { assertFalse(rules.ifsAdminCanEditInternalUser(userToEdit, user)); } }); }
ProjectDetailsServiceImpl extends AbstractProjectServiceImpl implements ProjectDetailsService { @Override @Transactional public ServiceResult<Void> updatePartnerProjectLocation(ProjectOrganisationCompositeId composite, PostcodeAndTownResource postcodeAndTown) { Function<PostcodeAndTownResource, ServiceResult<Void>> validation; ExceptionThrowingFunction<PartnerOrganisation, PartnerOrganisation> settingLocation; Optional<Organisation> organisation = organisationRepository.findById(composite.getOrganisationId()); if (organisation.isPresent() && organisation.get().isInternational()) { validation = ProjectDetailsServiceImpl::validateTown; settingLocation = settingTown(postcodeAndTown); } else { validation = ProjectDetailsServiceImpl::validatePostcode; settingLocation = settingPostcode(postcodeAndTown); } return validation.apply(postcodeAndTown). andOnSuccess(() -> getProject(composite.getProjectId())). andOnSuccess(project -> validateGOLGenerated(project, PROJECT_SETUP_LOCATION_CANNOT_BE_UPDATED_IF_GOL_GENERATED)). andOnSuccess(() -> getPartnerOrganisation(composite.getProjectId(), composite.getOrganisationId())). andOnSuccessReturn(settingLocation) .andOnSuccessReturnVoid(partnerOrganisation -> getCurrentlyLoggedInProjectUser(partnerOrganisation.getProject(), PROJECT_PARTNER) .andOnSuccessReturnVoid((projectUser) -> projectDetailsWorkflowHandler.projectLocationAdded(partnerOrganisation.getProject(), projectUser))); } @Override ServiceResult<ProjectUserResource> getProjectManager(Long projectId); @Override @Transactional ServiceResult<Void> setProjectManager(Long projectId, Long projectManagerUserId); @Override @Transactional ServiceResult<Void> updateProjectStartDate(Long projectId, LocalDate projectStartDate); @Override @Transactional ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths); @Override @Transactional ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId); @Override @Transactional ServiceResult<Void> updatePartnerProjectLocation(ProjectOrganisationCompositeId composite, PostcodeAndTownResource postcodeAndTown); @Override @Transactional ServiceResult<Void> updateProjectAddress(Long projectId, AddressResource address); @Override @Transactional ServiceResult<Void> inviteFinanceContact(Long projectId, ProjectUserInviteResource inviteResource); @Override @Transactional ServiceResult<Void> inviteProjectManager(Long projectId, ProjectUserInviteResource inviteResource); }
@Test public void updatePartnerProjectLocationWhenPostcodeIsNullOrEmpty() { long projectId = 1L; long organisationId = 2L; PostcodeAndTownResource postcodeAndTown = new PostcodeAndTownResource(null, null); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcodeAndTown); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(new Error("validation.field.must.not.be.blank", HttpStatus.BAD_REQUEST))); postcodeAndTown.setPostcode(""); updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcodeAndTown); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(new Error("validation.field.must.not.be.blank", HttpStatus.BAD_REQUEST))); postcodeAndTown.setPostcode(" "); updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcodeAndTown); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(new Error("validation.field.must.not.be.blank", HttpStatus.BAD_REQUEST))); } @Test public void updatePartnerProjectLocationWhenPostcodeEnteredExceedsMaxLength() { long projectId = 1L; long organisationId = 2L; PostcodeAndTownResource postcodeAndTownResource = new PostcodeAndTownResource("SOME LONG POSTCODE", null); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcodeAndTownResource); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(new Error("validation.field.too.many.characters", asList("", MAX_POSTCODE_LENGTH), HttpStatus.BAD_REQUEST))); } @Test public void updatePartnerProjectLocationWhenMonitoringOfficerAssigned() { long projectId = 1L; long organisationId = 2L; PostcodeAndTownResource postcodeAndTown = new PostcodeAndTownResource("TW14 9QG", null); Project existingProject = newProject().withId(projectId).withGrantOfferLetter(newFileEntry().build()).build(); when(projectRepositoryMock.findById(existingProject.getId())).thenReturn(Optional.of(existingProject)); when(monitoringOfficerRepositoryMock.findOneByProjectId(projectId)).thenReturn(new LegacyMonitoringOfficer()); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcodeAndTown); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(PROJECT_SETUP_LOCATION_CANNOT_BE_UPDATED_IF_GOL_GENERATED)); } @Test public void updatePartnerProjectLocationWhenPartnerOrganisationDoesNotExist() { long projectId = 1L; long organisationId = 2L; PostcodeAndTownResource postcodeAndTown = new PostcodeAndTownResource("TW14 9QG", null); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); Project existingProject = newProject().withId(projectId).build(); when(projectRepositoryMock.findById(existingProject.getId())).thenReturn(Optional.of(existingProject)); ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcodeAndTown); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(notFoundError(PartnerOrganisation.class, projectId, organisationId))); } @Test public void updatePartnerProjectLocationEnsureLowerCasePostcodeIsSavedAsUpperCase() { long projectId = 1L; long organisationId = 2L; PostcodeAndTownResource postcodeAndTown = new PostcodeAndTownResource("tw14 9qg", null); PartnerOrganisation partnerOrganisationInDb = new PartnerOrganisation(); Project existingProject = newProject().withId(projectId).build(); when(projectRepositoryMock.findById(existingProject.getId())).thenReturn(Optional.of(existingProject)); when(partnerOrganisationRepositoryMock.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(partnerOrganisationInDb); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcodeAndTown); assertTrue(updateResult.isSuccess()); assertEquals(postcodeAndTown.getPostcode().toUpperCase(), partnerOrganisationInDb.getPostcode()); } @Test public void updatePartnerProjectLocationEnsureWrongCaseInternationalLocationIsSavedWithAppropriateCasing() { long projectId = 1L; long organisationId = 2L; PostcodeAndTownResource postcodeAndTown = new PostcodeAndTownResource(null, "aMsTeRdAm"); PartnerOrganisation partnerOrganisationInDb = new PartnerOrganisation(); Project existingProject = newProject().withId(projectId).build(); when(projectRepositoryMock.findById(existingProject.getId())).thenReturn(Optional.of(existingProject)); when(partnerOrganisationRepositoryMock.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(partnerOrganisationInDb); when(organisationRepositoryMock.findById(organisationId)).thenReturn(Optional.of(newOrganisation().withInternational(true).build())); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcodeAndTown); assertTrue(updateResult.isSuccess()); assertEquals("Amsterdam", partnerOrganisationInDb.getInternationalLocation()); } @Test public void updatePartnerProjectLocationEnsureWrongCaseInternationalLocationIsSavedWithAppropriateCasingForMultipleWords() { long projectId = 1L; long organisationId = 2L; PostcodeAndTownResource postcodeAndTown = new PostcodeAndTownResource(null, "tHe hAgUe"); PartnerOrganisation partnerOrganisationInDb = new PartnerOrganisation(); Project existingProject = newProject().withId(projectId).build(); when(projectRepositoryMock.findById(existingProject.getId())).thenReturn(Optional.of(existingProject)); when(partnerOrganisationRepositoryMock.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(partnerOrganisationInDb); when(organisationRepositoryMock.findById(organisationId)).thenReturn(Optional.of(newOrganisation().withInternational(true).build())); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcodeAndTown); assertTrue(updateResult.isSuccess()); assertEquals("The Hague", partnerOrganisationInDb.getInternationalLocation()); } @Test public void updatePartnerProjectLocationEnsureWrongCaseInternationalLocationIsSavedWithoutExcessiveSpacingForMultipleWords() { long projectId = 1L; long organisationId = 2L; PostcodeAndTownResource postcodeAndTown = new PostcodeAndTownResource(null, "tHe hAgUe"); PartnerOrganisation partnerOrganisationInDb = new PartnerOrganisation(); Project existingProject = newProject().withId(projectId).build(); when(projectRepositoryMock.findById(existingProject.getId())).thenReturn(Optional.of(existingProject)); when(partnerOrganisationRepositoryMock.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(partnerOrganisationInDb); when(organisationRepositoryMock.findById(organisationId)).thenReturn(Optional.of(newOrganisation().withInternational(true).build())); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcodeAndTown); assertTrue(updateResult.isSuccess()); assertEquals("The Hague", partnerOrganisationInDb.getInternationalLocation()); } @Test public void updatePartnerProjectLocationWhenInternationalLocationIsNullOrEmpty() { long projectId = 1L; long organisationId = 2L; when(organisationRepositoryMock.findById(organisationId)).thenReturn(Optional.of(newOrganisation().withInternational(true).build())); PostcodeAndTownResource postcodeAndTown = new PostcodeAndTownResource(null, null); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcodeAndTown); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(new Error("validation.field.must.not.be.blank", HttpStatus.BAD_REQUEST))); postcodeAndTown.setTown(""); updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcodeAndTown); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(new Error("validation.field.must.not.be.blank", HttpStatus.BAD_REQUEST))); postcodeAndTown.setTown(" "); updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcodeAndTown); assertTrue(updateResult.isFailure()); assertTrue(updateResult.getFailure().is(new Error("validation.field.must.not.be.blank", HttpStatus.BAD_REQUEST))); } @Test public void updatePartnerProjectLocationSuccess() { long projectId = 1L; long organisationId = 2L; PostcodeAndTownResource postcodeAndTown = new PostcodeAndTownResource("UB7 8QF", null); PartnerOrganisation partnerOrganisationInDb = new PartnerOrganisation(project, null, true); Project existingProject = newProject().withId(projectId).build(); when(projectRepositoryMock.findById(existingProject.getId())).thenReturn(Optional.of(existingProject)); when(partnerOrganisationRepositoryMock.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(partnerOrganisationInDb); when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user)); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcodeAndTown); assertTrue(updateResult.isSuccess()); assertEquals(postcodeAndTown.getPostcode(), partnerOrganisationInDb.getPostcode()); verify(projectDetailsWorkflowHandlerMock).projectLocationAdded(eq(project), eq(leadPartnerProjectUser)); } @Test public void updatePartnerProjectLocationSuccessForInternational() { long projectId = 1L; long organisationId = 2L; PostcodeAndTownResource postcodeAndTown = new PostcodeAndTownResource(null, "Amsterdam"); PartnerOrganisation partnerOrganisationInDb = new PartnerOrganisation(project, null, true); Project existingProject = newProject().withId(projectId).build(); when(projectRepositoryMock.findById(existingProject.getId())).thenReturn(Optional.of(existingProject)); when(partnerOrganisationRepositoryMock.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(partnerOrganisationInDb); when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user)); when(organisationRepositoryMock.findById(organisationId)).thenReturn(Optional.of(newOrganisation().withInternational(true).build())); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); ServiceResult<Void> updateResult = service.updatePartnerProjectLocation(projectOrganisationCompositeId, postcodeAndTown); assertTrue(updateResult.isSuccess()); assertEquals(postcodeAndTown.getTown(), partnerOrganisationInDb.getInternationalLocation()); verify(projectDetailsWorkflowHandlerMock).projectLocationAdded(eq(project), eq(leadPartnerProjectUser)); }
UserPermissionRules { @PermissionRule(value = "DEACTIVATE", description = "IFS Administrator can deactivate Users") public boolean ifsAdminCanDeactivateUsers(UserResource userToDeactivate, UserResource user) { return user.hasRole(Role.IFS_ADMINISTRATOR); } @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 ifsAdminCanDeactivateUser() { UserResource userToDeactivate = UserResourceBuilder.newUserResource().build(); allGlobalRoleUsers.forEach(user -> { if (user.equals(ifsAdminUser())) { assertTrue(rules.ifsAdminCanDeactivateUsers(userToDeactivate, user)); } else { assertFalse(rules.ifsAdminCanDeactivateUsers(userToDeactivate, user)); } }); } @Test public void ifsAdminCanReactivateUser() { UserResource userToReactivate = UserResourceBuilder.newUserResource().build(); allGlobalRoleUsers.forEach(user -> { if (user.equals(ifsAdminUser())) { assertTrue(rules.ifsAdminCanDeactivateUsers(userToReactivate, user)); } else { assertFalse(rules.ifsAdminCanDeactivateUsers(userToReactivate, user)); } }); }
ProjectDetailsServiceImpl extends AbstractProjectServiceImpl implements ProjectDetailsService { @Override @Transactional public ServiceResult<Void> inviteProjectManager(Long projectId, ProjectUserInviteResource inviteResource) { return getProject(projectId) .andOnSuccess(project -> validateGOLGenerated(project, PROJECT_SETUP_PROJECT_MANAGER_CANNOT_BE_UPDATED_IF_GOL_GENERATED)) .andOnSuccess(() -> inviteContact(projectId, inviteResource, Notifications.INVITE_PROJECT_MANAGER)); } @Override ServiceResult<ProjectUserResource> getProjectManager(Long projectId); @Override @Transactional ServiceResult<Void> setProjectManager(Long projectId, Long projectManagerUserId); @Override @Transactional ServiceResult<Void> updateProjectStartDate(Long projectId, LocalDate projectStartDate); @Override @Transactional ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths); @Override @Transactional ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId); @Override @Transactional ServiceResult<Void> updatePartnerProjectLocation(ProjectOrganisationCompositeId composite, PostcodeAndTownResource postcodeAndTown); @Override @Transactional ServiceResult<Void> updateProjectAddress(Long projectId, AddressResource address); @Override @Transactional ServiceResult<Void> inviteFinanceContact(Long projectId, ProjectUserInviteResource inviteResource); @Override @Transactional ServiceResult<Void> inviteProjectManager(Long projectId, ProjectUserInviteResource inviteResource); }
@Test public void inviteProjectManagerWhenProjectNotInDB() { Long projectId = 1L; ProjectUserInviteResource inviteResource = newProjectUserInviteResource() .withName("Abc Xyz") .withEmail("[email protected]") .withLeadOrganisation(17L) .withOrganisationName("Invite Organisation 1") .withHash("sample/url") .build(); when(projectInviteMapperMock.mapToDomain(inviteResource)).thenReturn(newProjectUserInvite().withEmail("[email protected]").withName("A B").build()); when(projectRepositoryMock.findById(projectId)).thenThrow(new IllegalArgumentException()); ServiceResult<Void> result = null; try { result = service.inviteProjectManager(projectId, inviteResource); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); assertNull(result); verify(notificationService, never()).sendNotificationWithFlush(any(Notification.class), eq(EMAIL)); return; } assertFalse(true); } @Test public void inviteProjectManagerWhenGOLAlreadyGenerated() { Long projectId = 1L; ProjectUserInviteResource inviteResource = newProjectUserInviteResource() .build(); FileEntry golFile = newFileEntry().withFilesizeBytes(10).withMediaType("application/pdf").build(); Project projectInDB = ProjectBuilder.newProject() .withId(projectId) .withGrantOfferLetter(golFile) .build(); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.of(projectInDB)); ServiceResult<Void> result = service.inviteProjectManager(projectId, inviteResource); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(PROJECT_SETUP_PROJECT_MANAGER_CANNOT_BE_UPDATED_IF_GOL_GENERATED)); } @Test public void inviteProjectManagerWhenUnableToSendNotification() { ProjectUserInviteResource inviteResource = newProjectUserInviteResource() .withCompetitionName("Competition 1") .withApplicationId(application.getId()) .withName("Abc Xyz") .withEmail("[email protected]") .withLeadOrganisation(organisation.getId()) .withOrganisationName("Invite Organisation 1") .withHash("sample/url") .build(); Project projectInDB = ProjectBuilder.newProject() .withName("Project 1") .withApplication(application) .build(); when(projectRepositoryMock.findById(projectInDB.getId())).thenReturn(Optional.of(projectInDB)); NotificationTarget to = new UserNotificationTarget("A B", "[email protected]"); Map<String, Object> globalArguments = new HashMap<>(); globalArguments.put("projectName", projectInDB.getName()); globalArguments.put("competitionName", "Competition 1"); globalArguments.put("leadOrganisation", organisation.getName()); globalArguments.put("applicationId", application.getId()); globalArguments.put("inviteOrganisationName", "Invite Organisation 1"); globalArguments.put("inviteUrl", webBaseUrl + "/project-setup/accept-invite/" + inviteResource.getHash()); globalArguments.put("procurement", false); Notification notification = new Notification(systemNotificationSource, to, ProjectDetailsServiceImpl.Notifications.INVITE_PROJECT_MANAGER, globalArguments); when(notificationService.sendNotificationWithFlush(notification, EMAIL)).thenReturn( serviceFailure(new Error(NOTIFICATIONS_UNABLE_TO_SEND_MULTIPLE))); ProjectUserInvite projectInvite = newProjectUserInvite() .withEmail("[email protected]") .withName("A B") .build(); when(projectInviteMapperMock.mapToDomain(inviteResource)).thenReturn(projectInvite); ServiceResult<Void> result = service.inviteProjectManager(projectInDB.getId(), inviteResource); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(NOTIFICATIONS_UNABLE_TO_SEND_MULTIPLE)); verify(projectUserInviteRepositoryMock).save(projectInvite); } @Test public void inviteProjectManagerSuccess() { ProjectUserInviteResource inviteResource = newProjectUserInviteResource() .withCompetitionName("Competition 1") .withApplicationId(application.getId()) .withName("Abc Xyz") .withEmail("[email protected]") .withLeadOrganisation(organisation.getId()) .withOrganisationName("Invite Organisation 1") .withHash("sample/url") .build(); Project projectInDB = ProjectBuilder.newProject() .withName("Project 1") .withApplication(application) .build(); when(projectRepositoryMock.findById(projectInDB.getId())).thenReturn(Optional.of(projectInDB)); NotificationTarget to = new UserNotificationTarget("A B", "[email protected]"); Map<String, Object> globalArguments = new HashMap<>(); globalArguments.put("projectName", projectInDB.getName()); globalArguments.put("competitionName", "Competition 1"); globalArguments.put("leadOrganisation", organisation.getName()); globalArguments.put("applicationId", application.getId()); globalArguments.put("inviteOrganisationName", "Invite Organisation 1"); globalArguments.put("inviteUrl", webBaseUrl + "/project-setup/accept-invite/" + inviteResource.getHash()); globalArguments.put("procurement", false); Notification notification = new Notification(systemNotificationSource, to, ProjectDetailsServiceImpl.Notifications.INVITE_PROJECT_MANAGER, globalArguments); when(notificationService.sendNotificationWithFlush(notification, EMAIL)).thenReturn(serviceSuccess()); ProjectUserInvite projectInvite = newProjectUserInvite(). withEmail("[email protected]"). withName("A B"). build(); when(projectInviteMapperMock.mapToDomain(inviteResource)).thenReturn(projectInvite); ServiceResult<Void> result = service.inviteProjectManager(projectInDB.getId(), inviteResource); assertTrue(result.isSuccess()); verify(notificationService).sendNotificationWithFlush(notification, EMAIL); verify(projectUserInviteRepositoryMock).save(projectInvite); }
ProjectDetailsServiceImpl extends AbstractProjectServiceImpl implements ProjectDetailsService { @Override @Transactional public ServiceResult<Void> inviteFinanceContact(Long projectId, ProjectUserInviteResource inviteResource) { return getProject(projectId) .andOnSuccess(project -> validateGOLGenerated(project, PROJECT_SETUP_FINANCE_CONTACT_CANNOT_BE_UPDATED_IF_GOL_GENERATED)) .andOnSuccess(() -> inviteContact(projectId, inviteResource, Notifications.INVITE_FINANCE_CONTACT)); } @Override ServiceResult<ProjectUserResource> getProjectManager(Long projectId); @Override @Transactional ServiceResult<Void> setProjectManager(Long projectId, Long projectManagerUserId); @Override @Transactional ServiceResult<Void> updateProjectStartDate(Long projectId, LocalDate projectStartDate); @Override @Transactional ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths); @Override @Transactional ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId); @Override @Transactional ServiceResult<Void> updatePartnerProjectLocation(ProjectOrganisationCompositeId composite, PostcodeAndTownResource postcodeAndTown); @Override @Transactional ServiceResult<Void> updateProjectAddress(Long projectId, AddressResource address); @Override @Transactional ServiceResult<Void> inviteFinanceContact(Long projectId, ProjectUserInviteResource inviteResource); @Override @Transactional ServiceResult<Void> inviteProjectManager(Long projectId, ProjectUserInviteResource inviteResource); }
@Test public void inviteFinanceContactWhenGOLAlreadyGenerated() { Long projectId = 1L; ProjectUserInviteResource inviteResource = newProjectUserInviteResource() .withName("Abc Xyz") .withEmail("[email protected]") .withLeadOrganisation(17L) .withOrganisationName("Invite Organisation 1") .withHash("sample/url") .build(); FileEntry golFileEntry = newFileEntry().withFilesizeBytes(10).withMediaType("application/pdf").build(); Project projectInDB = ProjectBuilder.newProject() .withId(projectId) .withGrantOfferLetter(golFileEntry) .build(); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.of(projectInDB)); ServiceResult<Void> result = service.inviteFinanceContact(projectId, inviteResource); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(PROJECT_SETUP_FINANCE_CONTACT_CANNOT_BE_UPDATED_IF_GOL_GENERATED)); } @Test public void inviteFinanceContactSuccess() { ProjectUserInviteResource inviteResource = newProjectUserInviteResource() .withCompetitionName("Competition 1") .withApplicationId(application.getId()) .withName("Abc Xyz") .withEmail("[email protected]") .withLeadOrganisation(organisation.getId()) .withOrganisationName("Invite Organisation 1") .withHash("sample/url") .build(); Project projectInDB = ProjectBuilder.newProject() .withName("Project 1") .withApplication(application) .build(); NotificationTarget to = new UserNotificationTarget("A B", "[email protected]"); when(projectRepositoryMock.findById(projectInDB.getId())).thenReturn(Optional.of(projectInDB)); Map<String, Object> globalArguments = new HashMap<>(); globalArguments.put("projectName", projectInDB.getName()); globalArguments.put("competitionName", "Competition 1"); globalArguments.put("leadOrganisation", organisation.getName()); globalArguments.put("applicationId", application.getId()); globalArguments.put("inviteOrganisationName", "Invite Organisation 1"); globalArguments.put("inviteUrl", webBaseUrl + "/project-setup/accept-invite/" + inviteResource.getHash()); globalArguments.put("procurement", false); Notification notification = new Notification(systemNotificationSource, to, ProjectDetailsServiceImpl.Notifications.INVITE_FINANCE_CONTACT, globalArguments); when(notificationService.sendNotificationWithFlush(notification, EMAIL)).thenReturn(serviceSuccess()); ProjectUserInvite projectInvite = newProjectUserInvite() .withName("A B") .withEmail("[email protected]") .build(); when(projectInviteMapperMock.mapToDomain(inviteResource)).thenReturn(projectInvite); ServiceResult<Void> result = service.inviteFinanceContact(projectInDB.getId(), inviteResource); assertTrue(result.isSuccess()); verify(notificationService).sendNotificationWithFlush(notification, EMAIL); verify(projectUserInviteRepositoryMock).save(projectInvite); } @Test public void inviteProjectFinanceUser(){ ProjectUserInviteResource inviteResource = newProjectUserInviteResource() .withCompetitionName("Competition 1") .withApplicationId(application.getId()) .withName("Abc Xyz") .withEmail("[email protected]") .withLeadOrganisation(organisation.getId()) .withOrganisationName("Invite Organisation 1") .withHash("sample/url") .build(); ProcessRole[] roles = newProcessRole() .withOrganisationId(organisation.getId()) .withRole(Role.LEADAPPLICANT) .build(1) .toArray(new ProcessRole[0]); Application a = newApplication() .withProcessRoles(roles) .withCompetition(newCompetition().build()) .build(); Project projectInDB = ProjectBuilder.newProject() .withName("Project 1") .withApplication(a) .build(); when(organisationRepositoryMock.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(projectRepositoryMock.findById(projectInDB.getId())).thenReturn(Optional.of(projectInDB)); NotificationTarget to = new UserNotificationTarget("A B", "[email protected]"); Map<String, Object> globalArguments = new HashMap<>(); globalArguments.put("projectName", projectInDB.getName()); globalArguments.put("competitionName", "Competition 1"); globalArguments.put("leadOrganisation", organisation.getName()); globalArguments.put("applicationId", application.getId()); globalArguments.put("inviteOrganisationName", "Invite Organisation 1"); globalArguments.put("inviteUrl", webBaseUrl + "/project-setup/accept-invite/" + inviteResource.getHash()); globalArguments.put("procurement", false); Notification notification = new Notification(systemNotificationSource, to, ProjectDetailsServiceImpl.Notifications.INVITE_FINANCE_CONTACT, globalArguments); when(notificationService.sendNotificationWithFlush(notification, EMAIL)).thenReturn(serviceSuccess()); ProjectUserInvite projectInvite = newProjectUserInvite() .withEmail("[email protected]") .withName("A B") .build(); when(projectInviteMapperMock.mapToDomain(inviteResource)).thenReturn(projectInvite); ServiceResult<Void> success = service.inviteFinanceContact(projectInDB.getId(), inviteResource); assertTrue(success.isSuccess()); verify(notificationService).sendNotificationWithFlush(notification, EMAIL); verify(projectUserInviteRepositoryMock).save(projectInvite); verify(projectInviteMapperMock).mapToDomain(inviteResource); }
ProjectDetailsServiceImpl extends AbstractProjectServiceImpl implements ProjectDetailsService { @Override @Transactional public ServiceResult<Void> updateProjectAddress(Long projectId, AddressResource address) { return getProject(projectId). andOnSuccess(project -> validateGOLGenerated(project, PROJECT_SETUP_PROJECT_ADDRESS_CANNOT_BE_UPDATED_IF_GOL_GENERATED)). andOnSuccess(() -> find(getProject(projectId)). andOnSuccess(project -> { if (project.getAddress() != null) { project.getAddress().copyFrom(address); } else { project.setAddress(addressRepository.save(addressMapper.mapToDomain(address))); } return getCurrentlyLoggedInPartner(project).andOnSuccess(user -> { projectDetailsWorkflowHandler.projectAddressAdded(project, user); return serviceSuccess(); }); }) ); } @Override ServiceResult<ProjectUserResource> getProjectManager(Long projectId); @Override @Transactional ServiceResult<Void> setProjectManager(Long projectId, Long projectManagerUserId); @Override @Transactional ServiceResult<Void> updateProjectStartDate(Long projectId, LocalDate projectStartDate); @Override @Transactional ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths); @Override @Transactional ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId); @Override @Transactional ServiceResult<Void> updatePartnerProjectLocation(ProjectOrganisationCompositeId composite, PostcodeAndTownResource postcodeAndTown); @Override @Transactional ServiceResult<Void> updateProjectAddress(Long projectId, AddressResource address); @Override @Transactional ServiceResult<Void> inviteFinanceContact(Long projectId, ProjectUserInviteResource inviteResource); @Override @Transactional ServiceResult<Void> inviteProjectManager(Long projectId, ProjectUserInviteResource inviteResource); }
@Test public void updateProjectAddressToNewProjectAddress() { AddressResource newAddressResource = newAddressResource().build(); Address newAddress = newAddress() .build(); project.setAddress(null); when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user)); when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project)); when(organisationRepositoryMock.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(addressMapperMock.mapToDomain(newAddressResource)).thenReturn(newAddress); when(addressRepositoryMock.save(newAddress)).thenReturn(newAddress); when(projectDetailsWorkflowHandlerMock.projectAddressAdded(project, leadPartnerProjectUser)).thenReturn(true); setLoggedInUser(newUserResource().withId(user.getId()).build()); assertNull(project.getAddress()); ServiceResult<Void> result = service.updateProjectAddress(project.getId(), newAddressResource); assertTrue(result.isSuccess()); assertEquals(newAddress, project.getAddress()); } @Test public void updateProjectAddressToExistingAddress() { AddressResource newAddressResource = newAddressResource().withAddressLine1("new").build(); Address existingAddress = newAddress().withAddressLine1("old").build(); project.setAddress(existingAddress); when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user)); when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project)); when(organisationRepositoryMock.findById(organisation.getId())).thenReturn(Optional.of(organisation)); when(projectDetailsWorkflowHandlerMock.projectAddressAdded(project, leadPartnerProjectUser)).thenReturn(true); setLoggedInUser(newUserResource().withId(user.getId()).build()); ServiceResult<Void> result = service.updateProjectAddress(project.getId(), newAddressResource); assertTrue(result.isSuccess()); assertEquals(existingAddress, project.getAddress()); assertEquals(existingAddress.getAddressLine1(), "new"); }
UserPermissionRules { @PermissionRule(value = "DEACTIVATE", description = "System Maintenance can deactivate Users") public boolean systemMaintenanceUserCanDeactivateUsers(UserResource userToDeactivate, UserResource user) { return isSystemMaintenanceUser(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 systemMaintenanceUserCanDeactivateUser() { UserResource userToDeactivate = UserResourceBuilder.newUserResource().build(); allGlobalRoleUsers.forEach(user -> { if (user.equals(systemMaintenanceUser())) { assertTrue(rules.systemMaintenanceUserCanDeactivateUsers(userToDeactivate, user)); } else { assertFalse(rules.systemMaintenanceUserCanDeactivateUsers(userToDeactivate, user)); } }); }
DocumentPermissionRules extends BasePermissionRules { @PermissionRule(value = "UPLOAD_DOCUMENT", description = "Project Manager can upload document for their project") public boolean projectManagerCanUploadDocument(ProjectResource project, UserResource user) { return isProjectManager(project.getId(), user.getId()); } @PermissionRule(value = "UPLOAD_DOCUMENT", description = "Project Manager can upload document for their project") boolean projectManagerCanUploadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Partner can download document") boolean partnersCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Internal user can download document") boolean internalUserCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Monitoring officer can download document") boolean monitoringOfficerCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Stakeholder can download document") boolean stakeholderCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DELETE_DOCUMENT", description = "Project Manager can delete document for their project") boolean projectManagerCanDeleteDocument(ProjectResource project, UserResource user); @PermissionRule(value = "SUBMIT_DOCUMENT", description = "Project Manager can submit document") boolean projectManagerCanSubmitDocument(ProjectResource project, UserResource user); @PermissionRule(value = "REVIEW_DOCUMENT", description = "Comp admin, project finance and IFS admin users can approve or reject document") boolean internalAdminCanApproveDocument(ProjectResource project, UserResource user); }
@Test public void projectManagerCanUploadDocument() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); setUpUserAsProjectManager(project, user); assertTrue(rules.projectManagerCanUploadDocument(project, user)); } @Test public void nonProjectManagerCannotUploadDocument() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); setUpUserNotAsProjectManager(user); assertFalse(rules.projectManagerCanUploadDocument(project, user)); }
DocumentPermissionRules extends BasePermissionRules { @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Partner can download document") public boolean partnersCanDownloadDocument(ProjectResource project, UserResource user) { return isPartner(project.getId(), user.getId()); } @PermissionRule(value = "UPLOAD_DOCUMENT", description = "Project Manager can upload document for their project") boolean projectManagerCanUploadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Partner can download document") boolean partnersCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Internal user can download document") boolean internalUserCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Monitoring officer can download document") boolean monitoringOfficerCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Stakeholder can download document") boolean stakeholderCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DELETE_DOCUMENT", description = "Project Manager can delete document for their project") boolean projectManagerCanDeleteDocument(ProjectResource project, UserResource user); @PermissionRule(value = "SUBMIT_DOCUMENT", description = "Project Manager can submit document") boolean projectManagerCanSubmitDocument(ProjectResource project, UserResource user); @PermissionRule(value = "REVIEW_DOCUMENT", description = "Comp admin, project finance and IFS admin users can approve or reject document") boolean internalAdminCanApproveDocument(ProjectResource project, UserResource user); }
@Test public void partnersCanDownloadDocument() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); setupUserAsPartner(project, user); assertTrue(rules.partnersCanDownloadDocument(project, user)); } @Test public void nonPartnersCannotDownloadDocument() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); setupUserNotAsPartner(project, user); assertFalse(rules.partnersCanDownloadDocument(project, user)); }
DocumentPermissionRules extends BasePermissionRules { @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Internal user can download document") public boolean internalUserCanDownloadDocument(ProjectResource project, UserResource user) { return isInternal(user); } @PermissionRule(value = "UPLOAD_DOCUMENT", description = "Project Manager can upload document for their project") boolean projectManagerCanUploadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Partner can download document") boolean partnersCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Internal user can download document") boolean internalUserCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Monitoring officer can download document") boolean monitoringOfficerCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Stakeholder can download document") boolean stakeholderCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DELETE_DOCUMENT", description = "Project Manager can delete document for their project") boolean projectManagerCanDeleteDocument(ProjectResource project, UserResource user); @PermissionRule(value = "SUBMIT_DOCUMENT", description = "Project Manager can submit document") boolean projectManagerCanSubmitDocument(ProjectResource project, UserResource user); @PermissionRule(value = "REVIEW_DOCUMENT", description = "Comp admin, project finance and IFS admin users can approve or reject document") boolean internalAdminCanApproveDocument(ProjectResource project, UserResource user); }
@Test public void internalUserCanDownloadDocument() { ProjectResource project = newProjectResource().build(); allGlobalRoleUsers.forEach(user -> { if (isInternal(user)) { assertTrue(rules.internalUserCanDownloadDocument(project, user)); } else { assertFalse(rules.internalUserCanDownloadDocument(project, user)); } }); }
DocumentPermissionRules extends BasePermissionRules { @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Stakeholder can download document") public boolean stakeholderCanDownloadDocument(ProjectResource project, UserResource user) { return userIsStakeholderOnProject(project, user) && areDocumentsApproved(project); } @PermissionRule(value = "UPLOAD_DOCUMENT", description = "Project Manager can upload document for their project") boolean projectManagerCanUploadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Partner can download document") boolean partnersCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Internal user can download document") boolean internalUserCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Monitoring officer can download document") boolean monitoringOfficerCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Stakeholder can download document") boolean stakeholderCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DELETE_DOCUMENT", description = "Project Manager can delete document for their project") boolean projectManagerCanDeleteDocument(ProjectResource project, UserResource user); @PermissionRule(value = "SUBMIT_DOCUMENT", description = "Project Manager can submit document") boolean projectManagerCanSubmitDocument(ProjectResource project, UserResource user); @PermissionRule(value = "REVIEW_DOCUMENT", description = "Comp admin, project finance and IFS admin users can approve or reject document") boolean internalAdminCanApproveDocument(ProjectResource project, UserResource user); }
@Test public void stakeholderCanDownloadDocument() { long projectId = 100L; Competition competition = newCompetition() .withId(1L) .build(); List<ProjectDocumentResource> projectDocuments = newProjectDocumentResource() .withStatus(DocumentStatus.APPROVED) .build(1); ProjectResource projectResource = newProjectResource() .withId(projectId) .withProjectDocuments(projectDocuments) .build(); Application application = newApplication() .withId(1L) .withCompetition(competition) .withName("Application Name") .build(); Project project = newProject() .withId(projectId) .withApplication(application) .build(); UserResource user = newUserResource() .withRoleGlobal(STAKEHOLDER).build(); when(projectRepository.findById(project.getId())).thenReturn(Optional.of(project)); when(stakeholderRepository.existsByCompetitionIdAndUserId(competition.getId(), user.getId())).thenReturn(true); assertTrue(rules.stakeholderCanDownloadDocument(projectResource, user)); } @Test public void stakeholderCannotDownloadDocument() { long projectId = 100L; Competition competition = newCompetition() .withId(1L) .build(); List<ProjectDocumentResource> projectDocuments = newProjectDocumentResource() .withStatus(DocumentStatus.UNSET) .build(1); ProjectResource projectResource = newProjectResource() .withId(projectId) .withProjectDocuments(projectDocuments) .build(); Application application = newApplication() .withId(1L) .withCompetition(competition) .withName("Application Name") .build(); Project project = newProject() .withId(projectId) .withApplication(application) .build(); UserResource user = newUserResource() .withRoleGlobal(STAKEHOLDER).build(); when(projectRepository.findById(project.getId())).thenReturn(Optional.of(project)); when(stakeholderRepository.existsByCompetitionIdAndUserId(competition.getId(), user.getId())).thenReturn(false); assertFalse(rules.stakeholderCanDownloadDocument(projectResource, user)); }
DocumentPermissionRules extends BasePermissionRules { @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Monitoring officer can download document") public boolean monitoringOfficerCanDownloadDocument(ProjectResource project, UserResource user) { return isMonitoringOfficer(project.getId(), user.getId()); } @PermissionRule(value = "UPLOAD_DOCUMENT", description = "Project Manager can upload document for their project") boolean projectManagerCanUploadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Partner can download document") boolean partnersCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Internal user can download document") boolean internalUserCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Monitoring officer can download document") boolean monitoringOfficerCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Stakeholder can download document") boolean stakeholderCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DELETE_DOCUMENT", description = "Project Manager can delete document for their project") boolean projectManagerCanDeleteDocument(ProjectResource project, UserResource user); @PermissionRule(value = "SUBMIT_DOCUMENT", description = "Project Manager can submit document") boolean projectManagerCanSubmitDocument(ProjectResource project, UserResource user); @PermissionRule(value = "REVIEW_DOCUMENT", description = "Comp admin, project finance and IFS admin users can approve or reject document") boolean internalAdminCanApproveDocument(ProjectResource project, UserResource user); }
@Test public void monitoringOfficerCanDownloadDocument() { ProjectResource project = newProjectResource().build(); setupMonitoringOfficerExpectations(project, monitoringOfficerUser(), true); allGlobalRoleUsers.forEach(user -> { if (isMonitoringOfficer(user)) { assertTrue(rules.monitoringOfficerCanDownloadDocument(project, monitoringOfficerUser())); } else { assertFalse(rules.monitoringOfficerCanDownloadDocument(project, user)); } }); }
DocumentPermissionRules extends BasePermissionRules { @PermissionRule(value = "DELETE_DOCUMENT", description = "Project Manager can delete document for their project") public boolean projectManagerCanDeleteDocument(ProjectResource project, UserResource user) { return isProjectManager(project.getId(), user.getId()); } @PermissionRule(value = "UPLOAD_DOCUMENT", description = "Project Manager can upload document for their project") boolean projectManagerCanUploadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Partner can download document") boolean partnersCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Internal user can download document") boolean internalUserCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Monitoring officer can download document") boolean monitoringOfficerCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Stakeholder can download document") boolean stakeholderCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DELETE_DOCUMENT", description = "Project Manager can delete document for their project") boolean projectManagerCanDeleteDocument(ProjectResource project, UserResource user); @PermissionRule(value = "SUBMIT_DOCUMENT", description = "Project Manager can submit document") boolean projectManagerCanSubmitDocument(ProjectResource project, UserResource user); @PermissionRule(value = "REVIEW_DOCUMENT", description = "Comp admin, project finance and IFS admin users can approve or reject document") boolean internalAdminCanApproveDocument(ProjectResource project, UserResource user); }
@Test public void projectManagerCanDeleteDocument() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); setUpUserAsProjectManager(project, user); assertTrue(rules.projectManagerCanDeleteDocument(project, user)); } @Test public void nonProjectManagerCannotDeleteDocument() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); setUpUserNotAsProjectManager(user); assertFalse(rules.projectManagerCanDeleteDocument(project, user)); }
DocumentPermissionRules extends BasePermissionRules { @PermissionRule(value = "SUBMIT_DOCUMENT", description = "Project Manager can submit document") public boolean projectManagerCanSubmitDocument(ProjectResource project, UserResource user) { return isProjectManager(project.getId(), user.getId()); } @PermissionRule(value = "UPLOAD_DOCUMENT", description = "Project Manager can upload document for their project") boolean projectManagerCanUploadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Partner can download document") boolean partnersCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Internal user can download document") boolean internalUserCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Monitoring officer can download document") boolean monitoringOfficerCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Stakeholder can download document") boolean stakeholderCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DELETE_DOCUMENT", description = "Project Manager can delete document for their project") boolean projectManagerCanDeleteDocument(ProjectResource project, UserResource user); @PermissionRule(value = "SUBMIT_DOCUMENT", description = "Project Manager can submit document") boolean projectManagerCanSubmitDocument(ProjectResource project, UserResource user); @PermissionRule(value = "REVIEW_DOCUMENT", description = "Comp admin, project finance and IFS admin users can approve or reject document") boolean internalAdminCanApproveDocument(ProjectResource project, UserResource user); }
@Test public void projectManagerCanSubmitDocument() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); setUpUserAsProjectManager(project, user); assertTrue(rules.projectManagerCanSubmitDocument(project, user)); } @Test public void nonProjectManagerCannotSubmitDocument() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); setUpUserNotAsProjectManager(user); assertFalse(rules.projectManagerCanSubmitDocument(project, user)); }
DocumentPermissionRules extends BasePermissionRules { @PermissionRule(value = "REVIEW_DOCUMENT", description = "Comp admin, project finance and IFS admin users can approve or reject document") public boolean internalAdminCanApproveDocument(ProjectResource project, UserResource user) { return isInternalAdmin(user) || isIFSAdmin(user); } @PermissionRule(value = "UPLOAD_DOCUMENT", description = "Project Manager can upload document for their project") boolean projectManagerCanUploadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Partner can download document") boolean partnersCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Internal user can download document") boolean internalUserCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Monitoring officer can download document") boolean monitoringOfficerCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DOWNLOAD_DOCUMENT", description = "Stakeholder can download document") boolean stakeholderCanDownloadDocument(ProjectResource project, UserResource user); @PermissionRule(value = "DELETE_DOCUMENT", description = "Project Manager can delete document for their project") boolean projectManagerCanDeleteDocument(ProjectResource project, UserResource user); @PermissionRule(value = "SUBMIT_DOCUMENT", description = "Project Manager can submit document") boolean projectManagerCanSubmitDocument(ProjectResource project, UserResource user); @PermissionRule(value = "REVIEW_DOCUMENT", description = "Comp admin, project finance and IFS admin users can approve or reject document") boolean internalAdminCanApproveDocument(ProjectResource project, UserResource user); }
@Test public void internalAdminCanApproveDocument() { ProjectResource project = newProjectResource().build(); allGlobalRoleUsers.forEach(user -> { if (SecurityRuleUtil.isInternalAdmin(user) || SecurityRuleUtil.isIFSAdmin(user)) { assertTrue(rules.internalAdminCanApproveDocument(project, user)); } else { assertFalse(rules.internalAdminCanApproveDocument(project, user)); } }); }
DocumentsController { @PostMapping(value = "/config/{documentConfigId}/upload", produces = "application/json") public RestResult<FileEntryResource> uploadDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam(value = "filename", required = false) String originalFilename, HttpServletRequest request) { List<String> validMediaTypesForDocument = documentsService.getValidMediaTypesForDocument(documentConfigId).getSuccess(); return fileControllerUtils.handleFileUpload(contentType, contentLength, originalFilename, fileValidator, validMediaTypesForDocument, maxFileSizeBytesForProjectSetupDocuments, request, (fileAttributes, inputStreamSupplier) -> documentsService.createDocumentFileEntry(projectId, documentConfigId, fileAttributes.toFileEntryResource(), inputStreamSupplier)); } DocumentsController(); @PostMapping(value = "/config/{documentConfigId}/upload", produces = "application/json") RestResult<FileEntryResource> uploadDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam(value = "filename", required = false) String originalFilename, HttpServletRequest request); @GetMapping("/config/{documentConfigId}/file-contents") @ResponseBody ResponseEntity<Object> getFileContents(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @GetMapping(value = "/config/{documentConfigId}/file-entry-details", produces = "application/json") RestResult<FileEntryResource> getFileEntryDetails(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @DeleteMapping(value = "/config/{documentConfigId}/delete", produces = "application/json") RestResult<Void> deleteDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @PostMapping("/config/{documentConfigId}/submit") RestResult<Void> submitDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @PostMapping("/config/{documentConfigId}/decision") RestResult<Void> documentDecision(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @RequestBody final ProjectDocumentDecision decision); }
@Test public void uploadDocument() throws Exception { when(documentsServiceMock.getValidMediaTypesForDocument(documentConfigId)).thenReturn(serviceSuccess(mediaTypes)); BiFunction<DocumentsService, FileEntryResource, ServiceResult<FileEntryResource>> serviceCallToUpload = (service, fileToUpload) -> service.createDocumentFileEntry(eq(projectId), eq(documentConfigId), eq(fileToUpload), fileUploadInputStreamExpectations()); assertFileUploadProcess("/project/" + projectId + "/document/config/" + documentConfigId + "/upload", fileValidatorMock, mediaTypes, documentsServiceMock, serviceCallToUpload); }
DocumentsController { @GetMapping("/config/{documentConfigId}/file-contents") @ResponseBody public ResponseEntity<Object> getFileContents(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId) throws IOException { return fileControllerUtils.handleFileDownload(() -> documentsService.getFileContents(projectId, documentConfigId)); } DocumentsController(); @PostMapping(value = "/config/{documentConfigId}/upload", produces = "application/json") RestResult<FileEntryResource> uploadDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam(value = "filename", required = false) String originalFilename, HttpServletRequest request); @GetMapping("/config/{documentConfigId}/file-contents") @ResponseBody ResponseEntity<Object> getFileContents(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @GetMapping(value = "/config/{documentConfigId}/file-entry-details", produces = "application/json") RestResult<FileEntryResource> getFileEntryDetails(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @DeleteMapping(value = "/config/{documentConfigId}/delete", produces = "application/json") RestResult<Void> deleteDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @PostMapping("/config/{documentConfigId}/submit") RestResult<Void> submitDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @PostMapping("/config/{documentConfigId}/decision") RestResult<Void> documentDecision(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @RequestBody final ProjectDocumentDecision decision); }
@Test public void getFileContents() throws Exception { Function<DocumentsService, ServiceResult<FileAndContents>> serviceCallToUpload = (service) -> service.getFileContents(projectId, documentConfigId); assertGetFileContents("/project/" + projectId + "/document/config/" + documentConfigId + "/file-contents", new Object[] {}, emptyMap(), documentsServiceMock, serviceCallToUpload); }
DocumentsController { @GetMapping(value = "/config/{documentConfigId}/file-entry-details", produces = "application/json") public RestResult<FileEntryResource> getFileEntryDetails(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId) throws IOException { return documentsService.getFileEntryDetails(projectId, documentConfigId).toGetResponse(); } DocumentsController(); @PostMapping(value = "/config/{documentConfigId}/upload", produces = "application/json") RestResult<FileEntryResource> uploadDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam(value = "filename", required = false) String originalFilename, HttpServletRequest request); @GetMapping("/config/{documentConfigId}/file-contents") @ResponseBody ResponseEntity<Object> getFileContents(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @GetMapping(value = "/config/{documentConfigId}/file-entry-details", produces = "application/json") RestResult<FileEntryResource> getFileEntryDetails(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @DeleteMapping(value = "/config/{documentConfigId}/delete", produces = "application/json") RestResult<Void> deleteDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @PostMapping("/config/{documentConfigId}/submit") RestResult<Void> submitDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @PostMapping("/config/{documentConfigId}/decision") RestResult<Void> documentDecision(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @RequestBody final ProjectDocumentDecision decision); }
@Test public void getFileEntryDetails() throws Exception { Function<DocumentsService, ServiceResult<FileEntryResource>> serviceCallToUpload = (service) -> service.getFileEntryDetails(projectId, documentConfigId); assertGetFileDetails("/project/" + projectId + "/document/config/" + documentConfigId + "/file-entry-details", new Object[] {}, emptyMap(), documentsServiceMock, serviceCallToUpload); }
DocumentsController { @DeleteMapping(value = "/config/{documentConfigId}/delete", produces = "application/json") public RestResult<Void> deleteDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId) throws IOException { return documentsService.deleteDocument(projectId, documentConfigId).toDeleteResponse(); } DocumentsController(); @PostMapping(value = "/config/{documentConfigId}/upload", produces = "application/json") RestResult<FileEntryResource> uploadDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam(value = "filename", required = false) String originalFilename, HttpServletRequest request); @GetMapping("/config/{documentConfigId}/file-contents") @ResponseBody ResponseEntity<Object> getFileContents(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @GetMapping(value = "/config/{documentConfigId}/file-entry-details", produces = "application/json") RestResult<FileEntryResource> getFileEntryDetails(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @DeleteMapping(value = "/config/{documentConfigId}/delete", produces = "application/json") RestResult<Void> deleteDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @PostMapping("/config/{documentConfigId}/submit") RestResult<Void> submitDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @PostMapping("/config/{documentConfigId}/decision") RestResult<Void> documentDecision(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @RequestBody final ProjectDocumentDecision decision); }
@Test public void deleteDocument() throws Exception { Function<DocumentsService, ServiceResult<Void>> serviceCallToDelete = service -> service.deleteDocument(projectId, documentConfigId); assertDeleteFile("/project/" + projectId + "/document/config/" + documentConfigId + "/delete", new Object[] {}, emptyMap(), documentsServiceMock, serviceCallToDelete); }
DocumentsController { @PostMapping("/config/{documentConfigId}/submit") public RestResult<Void> submitDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId) { return documentsService.submitDocument(projectId, documentConfigId).toPostResponse(); } DocumentsController(); @PostMapping(value = "/config/{documentConfigId}/upload", produces = "application/json") RestResult<FileEntryResource> uploadDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam(value = "filename", required = false) String originalFilename, HttpServletRequest request); @GetMapping("/config/{documentConfigId}/file-contents") @ResponseBody ResponseEntity<Object> getFileContents(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @GetMapping(value = "/config/{documentConfigId}/file-entry-details", produces = "application/json") RestResult<FileEntryResource> getFileEntryDetails(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @DeleteMapping(value = "/config/{documentConfigId}/delete", produces = "application/json") RestResult<Void> deleteDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @PostMapping("/config/{documentConfigId}/submit") RestResult<Void> submitDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @PostMapping("/config/{documentConfigId}/decision") RestResult<Void> documentDecision(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @RequestBody final ProjectDocumentDecision decision); }
@Test public void submitDocument() throws Exception { when(documentsServiceMock.submitDocument(projectId, documentConfigId)).thenReturn(serviceSuccess()); mockMvc.perform(RestDocumentationRequestBuilders.post("/project/" + projectId + "/document/config/" + documentConfigId + "/submit") .contentType(APPLICATION_JSON).accept(APPLICATION_JSON)) .andExpect(status().isOk()); verify(documentsServiceMock).submitDocument(projectId, documentConfigId); }
UserPermissionRules { @PermissionRule(value = "READ_USER_ORGANISATION", description = "Internal support users can view all users and associated organisations") public boolean internalUsersCanViewUserOrganisation(UserOrganisationResource userToView, UserResource user) { return 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 internalUsersCanAccessAllUserOrganisations() { UserOrganisationResource userOrganisationResource = UserOrganisationResourceBuilder.newUserOrganisationResource().build(); allGlobalRoleUsers.forEach(user -> { if (isInternal(user)) { assertTrue(rules.internalUsersCanViewUserOrganisation(userOrganisationResource, user)); } else { assertFalse(rules.internalUsersCanViewUserOrganisation(userOrganisationResource, user)); } }); }
DocumentsController { @PostMapping("/config/{documentConfigId}/decision") public RestResult<Void> documentDecision(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @RequestBody final ProjectDocumentDecision decision) { return documentsService.documentDecision(projectId, documentConfigId, decision).toPostResponse(); } DocumentsController(); @PostMapping(value = "/config/{documentConfigId}/upload", produces = "application/json") RestResult<FileEntryResource> uploadDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam(value = "filename", required = false) String originalFilename, HttpServletRequest request); @GetMapping("/config/{documentConfigId}/file-contents") @ResponseBody ResponseEntity<Object> getFileContents(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @GetMapping(value = "/config/{documentConfigId}/file-entry-details", produces = "application/json") RestResult<FileEntryResource> getFileEntryDetails(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @DeleteMapping(value = "/config/{documentConfigId}/delete", produces = "application/json") RestResult<Void> deleteDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @PostMapping("/config/{documentConfigId}/submit") RestResult<Void> submitDocument(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId); @PostMapping("/config/{documentConfigId}/decision") RestResult<Void> documentDecision(@PathVariable("projectId") long projectId, @PathVariable("documentConfigId") long documentConfigId, @RequestBody final ProjectDocumentDecision decision); }
@Test public void documentDecision() throws Exception { ProjectDocumentDecision decision = new ProjectDocumentDecision(true, null); when(documentsServiceMock.documentDecision(projectId, documentConfigId, decision)).thenReturn(serviceSuccess()); mockMvc.perform(RestDocumentationRequestBuilders.post("/project/" + projectId + "/document/config/" + documentConfigId + "/decision") .contentType(APPLICATION_JSON) .content(toJson(decision))) .andExpect(status().isOk()); verify(documentsServiceMock).documentDecision(projectId, documentConfigId, decision); }
DocumentsServiceImpl extends AbstractProjectServiceImpl implements DocumentsService { @Override public ServiceResult<List<String>> getValidMediaTypesForDocument(long documentConfigId) { return getCompetitionDocumentConfig(documentConfigId) .andOnSuccessReturn(projectDocumentConfig -> getMediaTypes(projectDocumentConfig.getFileTypes())); } @Override ServiceResult<List<String>> getValidMediaTypesForDocument(long documentConfigId); @Override @Transactional ServiceResult<FileEntryResource> createDocumentFileEntry(long projectId, long documentConfigId, FileEntryResource fileEntryResource, Supplier<InputStream> inputStreamSupplier); @Override ServiceResult<FileAndContents> getFileContents(long projectId, long documentConfigId); @Override ServiceResult<FileEntryResource> getFileEntryDetails(long projectId, long documentConfigId); @Override @Transactional ServiceResult<Void> deleteDocument(long projectId, long documentConfigId); @Override @Transactional ServiceResult<Void> submitDocument(long projectId, long documentConfigId); @Override @Transactional ServiceResult<Void> documentDecision(long projectId, long documentConfigId, ProjectDocumentDecision decision); }
@Test public void getValidMediaTypesForDocumentWhenConfiguredProjectDocumentNotPresent() { when(competitionDocumentConfigRepositoryMock.findById(documentConfigId)).thenReturn(Optional.empty()); ServiceResult<List<String>> result = service.getValidMediaTypesForDocument(documentConfigId); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(CommonErrors.notFoundError(CompetitionDocument.class, documentConfigId))); } @Test public void getValidMediaTypesForDocument() { ServiceResult<List<String>> result = service.getValidMediaTypesForDocument(documentConfigId); assertTrue(result.isSuccess()); assertEquals(1, result.getSuccess().size()); assertEquals("application/pdf", result.getSuccess().get(0)); }
DocumentsServiceImpl extends AbstractProjectServiceImpl implements DocumentsService { @Override @Transactional public ServiceResult<FileEntryResource> createDocumentFileEntry(long projectId, long documentConfigId, FileEntryResource fileEntryResource, Supplier<InputStream> inputStreamSupplier) { return find(getProject(projectId), getCompetitionDocumentConfig(documentConfigId)). andOnSuccess((project, projectDocumentConfig) -> validateProjectActive(project) .andOnSuccess(() -> fileService.createFile(fileEntryResource, inputStreamSupplier)) .andOnSuccessReturn(fileDetails -> createProjectDocument(project, projectDocumentConfig, fileDetails))); } @Override ServiceResult<List<String>> getValidMediaTypesForDocument(long documentConfigId); @Override @Transactional ServiceResult<FileEntryResource> createDocumentFileEntry(long projectId, long documentConfigId, FileEntryResource fileEntryResource, Supplier<InputStream> inputStreamSupplier); @Override ServiceResult<FileAndContents> getFileContents(long projectId, long documentConfigId); @Override ServiceResult<FileEntryResource> getFileEntryDetails(long projectId, long documentConfigId); @Override @Transactional ServiceResult<Void> deleteDocument(long projectId, long documentConfigId); @Override @Transactional ServiceResult<Void> submitDocument(long projectId, long documentConfigId); @Override @Transactional ServiceResult<Void> documentDecision(long projectId, long documentConfigId, ProjectDocumentDecision decision); }
@Test public void createDocumentFileEntryWhenProjectNotInSetup() { FileEntryResource fileEntryResource = FileEntryResourceBuilder.newFileEntryResource().build(); Supplier<InputStream> inputStreamSupplier = () -> null; when(projectWorkflowHandlerMock.getState(project)).thenReturn(ProjectState.LIVE); ServiceResult<FileEntryResource> result = service.createDocumentFileEntry(projectId, documentConfigId, fileEntryResource, inputStreamSupplier); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(PROJECT_SETUP_ALREADY_COMPLETE)); verify(fileServiceMock, never()).createFile(any(), any()); verify(projectDocumentRepositoryMock, never()).save(any(ProjectDocument.class)); } @Test public void createDocumentFileEntry() { FileEntry fileEntry = newFileEntry().build(); FileEntryResource fileEntryResource = FileEntryResourceBuilder.newFileEntryResource().build(); Supplier<InputStream> inputStreamSupplier = () -> null; ServiceResult<Pair<File, FileEntry>> fileDetails = serviceSuccess(Pair.of(new File("newfile"), fileEntry)); when(fileServiceMock.createFile(fileEntryResource, inputStreamSupplier)).thenReturn(fileDetails); when(fileEntryMapperMock.mapToResource(fileEntry)).thenReturn(fileEntryResource); ServiceResult<FileEntryResource> result = service.createDocumentFileEntry(projectId, documentConfigId, fileEntryResource, inputStreamSupplier); assertTrue(result.isSuccess()); verify(projectDocumentRepositoryMock).save(any(ProjectDocument.class)); ArgumentCaptor<ProjectDocument> captor = ArgumentCaptor.forClass(ProjectDocument.class); verify(projectDocumentRepositoryMock).save(captor.capture()); ProjectDocument savedProjectDocument = captor.getValue(); assertEquals(project, savedProjectDocument.getProject()); assertEquals(configuredCompetitionDocument, savedProjectDocument.getCompetitionDocument()); assertEquals(fileEntry, savedProjectDocument.getFileEntry()); assertEquals(UPLOADED, savedProjectDocument.getStatus()); assertEquals(fileEntryResource, result.getSuccess()); }