src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
PartnerOrganisationPermissionRules extends BasePermissionRules { @PermissionRule(value = "UPDATE_PENDING_PARTNER_PROGRESS", description = "Partners can update their own progress when setting up their organisation") public boolean partnersCanUpdateTheirOwnPendingPartnerProgress(final PartnerOrganisationResource partnerOrganisation, final UserResource user) { return partnerBelongsToOrganisation(partnerOrganisation.getProject(), user.getId(), partnerOrganisation.getOrganisation()); } @PermissionRule(value = "READ", description = "A partner can see a list of all partner organisations on their project") boolean partnersOnProjectCanView(final PartnerOrganisationResource partnerOrganisation, final UserResource user); @PermissionRule(value = "READ", description = "Internal users can see partner organisations for any project") boolean internalUsersCanView(PartnerOrganisationResource partnerOrganisation, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can see partner organisations on projects in competitions they are assigned to") boolean stakeholdersCanViewProjects(PartnerOrganisationResource partnerOrganisation, final UserResource user); @PermissionRule(value = "READ", description = "Competition finances users can see partner organisations on projects in competitions they are assigned to") boolean competitionFinanceUsersCanViewProjects(PartnerOrganisationResource partnerOrganisation, final UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can see partner organisations on a project they are assigned to") boolean monitoringOfficersUsersCanView(PartnerOrganisationResource partnerOrganisation, UserResource user); @PermissionRule(value = "READ_PENDING_PARTNER_PROGRESS", description = "Partners can read their own progress when setting up their organisation") boolean partnersCanReadTheirOwnPendingPartnerProgress(final PartnerOrganisationResource partnerOrganisation, final UserResource user); @PermissionRule(value = "READ_PENDING_PARTNER_PROGRESS", description = "Internal users can read partner progress in project setup") boolean internalUsersCanReadPendingPartnerProgress(final PartnerOrganisationResource partnerOrganisation, final UserResource user); @PermissionRule(value = "READ_PENDING_PARTNER_PROGRESS", description = "Stakeholders can read partner progress in project setup in competitions they are assigned to") boolean stakeholdersCanReadPendingPartnerProgress(final PartnerOrganisationResource partnerOrganisation, final UserResource user); @PermissionRule(value = "READ_PENDING_PARTNER_PROGRESS", description = "Competition finance users can read partner progress in project setup in competitions they are assigned to") boolean competitionFinanceUsersCanReadPendingPartnerProgress(final PartnerOrganisationResource partnerOrganisation, final UserResource user); @PermissionRule(value = "UPDATE_PENDING_PARTNER_PROGRESS", description = "Partners can update their own progress when setting up their organisation") boolean partnersCanUpdateTheirOwnPendingPartnerProgress(final PartnerOrganisationResource partnerOrganisation, final UserResource user); @PermissionRule(value = "REMOVE_PARTNER_ORGANISATION", description = "Internal users can remove partner organisations for any project") boolean internalUsersCanRemovePartnerOrganisations(final PartnerOrganisationResource partnerOrganisation, final UserResource user); } | @Test public void partnersCanUpdateTheirOwnPendingPartnerProgress() { long projectId = 1L; long organisationId = 2L; UserResource user = newUserResource().build(); PartnerOrganisationResource partnerOrg = newPartnerOrganisationResource() .withProject(projectId) .withOrganisation(organisationId) .build(); ProjectUser projectUser = newProjectUser() .build(); when(projectUserRepository.findFirstByProjectIdAndUserIdAndOrganisationIdAndRoleIn(projectId, user.getId(), organisationId, PROJECT_USER_ROLES.stream().collect(Collectors.toList()))).thenReturn(projectUser); assertTrue(rules.partnersCanUpdateTheirOwnPendingPartnerProgress(partnerOrg, user)); } |
PartnerOrganisationPermissionRules extends BasePermissionRules { @PermissionRule(value = "REMOVE_PARTNER_ORGANISATION", description = "Internal users can remove partner organisations for any project") public boolean internalUsersCanRemovePartnerOrganisations(final PartnerOrganisationResource partnerOrganisation, final UserResource user) { return isInternalAdmin(user); } @PermissionRule(value = "READ", description = "A partner can see a list of all partner organisations on their project") boolean partnersOnProjectCanView(final PartnerOrganisationResource partnerOrganisation, final UserResource user); @PermissionRule(value = "READ", description = "Internal users can see partner organisations for any project") boolean internalUsersCanView(PartnerOrganisationResource partnerOrganisation, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can see partner organisations on projects in competitions they are assigned to") boolean stakeholdersCanViewProjects(PartnerOrganisationResource partnerOrganisation, final UserResource user); @PermissionRule(value = "READ", description = "Competition finances users can see partner organisations on projects in competitions they are assigned to") boolean competitionFinanceUsersCanViewProjects(PartnerOrganisationResource partnerOrganisation, final UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can see partner organisations on a project they are assigned to") boolean monitoringOfficersUsersCanView(PartnerOrganisationResource partnerOrganisation, UserResource user); @PermissionRule(value = "READ_PENDING_PARTNER_PROGRESS", description = "Partners can read their own progress when setting up their organisation") boolean partnersCanReadTheirOwnPendingPartnerProgress(final PartnerOrganisationResource partnerOrganisation, final UserResource user); @PermissionRule(value = "READ_PENDING_PARTNER_PROGRESS", description = "Internal users can read partner progress in project setup") boolean internalUsersCanReadPendingPartnerProgress(final PartnerOrganisationResource partnerOrganisation, final UserResource user); @PermissionRule(value = "READ_PENDING_PARTNER_PROGRESS", description = "Stakeholders can read partner progress in project setup in competitions they are assigned to") boolean stakeholdersCanReadPendingPartnerProgress(final PartnerOrganisationResource partnerOrganisation, final UserResource user); @PermissionRule(value = "READ_PENDING_PARTNER_PROGRESS", description = "Competition finance users can read partner progress in project setup in competitions they are assigned to") boolean competitionFinanceUsersCanReadPendingPartnerProgress(final PartnerOrganisationResource partnerOrganisation, final UserResource user); @PermissionRule(value = "UPDATE_PENDING_PARTNER_PROGRESS", description = "Partners can update their own progress when setting up their organisation") boolean partnersCanUpdateTheirOwnPendingPartnerProgress(final PartnerOrganisationResource partnerOrganisation, final UserResource user); @PermissionRule(value = "REMOVE_PARTNER_ORGANISATION", description = "Internal users can remove partner organisations for any project") boolean internalUsersCanRemovePartnerOrganisations(final PartnerOrganisationResource partnerOrganisation, final UserResource user); } | @Test public void internalUsersCanRemovePartnerOrganisations() { long projectId = 1L; long organisationId = 2L; PartnerOrganisationResource partnerOrg = newPartnerOrganisationResource() .withProject(projectId) .withOrganisation(organisationId) .build(); allGlobalRoleUsers.forEach(user -> { if (isInternalAdmin(user)) { assertTrue(rules.internalUsersCanRemovePartnerOrganisations(partnerOrg, user)); } else { assertFalse(rules.internalUsersCanRemovePartnerOrganisations(partnerOrg, user)); } }); } |
UserLookupStrategies { @PermissionEntityLookupStrategy public UserResource findById(Long id) { return userMapper.mapIdToResource(id); } @PermissionEntityLookupStrategy UserResource findById(Long id); } | @Test public void testFindById() { UserResource user = newUserResource().build(); when(userMapperMock.mapIdToResource(123L)).thenReturn(user); assertEquals(user, lookup.findById(123L)); } |
ProjectController { @GetMapping("/{id}") public RestResult<ProjectResource> getProjectById(@PathVariable long id) { return projectService.getProjectById(id).toGetResponse(); } @GetMapping("/{id}") RestResult<ProjectResource> getProjectById(@PathVariable long id); @GetMapping("/application/{applicationId}") RestResult<ProjectResource> getByApplicationId(@PathVariable long applicationId); @GetMapping RestResult<List<ProjectResource>> findAll(); @GetMapping(value = "/user/{userId}") RestResult<List<ProjectResource>> findByUserId(@PathVariable long userId); @GetMapping("/{projectId}/project-users") RestResult<List<ProjectUserResource>> getProjectUsers(@PathVariable long projectId); @GetMapping("/{projectId}/display-project-users") RestResult<List<ProjectUserResource>> getDisplayProjectUsers(@PathVariable long projectId); @GetMapping("/{projectId}/get-organisation-by-user/{userId}") RestResult<OrganisationResource> getOrganisationByProjectAndUser(@PathVariable long projectId,
@PathVariable long userId); @PostMapping("/create-project/application/{applicationId}") RestResult<ProjectResource> createProjectFromApplication(@PathVariable long applicationId); @GetMapping("/{projectId}/lead-organisation") RestResult<OrganisationResource> getLeadOrganisation(@PathVariable long projectId); @GetMapping("/{projectId}/user/{organisationId}/application-exists") RestResult<Boolean> existsOnApplication(@PathVariable long projectId, @PathVariable long organisationId); @GetMapping("/{projectId}/project-finance-contacts") RestResult<List<ProjectUserResource>> getProjectFinanceContacts(@PathVariable(value = "projectId") Long projectId); } | @Test public void getProjectById() throws Exception { ProjectResource project1 = newProjectResource().build(); ProjectResource project2 = newProjectResource().build(); when(projectServiceMock.getProjectById(project1.getId())).thenReturn(serviceSuccess(project1)); when(projectServiceMock.getProjectById(project2.getId())).thenReturn(serviceSuccess(project2)); mockMvc.perform(get("/project/{id}", project1.getId())) .andExpect(status().isOk()) .andExpect(content().json(toJson(project1))); mockMvc.perform(get("/project/{id}", project2.getId())) .andExpect(status().isOk()) .andExpect(content().json(toJson(project2))); } |
ProjectController { @GetMapping public RestResult<List<ProjectResource>> findAll() { return projectService.findAll().toGetResponse(); } @GetMapping("/{id}") RestResult<ProjectResource> getProjectById(@PathVariable long id); @GetMapping("/application/{applicationId}") RestResult<ProjectResource> getByApplicationId(@PathVariable long applicationId); @GetMapping RestResult<List<ProjectResource>> findAll(); @GetMapping(value = "/user/{userId}") RestResult<List<ProjectResource>> findByUserId(@PathVariable long userId); @GetMapping("/{projectId}/project-users") RestResult<List<ProjectUserResource>> getProjectUsers(@PathVariable long projectId); @GetMapping("/{projectId}/display-project-users") RestResult<List<ProjectUserResource>> getDisplayProjectUsers(@PathVariable long projectId); @GetMapping("/{projectId}/get-organisation-by-user/{userId}") RestResult<OrganisationResource> getOrganisationByProjectAndUser(@PathVariable long projectId,
@PathVariable long userId); @PostMapping("/create-project/application/{applicationId}") RestResult<ProjectResource> createProjectFromApplication(@PathVariable long applicationId); @GetMapping("/{projectId}/lead-organisation") RestResult<OrganisationResource> getLeadOrganisation(@PathVariable long projectId); @GetMapping("/{projectId}/user/{organisationId}/application-exists") RestResult<Boolean> existsOnApplication(@PathVariable long projectId, @PathVariable long organisationId); @GetMapping("/{projectId}/project-finance-contacts") RestResult<List<ProjectUserResource>> getProjectFinanceContacts(@PathVariable(value = "projectId") Long projectId); } | @Test public void findAll() throws Exception { int projectNumber = 3; List<ProjectResource> projects = newProjectResource().build(projectNumber); when(projectServiceMock.findAll()).thenReturn(serviceSuccess(projects)); mockMvc.perform(get("/project/").contentType(APPLICATION_JSON).accept(APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$", hasSize(projectNumber))); } |
ProjectController { @GetMapping("/{projectId}/project-users") public RestResult<List<ProjectUserResource>> getProjectUsers(@PathVariable long projectId) { return projectService.getProjectUsersByProjectIdAndRoleIn(projectId, PROJECT_USER_ROLES.stream().collect(Collectors.toList())).toGetResponse(); } @GetMapping("/{id}") RestResult<ProjectResource> getProjectById(@PathVariable long id); @GetMapping("/application/{applicationId}") RestResult<ProjectResource> getByApplicationId(@PathVariable long applicationId); @GetMapping RestResult<List<ProjectResource>> findAll(); @GetMapping(value = "/user/{userId}") RestResult<List<ProjectResource>> findByUserId(@PathVariable long userId); @GetMapping("/{projectId}/project-users") RestResult<List<ProjectUserResource>> getProjectUsers(@PathVariable long projectId); @GetMapping("/{projectId}/display-project-users") RestResult<List<ProjectUserResource>> getDisplayProjectUsers(@PathVariable long projectId); @GetMapping("/{projectId}/get-organisation-by-user/{userId}") RestResult<OrganisationResource> getOrganisationByProjectAndUser(@PathVariable long projectId,
@PathVariable long userId); @PostMapping("/create-project/application/{applicationId}") RestResult<ProjectResource> createProjectFromApplication(@PathVariable long applicationId); @GetMapping("/{projectId}/lead-organisation") RestResult<OrganisationResource> getLeadOrganisation(@PathVariable long projectId); @GetMapping("/{projectId}/user/{organisationId}/application-exists") RestResult<Boolean> existsOnApplication(@PathVariable long projectId, @PathVariable long organisationId); @GetMapping("/{projectId}/project-finance-contacts") RestResult<List<ProjectUserResource>> getProjectFinanceContacts(@PathVariable(value = "projectId") Long projectId); } | @Test public void getProjectUsers() throws Exception { List<ProjectUserResource> projectUsers = newProjectUserResource().build(3); when(projectServiceMock.getProjectUsersByProjectIdAndRoleIn(123L, PROJECT_USER_ROLES.stream().collect(Collectors.toList()))).thenReturn(serviceSuccess(projectUsers)); mockMvc.perform(get("/project/{projectId}/project-users", 123)) .andExpect(status().isOk()) .andExpect(content().json(toJson(projectUsers))); } |
ProjectController { @PostMapping("/create-project/application/{applicationId}") public RestResult<ProjectResource> createProjectFromApplication(@PathVariable long applicationId) { return projectService.createProjectFromApplication(applicationId).toPostWithBodyResponse(); } @GetMapping("/{id}") RestResult<ProjectResource> getProjectById(@PathVariable long id); @GetMapping("/application/{applicationId}") RestResult<ProjectResource> getByApplicationId(@PathVariable long applicationId); @GetMapping RestResult<List<ProjectResource>> findAll(); @GetMapping(value = "/user/{userId}") RestResult<List<ProjectResource>> findByUserId(@PathVariable long userId); @GetMapping("/{projectId}/project-users") RestResult<List<ProjectUserResource>> getProjectUsers(@PathVariable long projectId); @GetMapping("/{projectId}/display-project-users") RestResult<List<ProjectUserResource>> getDisplayProjectUsers(@PathVariable long projectId); @GetMapping("/{projectId}/get-organisation-by-user/{userId}") RestResult<OrganisationResource> getOrganisationByProjectAndUser(@PathVariable long projectId,
@PathVariable long userId); @PostMapping("/create-project/application/{applicationId}") RestResult<ProjectResource> createProjectFromApplication(@PathVariable long applicationId); @GetMapping("/{projectId}/lead-organisation") RestResult<OrganisationResource> getLeadOrganisation(@PathVariable long projectId); @GetMapping("/{projectId}/user/{organisationId}/application-exists") RestResult<Boolean> existsOnApplication(@PathVariable long projectId, @PathVariable long organisationId); @GetMapping("/{projectId}/project-finance-contacts") RestResult<List<ProjectUserResource>> getProjectFinanceContacts(@PathVariable(value = "projectId") Long projectId); } | @Test public void createProjectFromApplication() throws Exception { long applicationId = 1; ProjectResource expectedProject = newProjectResource().build(); when(projectServiceMock.createProjectFromApplication(applicationId)).thenReturn(serviceSuccess(expectedProject)); mockMvc.perform(post("/project/create-project/application/{applicationId}", applicationId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedProject))); verify(projectServiceMock).createProjectFromApplication(applicationId); } |
ProjectController { @GetMapping("/{projectId}/lead-organisation") public RestResult<OrganisationResource> getLeadOrganisation(@PathVariable long projectId){ return projectService.getLeadOrganisation(projectId).toGetResponse(); } @GetMapping("/{id}") RestResult<ProjectResource> getProjectById(@PathVariable long id); @GetMapping("/application/{applicationId}") RestResult<ProjectResource> getByApplicationId(@PathVariable long applicationId); @GetMapping RestResult<List<ProjectResource>> findAll(); @GetMapping(value = "/user/{userId}") RestResult<List<ProjectResource>> findByUserId(@PathVariable long userId); @GetMapping("/{projectId}/project-users") RestResult<List<ProjectUserResource>> getProjectUsers(@PathVariable long projectId); @GetMapping("/{projectId}/display-project-users") RestResult<List<ProjectUserResource>> getDisplayProjectUsers(@PathVariable long projectId); @GetMapping("/{projectId}/get-organisation-by-user/{userId}") RestResult<OrganisationResource> getOrganisationByProjectAndUser(@PathVariable long projectId,
@PathVariable long userId); @PostMapping("/create-project/application/{applicationId}") RestResult<ProjectResource> createProjectFromApplication(@PathVariable long applicationId); @GetMapping("/{projectId}/lead-organisation") RestResult<OrganisationResource> getLeadOrganisation(@PathVariable long projectId); @GetMapping("/{projectId}/user/{organisationId}/application-exists") RestResult<Boolean> existsOnApplication(@PathVariable long projectId, @PathVariable long organisationId); @GetMapping("/{projectId}/project-finance-contacts") RestResult<List<ProjectUserResource>> getProjectFinanceContacts(@PathVariable(value = "projectId") Long projectId); } | @Test public void getLeadOrganisation() throws Exception { long projectId = 5; OrganisationResource organisationResource = newOrganisationResource().build(); when(projectServiceMock.getLeadOrganisation(projectId)).thenReturn(serviceSuccess(organisationResource)); mockMvc.perform(get("/project/{projectId}/lead-organisation", projectId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(organisationResource))); verify(projectServiceMock, only()).getLeadOrganisation(projectId); } |
ProjectController { @GetMapping("/{projectId}/project-finance-contacts") public RestResult<List<ProjectUserResource>> getProjectFinanceContacts(@PathVariable(value = "projectId") Long projectId) { return projectService.getProjectUsersByProjectIdAndRoleIn(projectId, Collections.singletonList(ProjectParticipantRole.PROJECT_FINANCE_CONTACT)).toGetResponse(); } @GetMapping("/{id}") RestResult<ProjectResource> getProjectById(@PathVariable long id); @GetMapping("/application/{applicationId}") RestResult<ProjectResource> getByApplicationId(@PathVariable long applicationId); @GetMapping RestResult<List<ProjectResource>> findAll(); @GetMapping(value = "/user/{userId}") RestResult<List<ProjectResource>> findByUserId(@PathVariable long userId); @GetMapping("/{projectId}/project-users") RestResult<List<ProjectUserResource>> getProjectUsers(@PathVariable long projectId); @GetMapping("/{projectId}/display-project-users") RestResult<List<ProjectUserResource>> getDisplayProjectUsers(@PathVariable long projectId); @GetMapping("/{projectId}/get-organisation-by-user/{userId}") RestResult<OrganisationResource> getOrganisationByProjectAndUser(@PathVariable long projectId,
@PathVariable long userId); @PostMapping("/create-project/application/{applicationId}") RestResult<ProjectResource> createProjectFromApplication(@PathVariable long applicationId); @GetMapping("/{projectId}/lead-organisation") RestResult<OrganisationResource> getLeadOrganisation(@PathVariable long projectId); @GetMapping("/{projectId}/user/{organisationId}/application-exists") RestResult<Boolean> existsOnApplication(@PathVariable long projectId, @PathVariable long organisationId); @GetMapping("/{projectId}/project-finance-contacts") RestResult<List<ProjectUserResource>> getProjectFinanceContacts(@PathVariable(value = "projectId") Long projectId); } | @Test public void getProjectFinanceContacts() throws Exception { Long project1Id = 1L; List<ProjectParticipantRole> projectParticipantRoles = Collections.singletonList(ProjectParticipantRole.PROJECT_FINANCE_CONTACT); List<ProjectUserResource> projectFinanceContacts = Collections.singletonList(newProjectUserResource().withId(project1Id).build()); when(projectServiceMock.getProjectUsersByProjectIdAndRoleIn(project1Id, projectParticipantRoles)).thenReturn(serviceSuccess(projectFinanceContacts)); mockMvc.perform(get("/project/{id}/project-finance-contacts", project1Id)) .andExpect(status().isOk()) .andExpect(content().json(toJson(projectFinanceContacts))); verify(projectServiceMock).getProjectUsersByProjectIdAndRoleIn(project1Id, projectParticipantRoles); } |
PartnerOrganisationController { @GetMapping("/partner/{organisationId}") public RestResult<PartnerOrganisationResource> getPartnerOrganisation(@PathVariable long projectId, @PathVariable long organisationId) { return partnerOrganisationService.getPartnerOrganisation(projectId, organisationId).toGetResponse(); } @GetMapping("/partner-organisation") RestResult<List<PartnerOrganisationResource>> getFinanceCheck(@PathVariable final long projectId); @GetMapping("/partner/{organisationId}") RestResult<PartnerOrganisationResource> getPartnerOrganisation(@PathVariable long projectId,
@PathVariable long organisationId); @PostMapping("/remove-organisation/{organisationId}") RestResult<Void> removeOrganisation(@PathVariable long projectId,
@PathVariable long organisationId); } | @Test public void getProjectPartner() throws Exception { Long projectId = 123L; Long organisationId = 234L; PartnerOrganisationResource partnerOrg = newPartnerOrganisationResource().build(); when(partnerOrganisationService.getPartnerOrganisation(projectId, organisationId)).thenReturn(serviceSuccess(partnerOrg)); mockMvc.perform(get("/project/{projectId}/partner/{organisationId}", projectId, organisationId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(partnerOrg))); } |
PartnerOrganisationController { @PostMapping("/remove-organisation/{organisationId}") public RestResult<Void> removeOrganisation(@PathVariable long projectId, @PathVariable long organisationId) { return partnerOrganisationService.removePartnerOrganisation(id(projectId, organisationId)).toPostResponse(); } @GetMapping("/partner-organisation") RestResult<List<PartnerOrganisationResource>> getFinanceCheck(@PathVariable final long projectId); @GetMapping("/partner/{organisationId}") RestResult<PartnerOrganisationResource> getPartnerOrganisation(@PathVariable long projectId,
@PathVariable long organisationId); @PostMapping("/remove-organisation/{organisationId}") RestResult<Void> removeOrganisation(@PathVariable long projectId,
@PathVariable long organisationId); } | @Test public void removeOrganisation() throws Exception { long projectId = 123; long organisationId = 456; ProjectOrganisationCompositeId projectOrganisationCompositeId = id(projectId, organisationId); when(partnerOrganisationService.removePartnerOrganisation(projectOrganisationCompositeId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/remove-organisation/{organisationId}", projectId, organisationId)) .andExpect(status().isOk()); verify(partnerOrganisationService).removePartnerOrganisation(projectOrganisationCompositeId); } |
ProjectServiceImpl extends AbstractProjectServiceImpl implements ProjectService { @Override @Transactional public ServiceResult<ProjectResource> createProjectFromApplication(long applicationId) { return getApplication(applicationId).andOnSuccess(application -> { if (FundingDecisionStatus.FUNDED.equals(application.getFundingDecision())) { return createSingletonProjectFromApplicationId(applicationId); } else { return serviceFailure(CREATE_PROJECT_FROM_APPLICATION_FAILS); } }); } @Override ServiceResult<ProjectResource> getProjectById(long projectId); @Override ServiceResult<ProjectResource> getByApplicationId(long applicationId); @Override ServiceResult<Boolean> existsOnApplication(long projectId, long organisationId); @Override @Transactional ServiceResult<Void> createProjectsFromFundingDecisions(Map<Long, FundingDecision> applicationFundingDecisions); @Override @Transactional (readOnly = true) ServiceResult<List<ProjectResource>> findByUserId(long userId); @Override ServiceResult<List<ProjectUserResource>> getProjectUsersByProjectIdAndRoleIn(long projectId, List<ProjectParticipantRole> projectParticipantRoles); @Override @Transactional ServiceResult<ProjectUser> addPartner(long projectId, long userId, long organisationId); @Override ServiceResult<OrganisationResource> getOrganisationByProjectAndUser(long projectId, long userId); @Override ServiceResult<List<ProjectResource>> findAll(); @Override @Transactional ServiceResult<ProjectResource> createProjectFromApplication(long applicationId); @Override ServiceResult<OrganisationResource> getLeadOrganisation(long projectId); } | @Test public void createProjectFromApplication() { ProjectResource newProjectResource = newProjectResource().build(); PartnerOrganisation savedProjectPartnerOrganisation = newPartnerOrganisation(). withOrganisation(organisation). withLeadOrganisation(true). build(); Project savedProject = newProject(). withId(newProjectResource.getId()). withApplication(application). withProjectUsers(asList(leadPartnerProjectUser, newProjectUser().build())). withPartnerOrganisations(singletonList(savedProjectPartnerOrganisation)). build(); Project newProjectExpectations = createProjectExpectationsFromOriginalApplication(); when(projectRepositoryMock.save(newProjectExpectations)).thenReturn(savedProject); CostCategoryType costCategoryTypeForOrganisation = newCostCategoryType(). withCostCategoryGroup(newCostCategoryGroup(). withCostCategories(newCostCategory().withName("Cat1", "Cat2").build(2)). build()). build(); when(projectDetailsWorkflowHandlerMock.projectCreated(savedProject, leadPartnerProjectUser)).thenReturn(true); when(viabilityWorkflowHandlerMock.projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser)).thenReturn(true); when(eligibilityWorkflowHandlerMock.projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser)).thenReturn(true); when(golWorkflowHandlerMock.projectCreated(savedProject, leadPartnerProjectUser)).thenReturn(true); when(projectWorkflowHandlerMock.projectCreated(savedProject, leadPartnerProjectUser)).thenReturn(true); when(spendProfileWorkflowHandlerMock.projectCreated(savedProject, leadPartnerProjectUser)).thenReturn(true); when(projectMapperMock.mapToResource(savedProject)).thenReturn(newProjectResource); ServiceResult<ProjectResource> project = service.createProjectFromApplication(applicationId); assertTrue(project.isSuccess()); assertEquals(newProjectResource, project.getSuccess()); assertNotNull(competition.getProjectSetupStarted()); verify(projectDetailsWorkflowHandlerMock).projectCreated(savedProject, leadPartnerProjectUser); verify(viabilityWorkflowHandlerMock).projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser); verify(eligibilityWorkflowHandlerMock).projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser); verify(golWorkflowHandlerMock).projectCreated(savedProject, leadPartnerProjectUser); verify(projectWorkflowHandlerMock).projectCreated(savedProject, leadPartnerProjectUser); verify(projectMapperMock).mapToResource(savedProject); verify(activityLogService).recordActivityByApplicationId(applicationId, ActivityType.APPLICATION_INTO_PROJECT_SETUP); }
@Test public void createProjectFromApplication_alreadyExists() { ProjectResource existingProjectResource = newProjectResource().build(); Project existingProject = newProject().withApplication(application).build(); when(projectRepositoryMock.findOneByApplicationId(applicationId)).thenReturn(existingProject); when(projectMapperMock.mapToResource(existingProject)).thenReturn(existingProjectResource); ServiceResult<ProjectResource> project = service.createProjectFromApplication(applicationId); assertTrue(project.isSuccess()); assertEquals(existingProjectResource, project.getSuccess()); verify(projectRepositoryMock).findOneByApplicationId(applicationId); verify(projectMapperMock).mapToResource(existingProject); verify(projectDetailsWorkflowHandlerMock, never()).projectCreated(any(Project.class), any(ProjectUser.class)); verify(golWorkflowHandlerMock, never()).projectCreated(any(Project.class), any(ProjectUser.class)); verify(projectWorkflowHandlerMock, never()).projectCreated(any(Project.class), any(ProjectUser.class)); } |
AgreementPermissionRules extends BasePermissionRules { @PermissionRule(value = "READ", description = "Any assessor user can view the current agreement") public boolean anyAssessorCanViewTheCurrentAgreement(UserResource user) { return SecurityRuleUtil.hasAssessorAuthority(user); } @PermissionRule(value = "READ", description = "Any assessor user can view the current agreement") boolean anyAssessorCanViewTheCurrentAgreement(UserResource user); } | @Test public void anyAssessorCanViewTheCurrentAgreement() { UserResource userWithAssessorRole = getUserWithRole(ASSESSOR); assertTrue(rules.anyAssessorCanViewTheCurrentAgreement(userWithAssessorRole)); }
@Test public void anyAssessorCanViewTheCurrentAgreement_notAnAssessor() { UserResource userWithoutAssessorRole = newUserResource().build(); assertFalse(rules.anyAssessorCanViewTheCurrentAgreement(userWithoutAssessorRole)); } |
ProjectServiceImpl extends AbstractProjectServiceImpl implements ProjectService { @Override @Transactional (readOnly = true) public ServiceResult<List<ProjectResource>> findByUserId(long userId) { List<ProjectUser> projectUsers = projectUserRepository.findByUserId(userId); return serviceSuccess(projectUsers .stream() .map(ProjectUser::getProcess) .distinct() .map(projectMapper::mapToResource) .collect(toList()) ); } @Override ServiceResult<ProjectResource> getProjectById(long projectId); @Override ServiceResult<ProjectResource> getByApplicationId(long applicationId); @Override ServiceResult<Boolean> existsOnApplication(long projectId, long organisationId); @Override @Transactional ServiceResult<Void> createProjectsFromFundingDecisions(Map<Long, FundingDecision> applicationFundingDecisions); @Override @Transactional (readOnly = true) ServiceResult<List<ProjectResource>> findByUserId(long userId); @Override ServiceResult<List<ProjectUserResource>> getProjectUsersByProjectIdAndRoleIn(long projectId, List<ProjectParticipantRole> projectParticipantRoles); @Override @Transactional ServiceResult<ProjectUser> addPartner(long projectId, long userId, long organisationId); @Override ServiceResult<OrganisationResource> getOrganisationByProjectAndUser(long projectId, long userId); @Override ServiceResult<List<ProjectResource>> findAll(); @Override @Transactional ServiceResult<ProjectResource> createProjectFromApplication(long applicationId); @Override ServiceResult<OrganisationResource> getLeadOrganisation(long projectId); } | @Test public void findByUserId_returnsOnlyDistinctProjects() { Project project = newProject().build(); User user = newUser().build(); List<ProjectUser> projectUserRecords = newProjectUser() .withProject(project) .withRole(PROJECT_PARTNER, PROJECT_FINANCE_CONTACT) .build(2); ProjectResource projectResource = newProjectResource().build(); when(projectUserRepositoryMock.findByUserId(user.getId())).thenReturn(projectUserRecords); when(projectMapperMock.mapToResource(project)).thenReturn(projectResource); List<ProjectResource> result = service.findByUserId(user.getId()).getSuccess(); assertEquals(1L, result.size()); InOrder inOrder = inOrder(projectUserRepositoryMock, projectMapperMock); inOrder.verify(projectUserRepositoryMock).findByUserId(user.getId()); inOrder.verify(projectMapperMock).mapToResource(project); inOrder.verifyNoMoreInteractions(); } |
ProjectServiceImpl extends AbstractProjectServiceImpl implements ProjectService { @Override @Transactional public ServiceResult<ProjectUser> addPartner(long projectId, long userId, long organisationId) { return find(getProject(projectId), getOrganisation(organisationId), getUser(userId)). andOnSuccess((project, organisation, user) -> { if (project.getOrganisations(o -> o.getId() == organisationId).isEmpty()) { return serviceFailure(badRequestError("project does not contain organisation")); } return addProjectPartner(project, user, organisation); }); } @Override ServiceResult<ProjectResource> getProjectById(long projectId); @Override ServiceResult<ProjectResource> getByApplicationId(long applicationId); @Override ServiceResult<Boolean> existsOnApplication(long projectId, long organisationId); @Override @Transactional ServiceResult<Void> createProjectsFromFundingDecisions(Map<Long, FundingDecision> applicationFundingDecisions); @Override @Transactional (readOnly = true) ServiceResult<List<ProjectResource>> findByUserId(long userId); @Override ServiceResult<List<ProjectUserResource>> getProjectUsersByProjectIdAndRoleIn(long projectId, List<ProjectParticipantRole> projectParticipantRoles); @Override @Transactional ServiceResult<ProjectUser> addPartner(long projectId, long userId, long organisationId); @Override ServiceResult<OrganisationResource> getOrganisationByProjectAndUser(long projectId, long userId); @Override ServiceResult<List<ProjectResource>> findAll(); @Override @Transactional ServiceResult<ProjectResource> createProjectFromApplication(long applicationId); @Override ServiceResult<OrganisationResource> getLeadOrganisation(long projectId); } | @Test public void addPartner_organisationNotOnProject(){ Organisation organisationNotOnProject = newOrganisation().build(); when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project)); when(organisationRepositoryMock.findById(o.getId())).thenReturn(Optional.of(o)); when(organisationRepositoryMock.findById(organisationNotOnProject.getId())).thenReturn(Optional.of(organisationNotOnProject)); when(userRepositoryMock.findById(u.getId())).thenReturn(Optional.of(u)); ServiceResult<ProjectUser> shouldFail = service.addPartner(project.getId(), u.getId(), organisationNotOnProject.getId()); assertTrue(shouldFail.isFailure()); assertTrue(shouldFail.getFailure().is(badRequestError("project does not contain organisation"))); }
@Test public void addPartner_partnerAlreadyExists(){ when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project)); when(organisationRepositoryMock.findById(o.getId())).thenReturn(Optional.of(o)); when(userRepositoryMock.findById(u.getId())).thenReturn(Optional.of(u)); setLoggedInUser(newUserResource().withId(u.getId()).build()); ServiceResult<ProjectUser> shouldFail = service.addPartner(project.getId(), u.getId(), o.getId()); verifyZeroInteractions(projectUserRepositoryMock); assertTrue(shouldFail.isSuccess()); }
@Test public void addPartner(){ User newUser = newUser().build(); when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.ofNullable(project)); when(organisationRepositoryMock.findById(o.getId())).thenReturn(Optional.ofNullable(o)); when(userRepositoryMock.findById(u.getId())).thenReturn(Optional.ofNullable(u)); when(userRepositoryMock.findById(newUser.getId())).thenReturn(Optional.ofNullable(u)); List<ProjectUserInvite> projectInvites = newProjectUserInvite().withUser(user).build(1); projectInvites.get(0).open(); when(projectUserInviteRepositoryMock.findByProjectId(project.getId())).thenReturn(projectInvites); ServiceResult<ProjectUser> shouldSucceed = service.addPartner(project.getId(), newUser.getId(), o.getId()); assertTrue(shouldSucceed.isSuccess()); } |
ProjectServiceImpl extends AbstractProjectServiceImpl implements ProjectService { @Override public ServiceResult<Boolean> existsOnApplication(long projectId, long organisationId) { return getProject(projectId).andOnSuccessReturn(p -> p.getApplication().getApplicantProcessRoles().stream() .anyMatch(pr -> pr.getOrganisationId() == organisationId)); } @Override ServiceResult<ProjectResource> getProjectById(long projectId); @Override ServiceResult<ProjectResource> getByApplicationId(long applicationId); @Override ServiceResult<Boolean> existsOnApplication(long projectId, long organisationId); @Override @Transactional ServiceResult<Void> createProjectsFromFundingDecisions(Map<Long, FundingDecision> applicationFundingDecisions); @Override @Transactional (readOnly = true) ServiceResult<List<ProjectResource>> findByUserId(long userId); @Override ServiceResult<List<ProjectUserResource>> getProjectUsersByProjectIdAndRoleIn(long projectId, List<ProjectParticipantRole> projectParticipantRoles); @Override @Transactional ServiceResult<ProjectUser> addPartner(long projectId, long userId, long organisationId); @Override ServiceResult<OrganisationResource> getOrganisationByProjectAndUser(long projectId, long userId); @Override ServiceResult<List<ProjectResource>> findAll(); @Override @Transactional ServiceResult<ProjectResource> createProjectFromApplication(long applicationId); @Override ServiceResult<OrganisationResource> getLeadOrganisation(long projectId); } | @Test public void existsOnApplication(){ when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.ofNullable(project)); ServiceResult<Boolean> shouldSucceed = service.existsOnApplication(project.getId(), organisation.getId()); assertTrue(shouldSucceed.isSuccess()); assertTrue(shouldSucceed.getSuccess()); }
@Test public void doesNotExistsOnApplication(){ when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.ofNullable(project)); ServiceResult<Boolean> shouldSucceed = service.existsOnApplication(project.getId(), newOrganisation().build().getId()); assertTrue(shouldSucceed.isSuccess()); assertFalse(shouldSucceed.getSuccess()); } |
ProjectServiceImpl extends AbstractProjectServiceImpl implements ProjectService { @Override @Transactional public ServiceResult<Void> createProjectsFromFundingDecisions(Map<Long, FundingDecision> applicationFundingDecisions) { List<ServiceResult<ProjectResource>> projectCreationResults = applicationFundingDecisions .keySet() .stream() .filter(d -> applicationFundingDecisions.get(d).equals(FundingDecision.FUNDED)) .map(this::createSingletonProjectFromApplicationId) .collect(toList()); boolean anyProjectCreationFailed = simpleAnyMatch(projectCreationResults, BaseFailingOrSucceedingResult::isFailure); return anyProjectCreationFailed ? serviceFailure(CREATE_PROJECT_FROM_APPLICATION_FAILS) : serviceSuccess(); } @Override ServiceResult<ProjectResource> getProjectById(long projectId); @Override ServiceResult<ProjectResource> getByApplicationId(long applicationId); @Override ServiceResult<Boolean> existsOnApplication(long projectId, long organisationId); @Override @Transactional ServiceResult<Void> createProjectsFromFundingDecisions(Map<Long, FundingDecision> applicationFundingDecisions); @Override @Transactional (readOnly = true) ServiceResult<List<ProjectResource>> findByUserId(long userId); @Override ServiceResult<List<ProjectUserResource>> getProjectUsersByProjectIdAndRoleIn(long projectId, List<ProjectParticipantRole> projectParticipantRoles); @Override @Transactional ServiceResult<ProjectUser> addPartner(long projectId, long userId, long organisationId); @Override ServiceResult<OrganisationResource> getOrganisationByProjectAndUser(long projectId, long userId); @Override ServiceResult<List<ProjectResource>> findAll(); @Override @Transactional ServiceResult<ProjectResource> createProjectFromApplication(long applicationId); @Override ServiceResult<OrganisationResource> getLeadOrganisation(long projectId); } | @Test public void createProjectsFromFundingDecisions() { ProjectResource newProjectResource = newProjectResource().build(); PartnerOrganisation savedProjectPartnerOrganisation = newPartnerOrganisation(). withOrganisation(organisation). withLeadOrganisation(true). build(); Project savedProject = newProject(). withId(newProjectResource.getId()). withApplication(application). withProjectUsers(asList(leadPartnerProjectUser, newProjectUser().build())). withPartnerOrganisations(singletonList(savedProjectPartnerOrganisation)). build(); Project newProjectExpectations = createProjectExpectationsFromOriginalApplication(); when(projectRepositoryMock.save(newProjectExpectations)).thenReturn(savedProject); CostCategoryType costCategoryTypeForOrganisation = newCostCategoryType(). withCostCategoryGroup(newCostCategoryGroup(). withCostCategories(newCostCategory().withName("Cat1", "Cat2").build(2)). build()). build(); when(projectDetailsWorkflowHandlerMock.projectCreated(savedProject, leadPartnerProjectUser)).thenReturn(true); when(viabilityWorkflowHandlerMock.projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser)).thenReturn(true); when(eligibilityWorkflowHandlerMock.projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser)).thenReturn(true); when(golWorkflowHandlerMock.projectCreated(savedProject, leadPartnerProjectUser)).thenReturn(true); when(projectWorkflowHandlerMock.projectCreated(savedProject, leadPartnerProjectUser)).thenReturn(true); when(spendProfileWorkflowHandlerMock.projectCreated(savedProject, leadPartnerProjectUser)).thenReturn(true); when(projectMapperMock.mapToResource(savedProject)).thenReturn(newProjectResource); Map<Long, FundingDecision> fundingDecisions = new HashMap<>(); fundingDecisions.put(applicationId, FundingDecision.FUNDED); ServiceResult<Void> project = service.createProjectsFromFundingDecisions(fundingDecisions); assertTrue(project.isSuccess()); assertNotNull(competition.getProjectSetupStarted()); verify(projectDetailsWorkflowHandlerMock).projectCreated(savedProject, leadPartnerProjectUser); verify(viabilityWorkflowHandlerMock).projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser); verify(eligibilityWorkflowHandlerMock).projectCreated(savedProjectPartnerOrganisation, leadPartnerProjectUser); verify(golWorkflowHandlerMock).projectCreated(savedProject, leadPartnerProjectUser); verify(projectWorkflowHandlerMock).projectCreated(savedProject, leadPartnerProjectUser); verify(projectMapperMock).mapToResource(savedProject); verify(activityLogService).recordActivityByApplicationId(applicationId, ActivityType.APPLICATION_INTO_PROJECT_SETUP); }
@Test public void createProjectsFromFundingDecisions_saveFails() throws Exception { Project newProjectExpectations = createProjectExpectationsFromOriginalApplication(); when(projectRepositoryMock.save(newProjectExpectations)).thenThrow(new DataIntegrityViolationException("dummy constraint violation")); Map<Long, FundingDecision> fundingDecisions = new HashMap<>(); fundingDecisions.put(applicationId, FundingDecision.FUNDED); try { service.createProjectsFromFundingDecisions(fundingDecisions); assertThat("Service failed to throw expected exception.", false); } catch (Exception e) { assertEquals(e.getCause().getCause().getMessage(),"dummy constraint violation"); } }
@Test public void createProjectsFromFundingDecisions_noFinanceFails() throws Exception { createProjectExpectationsFromOriginalApplication(); List<Section> oldSections = competition.getSections(); competition.setSections(emptyList()); Map<Long, FundingDecision> fundingDecisions = new HashMap<>(); fundingDecisions.put(applicationId, FundingDecision.FUNDED); ServiceResult<Void> result = service.createProjectsFromFundingDecisions(fundingDecisions); assertTrue(result.isFailure()); assertEquals(result.getFailure().getErrors().get(0).getErrorKey(), "CREATE_PROJECT_FROM_APPLICATION_FAILS"); competition.setSections(oldSections); } |
ProjectServiceImpl extends AbstractProjectServiceImpl implements ProjectService { @Override public ServiceResult<OrganisationResource> getLeadOrganisation(long projectId) { return getProject(projectId) .andOnSuccessReturn(p -> p.getApplication().getLeadOrganisationId()) .andOnSuccess(this::getOrganisation) .andOnSuccessReturn(o -> organisationMapper.mapToResource(o)); } @Override ServiceResult<ProjectResource> getProjectById(long projectId); @Override ServiceResult<ProjectResource> getByApplicationId(long applicationId); @Override ServiceResult<Boolean> existsOnApplication(long projectId, long organisationId); @Override @Transactional ServiceResult<Void> createProjectsFromFundingDecisions(Map<Long, FundingDecision> applicationFundingDecisions); @Override @Transactional (readOnly = true) ServiceResult<List<ProjectResource>> findByUserId(long userId); @Override ServiceResult<List<ProjectUserResource>> getProjectUsersByProjectIdAndRoleIn(long projectId, List<ProjectParticipantRole> projectParticipantRoles); @Override @Transactional ServiceResult<ProjectUser> addPartner(long projectId, long userId, long organisationId); @Override ServiceResult<OrganisationResource> getOrganisationByProjectAndUser(long projectId, long userId); @Override ServiceResult<List<ProjectResource>> findAll(); @Override @Transactional ServiceResult<ProjectResource> createProjectFromApplication(long applicationId); @Override ServiceResult<OrganisationResource> getLeadOrganisation(long projectId); } | @Test public void getLeadOrganisation() { OrganisationResource expectedOrganisationResource = newOrganisationResource().build(); when(projectRepositoryMock.findById(project.getId())).thenReturn(Optional.of(project)); when(organisationMapperMock.mapToResource(organisation)).thenReturn(expectedOrganisationResource); OrganisationResource organisationResource = service.getLeadOrganisation(project.getId()).getSuccess(); assertEquals(expectedOrganisationResource, organisationResource); InOrder inOrder = inOrder(projectRepositoryMock, organisationRepositoryMock, organisationMapperMock); inOrder.verify(projectRepositoryMock).findById(project.getId()); inOrder.verify(organisationRepositoryMock).findById(project.getApplication().getLeadOrganisationId()); inOrder.verify(organisationMapperMock).mapToResource(organisation); inOrder.verifyNoMoreInteractions(); } |
PartnerOrganisationServiceImpl implements PartnerOrganisationService { @Override public ServiceResult<PartnerOrganisationResource> getPartnerOrganisation(Long projectId, Long organisationId) { return find(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(projectId, organisationId), notFoundError(PartnerOrganisation.class)). andOnSuccessReturn(partnerOrganisationMapper::mapToResource); } @Override ServiceResult<List<PartnerOrganisationResource>> getProjectPartnerOrganisations(Long projectId); @Override ServiceResult<PartnerOrganisationResource> getPartnerOrganisation(Long projectId, Long organisationId); @Override @Transactional ServiceResult<Void> removePartnerOrganisation(ProjectOrganisationCompositeId projectOrganisationCompositeId); } | @Test public void getPartnerOrganisation() { when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(projectId, organisations.get(0).getId())).thenReturn(partnerOrganisations.get(0)); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(projectId, organisations.get(1).getId())).thenReturn(partnerOrganisations.get(1)); when(partnerOrganisationMapper.mapToResource(partnerOrganisations.get(0))).thenReturn(partnerOrganisationResources.get(0)); when(partnerOrganisationMapper.mapToResource(partnerOrganisations.get(1))).thenReturn(partnerOrganisationResources.get(1)); ServiceResult<PartnerOrganisationResource> result = service.getPartnerOrganisation(projectId, organisations.get(0).getId()); ServiceResult<PartnerOrganisationResource> result2 = service.getPartnerOrganisation(projectId, organisations.get(1).getId()); assertEquals(partnerOrganisationResources.get(0), result.getSuccess()); assertEquals(partnerOrganisationResources.get(1), result2.getSuccess()); verify(partnerOrganisationRepository, times(1)).findOneByProjectIdAndOrganisationId(projectId, organisations.get(0).getId()); verify(partnerOrganisationRepository, times(1)).findOneByProjectIdAndOrganisationId(projectId, organisations.get(1).getId()); verifyNoMoreInteractions(partnerOrganisationRepository); } |
PartnerOrganisationServiceImpl implements PartnerOrganisationService { @Override public ServiceResult<List<PartnerOrganisationResource>> getProjectPartnerOrganisations(Long projectId) { return find(partnerOrganisationRepository.findByProjectId(projectId), notFoundError(PartnerOrganisation.class)). andOnSuccessReturn(lst -> simpleMap(lst, partnerOrganisationMapper::mapToResource)); } @Override ServiceResult<List<PartnerOrganisationResource>> getProjectPartnerOrganisations(Long projectId); @Override ServiceResult<PartnerOrganisationResource> getPartnerOrganisation(Long projectId, Long organisationId); @Override @Transactional ServiceResult<Void> removePartnerOrganisation(ProjectOrganisationCompositeId projectOrganisationCompositeId); } | @Test public void getProjectPartnerOrganisations() { when(partnerOrganisationRepository.findByProjectId(projectId)).thenReturn(partnerOrganisations); when(partnerOrganisationMapper.mapToResource(partnerOrganisations.get(0))).thenReturn(partnerOrganisationResources.get(0)); when(partnerOrganisationMapper.mapToResource(partnerOrganisations.get(1))).thenReturn(partnerOrganisationResources.get(1)); ServiceResult<List<PartnerOrganisationResource>> result = service.getProjectPartnerOrganisations(projectId); assertTrue(result.isSuccess()); assertEquals(partnerOrganisationResources, result.getSuccess()); verify(partnerOrganisationRepository, times(1)).findByProjectId(projectId); verifyNoMoreInteractions(partnerOrganisationRepository); } |
PartnerOrganisationServiceImpl implements PartnerOrganisationService { @Override @Transactional public ServiceResult<Void> removePartnerOrganisation(ProjectOrganisationCompositeId projectOrganisationCompositeId) { return find(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(projectOrganisationCompositeId.getProjectId(), projectOrganisationCompositeId.getOrganisationId()), notFoundError(PartnerOrganisation.class)).andOnSuccess( projectPartner -> validatePartnerNotLead(projectPartner).andOnSuccessReturnVoid( () -> { removePartnerOrg(projectOrganisationCompositeId.getProjectId(), projectPartner.getOrganisation().getId()); projectPartnerChangeService.updateProjectWhenPartnersChange(projectOrganisationCompositeId.getProjectId()); removePartnerNotificationService.sendNotifications(projectPartner.getProject(), projectPartner.getOrganisation()); }) ); } @Override ServiceResult<List<PartnerOrganisationResource>> getProjectPartnerOrganisations(Long projectId); @Override ServiceResult<PartnerOrganisationResource> getPartnerOrganisation(Long projectId, Long organisationId); @Override @Transactional ServiceResult<Void> removePartnerOrganisation(ProjectOrganisationCompositeId projectOrganisationCompositeId); } | @Test public void removeNonLeadPartnerOrganisation() { pendingPartnerProgress = new PendingPartnerProgress(partnerOrganisations.get(1)); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisations.get(1).getId()); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(projectOrganisationCompositeId.getProjectId(), projectOrganisationCompositeId.getOrganisationId())).thenReturn(partnerOrganisations.get(1)); when(pendingPartnerProgressRepository.findByOrganisationIdAndProjectId(organisations.get(1).getId(), projectId)).thenReturn(Optional.of(pendingPartnerProgress)); when(projectFinanceRepository.findByProjectIdAndOrganisationId(projectId, organisations.get(1).getId())).thenReturn(Optional.of(projectFinance.get(1))); when(bankDetailsRepository.findByProjectIdAndOrganisationId(projectId, organisations.get(1).getId())).thenReturn(Optional.of(bankDetails.get(1))); when(projectUserRepository.findByProjectIdAndRole(projectId, PROJECT_MANAGER)).thenReturn(Optional.of(projectUsers.get(0))); ServiceResult<Void> result = service.removePartnerOrganisation(projectOrganisationCompositeId); assertTrue(result.isSuccess()); verify(partnerOrganisationRepository, times(1)).findOneByProjectIdAndOrganisationId(projectOrganisationCompositeId.getProjectId(), projectOrganisationCompositeId.getOrganisationId()); verify(pendingPartnerProgressRepository, times(1)).findByOrganisationIdAndProjectId(organisations.get(1).getId(), projectId); verify(projectFinanceRepository, times(1)).findByProjectIdAndOrganisationId(projectId, organisations.get(1).getId()); verify(bankDetailsRepository, times(1)).findByProjectIdAndOrganisationId(projectId, organisations.get(1).getId()); verify(projectUserInviteRepository, times(1)).deleteAllByProjectIdAndOrganisationId(projectId, organisations.get(1).getId()); verify(projectPartnerInviteRepository, times(1)).deleteByProjectIdAndInviteOrganisationOrganisationId(projectId, organisations.get(1).getId()); verify(projectUserRepository, times(1)).deleteAllByProjectIdAndOrganisationId(projectId, organisations.get(1).getId()); verify(partnerOrganisationRepository, times(1)).deleteOneByProjectIdAndOrganisationId(projectId, organisations.get(1).getId()); verify(projectFinanceRowRepository, times(1)).deleteAllByTargetId(projectFinance.get(1).getId()); verify(projectFinanceRepository, times(1)).deleteAllByProjectIdAndOrganisationId(projectId, organisations.get(1).getId()); verify(noteRepository, times(1)).deleteAllByClassPk(projectFinance.get(1).getId()); verify(queryRepository, times(1)).deleteAllByClassPk(projectFinance.get(1).getId()); verify(projectPartnerChangeService, times(1)).updateProjectWhenPartnersChange(projectOrganisationCompositeId.getProjectId()); verify(removePartnerNotificationService, times(1)).sendNotifications(project, organisations.get(1)); }
@Test public void removeLeadPartnerOrganisation() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisations.get(0).getId()); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(projectId, organisations.get(0).getId())).thenReturn(partnerOrganisations.get(0)); ServiceResult<Void> result = service.removePartnerOrganisation(projectOrganisationCompositeId); assertTrue(result.isFailure()); verify(partnerOrganisationRepository, times(1)).findOneByProjectIdAndOrganisationId(projectId, organisations.get(0).getId()); verifyNoMoreInteractions(partnerOrganisationRepository); } |
ProjectPartnerChangeServiceImpl extends BaseTransactionalService implements ProjectPartnerChangeService { @Override @Transactional public void updateProjectWhenPartnersChange(long projectId) { rejectProjectDocuments(projectId); resetProjectFinanceEligibility(projectId); } @Override @Transactional void updateProjectWhenPartnersChange(long projectId); } | @Test public void updateProjectWhenPartnersChange_EligibilityIsReset() { when(projectDocumentRepository.findAllByProjectId(2L)).thenReturn(Collections.emptyList()); when(partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(2L, 1L)).thenReturn(partnerOrganisation); service.updateProjectWhenPartnersChange(2L); verify(eligibilityWorkflowHandler, times(1)).eligibilityReset(partnerOrganisation, user); }
@Test public void updateProjectWhenPartnersChange_submittedDocumentIsRejected() { List<ProjectDocument> documents = Collections.singletonList(projectDocument); when(projectDocumentRepository.findAllByProjectId(1L)).thenReturn(documents); service.updateProjectWhenPartnersChange(1L); verify(projectDocument).setStatus(DocumentStatus.REJECTED_DUE_TO_TEAM_CHANGE); }
@Test public void updateProjectWhenPartnersChange_thereAreNoSubmittedDocuments() { List<ProjectDocument> documents = Collections.emptyList(); when(projectDocumentRepository.findAllByProjectId(1L)).thenReturn(documents); service.updateProjectWhenPartnersChange(1L); verify(projectDocumentRepository, times(0)).saveAll(any()); }
@Test public void updateProjectWhenPartnersChange_thereAreOnlyRejectedDocuments() { List<ProjectDocument> documents = Collections.singletonList(projectDocument); when(projectDocumentRepository.findAllByProjectId(1L)).thenReturn(documents); service.updateProjectWhenPartnersChange(1L); verify(projectDocumentRepository, times(0)).saveAll(any()); } |
Project implements ProcessActivity { public List<Organisation> getOrganisations(){ return simpleMap(partnerOrganisations, PartnerOrganisation::getOrganisation); } Project(); Project(Application application, LocalDate targetStartDate, Address address,
Long durationInMonths, String name, ZonedDateTime documentsSubmittedDate, ApprovalType otherDocumentsApproved ); void addProjectUser(ProjectUser projectUser); void setProjectMonitoringOfficer(MonitoringOfficer projectMonitoringOfficer); FinanceReviewer getFinanceReviewer(); void setFinanceReviewer(FinanceReviewer financeReviewer); void addPartnerOrganisation(PartnerOrganisation partnerOrganisation); boolean removeProjectUser(ProjectUser projectUser); boolean removeProjectUsers(List<ProjectUser> projectUserstoRemove); ProjectUser getExistingProjectUserWithRoleForOrganisation(ProjectParticipantRole role, Organisation organisation); Optional<PartnerOrganisation> getLeadOrganisation(); Long getId(); void setId(Long id); LocalDate getTargetStartDate(); void setTargetStartDate(LocalDate targetStartDate); Address getAddress(); void setAddress(Address address); Long getDurationInMonths(); void setDurationInMonths(Long durationInMonths); String getName(); void setName(String name); Application getApplication(); void setApplication(Application application); List<ProjectUser> getProjectUsers(); List<ProjectUser> getProjectUsers(Predicate<ProjectUser> filter); List<ProjectUser> getProjectUsersWithRole(ProjectParticipantRole... roles); List<Organisation> getOrganisations(); List<Organisation> getOrganisations(Predicate<Organisation> predicate); List<PartnerOrganisation> getPartnerOrganisations(); void setProjectUsers(List<ProjectUser> projectUsers); void setPartnerOrganisations(List<PartnerOrganisation> partnerOrganisations); ZonedDateTime getDocumentsSubmittedDate(); void setDocumentsSubmittedDate(ZonedDateTime documentsSubmittedDate); ZonedDateTime getOfferSubmittedDate(); void setOfferSubmittedDate(ZonedDateTime offerSubmittedDate); String getGrantOfferLetterRejectionReason(); void setGrantOfferLetterRejectionReason(String grantOfferLetterRejectionReason); FileEntry getSignedGrantOfferLetter(); void setSignedGrantOfferLetter(FileEntry signedGrantOfferLetter); FileEntry getAdditionalContractFile(); void setAdditionalContractFile(FileEntry additionalContractFile); FileEntry getGrantOfferLetter(); void setGrantOfferLetter(FileEntry grantOfferLetter); @NotNull ApprovalType getOtherDocumentsApproved(); void setOtherDocumentsApproved(@NotNull ApprovalType otherDocumentsApproved); ZonedDateTime getSpendProfileSubmittedDate(); void setSpendProfileSubmittedDate(ZonedDateTime spendProfileSubmittedDate); List<SpendProfile> getSpendProfiles(); void setSpendProfiles(List<SpendProfile> spendProfiles); List<ProjectDocument> getProjectDocuments(); void setProjectDocuments(List<ProjectDocument> projectDocuments); boolean isPartner(User user); boolean isProjectManager(User user); Optional<MonitoringOfficer> getProjectMonitoringOfficer(); MonitoringOfficer getProjectMonitoringOfficerOrElseNull(); ProjectProcess getProjectProcess(); boolean isSpendProfileGenerated(); boolean isCollaborativeProject(); ProjectState getProjectState(); DocusignDocument getSignedGolDocusignDocument(); void setSignedGolDocusignDocument(DocusignDocument signedGolDocusignDocument); void setProjectProcess(ProjectProcess projectProcess); boolean isUseDocusignForGrantOfferLetter(); void setUseDocusignForGrantOfferLetter(boolean useDocusignForGrantOfferLetter); } | @Test public void testGetOrganisations() { Organisation org1 = newOrganisation().build(); Organisation org2 = newOrganisation().build(); List<PartnerOrganisation> partnerOrganisations = newPartnerOrganisation().withOrganisation(org1, org2).build(2); Project project = newProject().withPartnerOrganisations(partnerOrganisations).build(); assertNotNull(project.getOrganisations()); assertEquals(org1, project.getOrganisations().get(0)); assertEquals(org2, project.getOrganisations().get(1)); } |
Project implements ProcessActivity { public List<ProjectUser> getProjectUsers() { return projectUsers; } Project(); Project(Application application, LocalDate targetStartDate, Address address,
Long durationInMonths, String name, ZonedDateTime documentsSubmittedDate, ApprovalType otherDocumentsApproved ); void addProjectUser(ProjectUser projectUser); void setProjectMonitoringOfficer(MonitoringOfficer projectMonitoringOfficer); FinanceReviewer getFinanceReviewer(); void setFinanceReviewer(FinanceReviewer financeReviewer); void addPartnerOrganisation(PartnerOrganisation partnerOrganisation); boolean removeProjectUser(ProjectUser projectUser); boolean removeProjectUsers(List<ProjectUser> projectUserstoRemove); ProjectUser getExistingProjectUserWithRoleForOrganisation(ProjectParticipantRole role, Organisation organisation); Optional<PartnerOrganisation> getLeadOrganisation(); Long getId(); void setId(Long id); LocalDate getTargetStartDate(); void setTargetStartDate(LocalDate targetStartDate); Address getAddress(); void setAddress(Address address); Long getDurationInMonths(); void setDurationInMonths(Long durationInMonths); String getName(); void setName(String name); Application getApplication(); void setApplication(Application application); List<ProjectUser> getProjectUsers(); List<ProjectUser> getProjectUsers(Predicate<ProjectUser> filter); List<ProjectUser> getProjectUsersWithRole(ProjectParticipantRole... roles); List<Organisation> getOrganisations(); List<Organisation> getOrganisations(Predicate<Organisation> predicate); List<PartnerOrganisation> getPartnerOrganisations(); void setProjectUsers(List<ProjectUser> projectUsers); void setPartnerOrganisations(List<PartnerOrganisation> partnerOrganisations); ZonedDateTime getDocumentsSubmittedDate(); void setDocumentsSubmittedDate(ZonedDateTime documentsSubmittedDate); ZonedDateTime getOfferSubmittedDate(); void setOfferSubmittedDate(ZonedDateTime offerSubmittedDate); String getGrantOfferLetterRejectionReason(); void setGrantOfferLetterRejectionReason(String grantOfferLetterRejectionReason); FileEntry getSignedGrantOfferLetter(); void setSignedGrantOfferLetter(FileEntry signedGrantOfferLetter); FileEntry getAdditionalContractFile(); void setAdditionalContractFile(FileEntry additionalContractFile); FileEntry getGrantOfferLetter(); void setGrantOfferLetter(FileEntry grantOfferLetter); @NotNull ApprovalType getOtherDocumentsApproved(); void setOtherDocumentsApproved(@NotNull ApprovalType otherDocumentsApproved); ZonedDateTime getSpendProfileSubmittedDate(); void setSpendProfileSubmittedDate(ZonedDateTime spendProfileSubmittedDate); List<SpendProfile> getSpendProfiles(); void setSpendProfiles(List<SpendProfile> spendProfiles); List<ProjectDocument> getProjectDocuments(); void setProjectDocuments(List<ProjectDocument> projectDocuments); boolean isPartner(User user); boolean isProjectManager(User user); Optional<MonitoringOfficer> getProjectMonitoringOfficer(); MonitoringOfficer getProjectMonitoringOfficerOrElseNull(); ProjectProcess getProjectProcess(); boolean isSpendProfileGenerated(); boolean isCollaborativeProject(); ProjectState getProjectState(); DocusignDocument getSignedGolDocusignDocument(); void setSignedGolDocusignDocument(DocusignDocument signedGolDocusignDocument); void setProjectProcess(ProjectProcess projectProcess); boolean isUseDocusignForGrantOfferLetter(); void setUseDocusignForGrantOfferLetter(boolean useDocusignForGrantOfferLetter); } | @Test public void testGetProjectUsersFilter() { Project project = newProject().withProjectUsers(newProjectUser().withRole(PROJECT_PARTNER).build(1)).build(); Predicate<ProjectUser> shouldRemove = pu -> PROJECT_PARTNER != pu.getRole(); Predicate<ProjectUser> shouldNotRemove = pu -> PROJECT_PARTNER == pu.getRole(); assertNotNull(project.getProjectUsers(shouldRemove)); assertTrue(project.getProjectUsers(shouldRemove).isEmpty()); assertNotNull(project.getProjectUsers(shouldNotRemove)); assertEquals(1, project.getProjectUsers(shouldNotRemove).size()); } |
ProcessRoleController { @GetMapping("{id}/application") public RestResult<ApplicationResource> findByProcessRole(@PathVariable("id") final long id) { return applicationService.findByProcessRole(id).toGetResponse(); } @GetMapping("/{id}") RestResult<ProcessRoleResource> findOne(@PathVariable("id") final long id); @GetMapping("/find-by-user-application/{userId}/{applicationId}") RestResult<ProcessRoleResource> findByUserApplication(@PathVariable("userId") final long userId,
@PathVariable("applicationId") final long applicationId); @GetMapping("/find-by-application-id/{applicationId}") RestResult<List<ProcessRoleResource>> findByUserApplication(@PathVariable("applicationId") final long applicationId); @GetMapping("/find-by-user-id/{userId}") RestResult<List<ProcessRoleResource>> findByUser(@PathVariable("userId") final long userId); @GetMapping("/find-assignable/{applicationId}") RestResult<List<ProcessRoleResource>> findAssignable(@PathVariable("applicationId") final long applicationId); @GetMapping("{id}/application") RestResult<ApplicationResource> findByProcessRole(@PathVariable("id") final long id); @GetMapping("user-has-application-for-competition/{userId}/{competitionId}") RestResult<Boolean> userHasApplicationForCompetition(@PathVariable("userId") final long userId, @PathVariable("competitionId") final long competitionId); } | @Test public void findByProcessRoleShouldReturnApplicationResourceList() throws Exception { String appName = "app1"; when(applicationServiceMock.findByProcessRole(1L)).thenReturn(serviceSuccess(newApplicationResource().withName(appName).build())); mockMvc.perform(get("/processrole/{id}/application", 1)) .andExpect(status().isOk()) .andExpect(jsonPath("$.name", is(appName))); } |
Project implements ProcessActivity { public List<ProjectUser> getProjectUsersWithRole(ProjectParticipantRole... roles){ return getProjectUsers(pu -> Arrays.stream(roles).anyMatch(pu.getRole()::equals)); } Project(); Project(Application application, LocalDate targetStartDate, Address address,
Long durationInMonths, String name, ZonedDateTime documentsSubmittedDate, ApprovalType otherDocumentsApproved ); void addProjectUser(ProjectUser projectUser); void setProjectMonitoringOfficer(MonitoringOfficer projectMonitoringOfficer); FinanceReviewer getFinanceReviewer(); void setFinanceReviewer(FinanceReviewer financeReviewer); void addPartnerOrganisation(PartnerOrganisation partnerOrganisation); boolean removeProjectUser(ProjectUser projectUser); boolean removeProjectUsers(List<ProjectUser> projectUserstoRemove); ProjectUser getExistingProjectUserWithRoleForOrganisation(ProjectParticipantRole role, Organisation organisation); Optional<PartnerOrganisation> getLeadOrganisation(); Long getId(); void setId(Long id); LocalDate getTargetStartDate(); void setTargetStartDate(LocalDate targetStartDate); Address getAddress(); void setAddress(Address address); Long getDurationInMonths(); void setDurationInMonths(Long durationInMonths); String getName(); void setName(String name); Application getApplication(); void setApplication(Application application); List<ProjectUser> getProjectUsers(); List<ProjectUser> getProjectUsers(Predicate<ProjectUser> filter); List<ProjectUser> getProjectUsersWithRole(ProjectParticipantRole... roles); List<Organisation> getOrganisations(); List<Organisation> getOrganisations(Predicate<Organisation> predicate); List<PartnerOrganisation> getPartnerOrganisations(); void setProjectUsers(List<ProjectUser> projectUsers); void setPartnerOrganisations(List<PartnerOrganisation> partnerOrganisations); ZonedDateTime getDocumentsSubmittedDate(); void setDocumentsSubmittedDate(ZonedDateTime documentsSubmittedDate); ZonedDateTime getOfferSubmittedDate(); void setOfferSubmittedDate(ZonedDateTime offerSubmittedDate); String getGrantOfferLetterRejectionReason(); void setGrantOfferLetterRejectionReason(String grantOfferLetterRejectionReason); FileEntry getSignedGrantOfferLetter(); void setSignedGrantOfferLetter(FileEntry signedGrantOfferLetter); FileEntry getAdditionalContractFile(); void setAdditionalContractFile(FileEntry additionalContractFile); FileEntry getGrantOfferLetter(); void setGrantOfferLetter(FileEntry grantOfferLetter); @NotNull ApprovalType getOtherDocumentsApproved(); void setOtherDocumentsApproved(@NotNull ApprovalType otherDocumentsApproved); ZonedDateTime getSpendProfileSubmittedDate(); void setSpendProfileSubmittedDate(ZonedDateTime spendProfileSubmittedDate); List<SpendProfile> getSpendProfiles(); void setSpendProfiles(List<SpendProfile> spendProfiles); List<ProjectDocument> getProjectDocuments(); void setProjectDocuments(List<ProjectDocument> projectDocuments); boolean isPartner(User user); boolean isProjectManager(User user); Optional<MonitoringOfficer> getProjectMonitoringOfficer(); MonitoringOfficer getProjectMonitoringOfficerOrElseNull(); ProjectProcess getProjectProcess(); boolean isSpendProfileGenerated(); boolean isCollaborativeProject(); ProjectState getProjectState(); DocusignDocument getSignedGolDocusignDocument(); void setSignedGolDocusignDocument(DocusignDocument signedGolDocusignDocument); void setProjectProcess(ProjectProcess projectProcess); boolean isUseDocusignForGrantOfferLetter(); void setUseDocusignForGrantOfferLetter(boolean useDocusignForGrantOfferLetter); } | @Test public void testGetProjectUsersWithRole() { ProjectUser pu1 = newProjectUser().withRole(PROJECT_PARTNER).build(); ProjectUser pu2 = newProjectUser().withRole(PROJECT_FINANCE_CONTACT).build(); Project project = newProject().withProjectUsers(asList(pu1, pu2)).build(); assertNotNull(project.getProjectUsersWithRole(PROJECT_PARTNER)); assertEquals(1, project.getProjectUsersWithRole(PROJECT_PARTNER).size()); assertEquals(pu1, project.getProjectUsersWithRole(PROJECT_PARTNER).get(0)); assertNotNull(project.getProjectUsersWithRole(PROJECT_MANAGER)); assertTrue(project.getProjectUsersWithRole(PROJECT_MANAGER).isEmpty()); } |
LegacyMonitoringOfficerPermissionRules extends BasePermissionRules { @PermissionRule( value = "ASSIGN_MONITORING_OFFICER", description = "Internal users can assign Monitoring Officers on any Project") public boolean internalUsersCanAssignMonitoringOfficersForAnyProject(ProjectResource project, UserResource user) { return isInternal(user) && isProjectActive(project.getId()); } @PermissionRule( value = "ASSIGN_MONITORING_OFFICER", description = "Internal users can assign Monitoring Officers on any Project") boolean internalUsersCanAssignMonitoringOfficersForAnyProject(ProjectResource project, UserResource user); } | @Test public void internalUsersCanEditMonitoringOfficersOnProjects() { ProjectResource project = newProjectResource() .withProjectState(SETUP) .build(); when(projectProcessRepository.findOneByTargetId(project.getId())).thenReturn(projectProcess); allGlobalRoleUsers.forEach(user -> { if (allInternalUsers.contains(user)) { assertTrue(rules.internalUsersCanAssignMonitoringOfficersForAnyProject(project, user)); } else { assertFalse(rules.internalUsersCanAssignMonitoringOfficersForAnyProject(project, user)); } }); } |
LegacyMonitoringOfficerController { @GetMapping("/{projectId}/monitoring-officer") public RestResult<LegacyMonitoringOfficerResource> getMonitoringOfficer(@PathVariable("projectId") final Long projectId) { return monitoringOfficerService.getMonitoringOfficer(projectId).toGetResponse(); } @GetMapping("/{projectId}/monitoring-officer") RestResult<LegacyMonitoringOfficerResource> getMonitoringOfficer(@PathVariable("projectId") final Long projectId); @PutMapping("/{projectId}/monitoring-officer") RestResult<Void> saveMonitoringOfficer(@PathVariable("projectId") final Long projectId,
@RequestBody @Valid final LegacyMonitoringOfficerResource monitoringOfficerResource); } | @Test public void getMonitoringOfficer() throws Exception { LegacyMonitoringOfficerResource monitoringOfficer = newLegacyMonitoringOfficerResource().build(); when(monitoringOfficerServiceMock.getMonitoringOfficer(123L)).thenReturn(serviceSuccess(monitoringOfficer)); mockMvc.perform(get("/project/{projectId}/monitoring-officer", 123L)). andExpect(status().isOk()). andExpect(content().json(toJson(monitoringOfficer))); } |
LegacyMonitoringOfficerController { @PutMapping("/{projectId}/monitoring-officer") public RestResult<Void> saveMonitoringOfficer(@PathVariable("projectId") final Long projectId, @RequestBody @Valid final LegacyMonitoringOfficerResource monitoringOfficerResource) { ServiceResult<Boolean> result = monitoringOfficerService.saveMonitoringOfficer(projectId, monitoringOfficerResource) .andOnSuccessReturn(r -> r.isMonitoringOfficerSaved()); if (result.isSuccess() && result.getSuccess()) { return monitoringOfficerService.notifyStakeholdersOfMonitoringOfficerChange(monitoringOfficerResource).toPutResponse(); } return result.toPutResponse(); } @GetMapping("/{projectId}/monitoring-officer") RestResult<LegacyMonitoringOfficerResource> getMonitoringOfficer(@PathVariable("projectId") final Long projectId); @PutMapping("/{projectId}/monitoring-officer") RestResult<Void> saveMonitoringOfficer(@PathVariable("projectId") final Long projectId,
@RequestBody @Valid final LegacyMonitoringOfficerResource monitoringOfficerResource); } | @Test public void saveMOWhenErrorWhistSaving() throws Exception { Long projectId = 1L; when(monitoringOfficerServiceMock.saveMonitoringOfficer(projectId, monitoringOfficerResource)). thenReturn(serviceFailure(new Error(PROJECT_SETUP_MONITORING_OFFICER_CANNOT_BE_ASSIGNED_UNTIL_PROJECT_DETAILS_SUBMITTED))); mockMvc.perform(put("/project/{projectId}/monitoring-officer", projectId) .contentType(APPLICATION_JSON) .content(toJson(monitoringOfficerResource))) .andExpect(status().isBadRequest()); verify(monitoringOfficerServiceMock).saveMonitoringOfficer(projectId, monitoringOfficerResource); verify(monitoringOfficerServiceMock, never()).notifyStakeholdersOfMonitoringOfficerChange(monitoringOfficerResource); }
@Test public void saveMOWhenUnableToSendNotifications() throws Exception { Long projectId = 1L; SaveMonitoringOfficerResult successResult = new SaveMonitoringOfficerResult(); when(monitoringOfficerServiceMock.saveMonitoringOfficer(projectId, monitoringOfficerResource)).thenReturn(serviceSuccess(successResult)); when(monitoringOfficerServiceMock.notifyStakeholdersOfMonitoringOfficerChange(monitoringOfficerResource)). thenReturn(serviceFailure(new Error(NOTIFICATIONS_UNABLE_TO_SEND_MULTIPLE))); mockMvc.perform(put("/project/{projectId}/monitoring-officer", projectId) .contentType(APPLICATION_JSON) .content(toJson(monitoringOfficerResource))) .andExpect(status().isInternalServerError()); verify(monitoringOfficerServiceMock).saveMonitoringOfficer(projectId, monitoringOfficerResource); verify(monitoringOfficerServiceMock).notifyStakeholdersOfMonitoringOfficerChange(monitoringOfficerResource); }
@Test public void saveMonitoringOfficer() throws Exception { Long projectId = 1L; SaveMonitoringOfficerResult successResult = new SaveMonitoringOfficerResult(); when(monitoringOfficerServiceMock.saveMonitoringOfficer(projectId, monitoringOfficerResource)).thenReturn(serviceSuccess(successResult)); when(monitoringOfficerServiceMock.notifyStakeholdersOfMonitoringOfficerChange(monitoringOfficerResource)). thenReturn(serviceSuccess()); mockMvc.perform(put("/project/{projectId}/monitoring-officer", projectId) .contentType(APPLICATION_JSON) .content(toJson(monitoringOfficerResource))) .andExpect(status().isOk()); verify(monitoringOfficerServiceMock).saveMonitoringOfficer(projectId, monitoringOfficerResource); verify(monitoringOfficerServiceMock).notifyStakeholdersOfMonitoringOfficerChange(monitoringOfficerResource); }
@Test public void saveMonitoringOfficerWithoutSendingNotifications() throws Exception { Long projectId = 1L; SaveMonitoringOfficerResult successResult = new SaveMonitoringOfficerResult(); successResult.setMonitoringOfficerSaved(false); when(monitoringOfficerServiceMock.saveMonitoringOfficer(projectId, monitoringOfficerResource)).thenReturn(serviceSuccess(successResult)); when(monitoringOfficerServiceMock.notifyStakeholdersOfMonitoringOfficerChange(monitoringOfficerResource)). thenReturn(serviceSuccess()); mockMvc.perform(put("/project/{projectId}/monitoring-officer", projectId) .contentType(APPLICATION_JSON) .content(toJson(monitoringOfficerResource))) .andExpect(status().isOk()); verify(monitoringOfficerServiceMock).saveMonitoringOfficer(projectId, monitoringOfficerResource); verify(monitoringOfficerServiceMock, never()).notifyStakeholdersOfMonitoringOfficerChange(monitoringOfficerResource); }
@Test public void saveMonitoringOfficerWithBindExceptions() throws Exception { Long projectId = 1L; LegacyMonitoringOfficerResource monitoringOfficerResource = LegacyMonitoringOfficerResourceBuilder.newLegacyMonitoringOfficerResource() .withId(null) .withProject(projectId) .withFirstName("") .withLastName("") .withEmail("abc") .withPhoneNumber("hello") .build(); Error firstNameError = fieldError("firstName", "", "validation.standard.firstname.required", ""); Error lastNameError = fieldError("lastName", "", "validation.standard.lastname.required", ""); Error emailError = fieldError("email", "abc", "validation.standard.email.format", "", "", "^$|^[a-zA-Z0-9._%+-^[^{}|]*$]+@[a-zA-Z0-9.-^[^{}|]*$]+\\.[a-zA-Z^[^0-9{}|]*$]{2,}$"); Error phoneNumberError = fieldError("phoneNumber", "hello", "validation.standard.phonenumber.format", "", "", "^[\\\\)\\\\(\\\\+\\s-]*(?:\\d[\\\\)\\\\(\\\\+\\s-]*){8,20}$"); MvcResult result = mockMvc.perform(put("/project/{projectId}/monitoring-officer", projectId) .contentType(APPLICATION_JSON) .content(toJson(monitoringOfficerResource))) .andExpect(status().isNotAcceptable()) .andReturn(); RestErrorResponse response = fromJson(result.getResponse().getContentAsString(), RestErrorResponse.class); assertEquals(6, response.getErrors().size()); asList(firstNameError, lastNameError, emailError, phoneNumberError).forEach(e -> { String fieldName = e.getFieldName(); String errorKey = e.getErrorKey(); List<Error> matchingErrors = simpleFilter(response.getErrors(), error -> fieldName.equals(error.getFieldName()) && errorKey.equals(error.getErrorKey()) && e.getArguments().containsAll(error.getArguments())); assertEquals(1, matchingErrors.size()); }); verify(monitoringOfficerServiceMock, never()).saveMonitoringOfficer(projectId, monitoringOfficerResource); } |
LegacyMonitoringOfficerServiceImpl extends AbstractProjectServiceImpl implements LegacyMonitoringOfficerService { @Override @Transactional public ServiceResult<SaveMonitoringOfficerResult> saveMonitoringOfficer(final Long projectId, final LegacyMonitoringOfficerResource monitoringOfficerResource) { return validateMonitoringOfficer(projectId, monitoringOfficerResource). andOnSuccess(() -> validateInMonitoringOfficerAssignableState(projectId)). andOnSuccess(() -> saveMonitoringOfficer(monitoringOfficerResource)); } @Override ServiceResult<LegacyMonitoringOfficerResource> getMonitoringOfficer(Long projectId); @Override @Transactional ServiceResult<SaveMonitoringOfficerResult> saveMonitoringOfficer(final Long projectId, final LegacyMonitoringOfficerResource monitoringOfficerResource); @Override @Transactional ServiceResult<Void> notifyStakeholdersOfMonitoringOfficerChange(LegacyMonitoringOfficerResource monitoringOfficer); } | @Test public void testSaveMOWithDiffProjectIdInURLAndMOResource() { Long projectid = 1L; LegacyMonitoringOfficerResource monitoringOfficerResource = newLegacyMonitoringOfficerResource() .withProject(3L) .withFirstName("abc") .withLastName("xyz") .withEmail("[email protected]") .withPhoneNumber("078323455") .build(); ServiceResult<SaveMonitoringOfficerResult> result = service.saveMonitoringOfficer(projectid, monitoringOfficerResource); assertTrue(result.getFailure().is(PROJECT_SETUP_PROJECT_ID_IN_URL_MUST_MATCH_PROJECT_ID_IN_MONITORING_OFFICER_RESOURCE)); }
@Test public void testSaveMOWhenProjectDetailsNotYetSubmitted() { Long projectid = 1L; Project projectInDB = newProject().withId(1L).build(); when(projectRepositoryMock.findById(projectid)).thenReturn(Optional.of(projectInDB)); ServiceResult<SaveMonitoringOfficerResult> result = service.saveMonitoringOfficer(projectid, monitoringOfficerResource); assertTrue(result.getFailure().is(PROJECT_SETUP_MONITORING_OFFICER_CANNOT_BE_ASSIGNED_UNTIL_PROJECT_DETAILS_SUBMITTED)); }
@Test public void testSaveMOWhenMOExistsForAProject() { Long projectid = 1L; LegacyMonitoringOfficer monitoringOfficerInDB = LegacyMonitoringOfficerBuilder.newLegacyMonitoringOfficer() .withFirstName("def") .withLastName("klm") .withEmail("[email protected]") .withPhoneNumber("079237439") .build(); Project projectInDB = newProject().withId(1L).build(); when(projectRepositoryMock.findById(projectid)).thenReturn(Optional.of(projectInDB)); when(monitoringOfficerRepositoryMock.findOneByProjectId(monitoringOfficerResource.getProject())).thenReturn(monitoringOfficerInDB); when(projectDetailsWorkflowHandlerMock.isSubmitted(projectInDB)).thenReturn(true); ServiceResult<SaveMonitoringOfficerResult> result = service.saveMonitoringOfficer(projectid, monitoringOfficerResource); Assert.assertEquals("First name of MO in DB should be updated with the value from MO Resource", monitoringOfficerInDB.getFirstName(), monitoringOfficerResource.getFirstName()); Assert.assertEquals("Last name of MO in DB should be updated with the value from MO Resource", monitoringOfficerInDB.getLastName(), monitoringOfficerResource.getLastName()); Assert.assertEquals("Email of MO in DB should be updated with the value from MO Resource", monitoringOfficerInDB.getEmail(), monitoringOfficerResource.getEmail()); Assert.assertEquals("Phone number of MO in DB should be updated with the value from MO Resource", monitoringOfficerInDB.getPhoneNumber(), monitoringOfficerResource.getPhoneNumber()); Optional<SaveMonitoringOfficerResult> successResult = result.getOptionalSuccessObject(); assertTrue(successResult.isPresent()); assertTrue(successResult.get().isMonitoringOfficerSaved()); assertTrue(result.isSuccess()); }
@Test public void testSaveMOWhenMODetailsRemainsTheSame() { Long projectId = 1L; LegacyMonitoringOfficer monitoringOfficerInDB = LegacyMonitoringOfficerBuilder.newLegacyMonitoringOfficer() .withFirstName("abc") .withLastName("xyz") .withEmail("[email protected]") .withPhoneNumber("078323455") .build(); Project projectInDB = newProject().withId(1L).build(); when(projectRepositoryMock.findById(projectId)).thenReturn(Optional.of(projectInDB)); when(monitoringOfficerRepositoryMock.findOneByProjectId(monitoringOfficerResource.getProject())).thenReturn(monitoringOfficerInDB); when(projectDetailsWorkflowHandlerMock.isSubmitted(projectInDB)).thenReturn(true); ServiceResult<SaveMonitoringOfficerResult> result = service.saveMonitoringOfficer(projectId, monitoringOfficerResource); Optional<SaveMonitoringOfficerResult> successResult = result.getOptionalSuccessObject(); assertTrue(successResult.isPresent()); assertFalse(successResult.get().isMonitoringOfficerSaved()); assertTrue(result.isSuccess()); }
@Test public void testSaveMOWhenMODoesNotExistForAProject() { Long projectid = 1L; Project projectInDB = newProject().withId(1L).build(); when(projectRepositoryMock.findById(projectid)).thenReturn(Optional.of(projectInDB)); when(monitoringOfficerRepositoryMock.findOneByProjectId(monitoringOfficerResource.getProject())).thenReturn(null); when(projectDetailsWorkflowHandlerMock.isSubmitted(projectInDB)).thenReturn(true); ServiceResult<SaveMonitoringOfficerResult> result = service.saveMonitoringOfficer(projectid, monitoringOfficerResource); Optional<SaveMonitoringOfficerResult> successResult = result.getOptionalSuccessObject(); assertTrue(successResult.isPresent()); assertTrue(successResult.get().isMonitoringOfficerSaved()); assertTrue(result.isSuccess()); } |
RoleProfileStatusController { @GetMapping("/{userId}/role-profile-status") public RestResult<List<RoleProfileStatusResource>> findByUserId(@PathVariable long userId) { return roleProfileStatusService.findByUserId(userId).toGetResponse(); } @GetMapping("/{userId}/role-profile-status/{profileRole}") RestResult<RoleProfileStatusResource> findByUserIdAndProfileRole(@PathVariable long userId, @PathVariable final ProfileRole profileRole); @GetMapping("/{userId}/role-profile-status") RestResult<List<RoleProfileStatusResource>> findByUserId(@PathVariable long userId); @PutMapping("/{userId}/role-profile-status") RestResult<Void> updateUserStatus(@PathVariable long userId, @RequestBody RoleProfileStatusResource roleProfileStatusResource); @GetMapping("/role-profile-status/{roleProfileState}/{profileRole}") RestResult<UserPageResource> getByRoleProfileStatus(@PathVariable RoleProfileState roleProfileState,
@PathVariable ProfileRole profileRole,
@RequestParam(required = false) String filter,
@RequestParam(defaultValue = DEFAULT_PAGE_NUMBER) int page,
@RequestParam(defaultValue = DEFAULT_PAGE_SIZE) int size); static final Sort DEFAULT_SORT; } | @Test public void findByUserId() throws Exception { long userId = 1L; List<RoleProfileStatusResource> roleProfileStatusResources = newRoleProfileStatusResource().withUserId(userId).build(1); when(roleProfileStatusServiceMock.findByUserId(userId)).thenReturn(serviceSuccess(roleProfileStatusResources)); mockMvc.perform(get("/user/{id}/role-profile-status", userId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(roleProfileStatusResources))); } |
LegacyMonitoringOfficerServiceImpl extends AbstractProjectServiceImpl implements LegacyMonitoringOfficerService { @Override public ServiceResult<LegacyMonitoringOfficerResource> getMonitoringOfficer(Long projectId) { return getExistingMonitoringOfficerForProject(projectId).andOnSuccessReturn(legacyMonitoringOfficerMapper::mapToResource); } @Override ServiceResult<LegacyMonitoringOfficerResource> getMonitoringOfficer(Long projectId); @Override @Transactional ServiceResult<SaveMonitoringOfficerResult> saveMonitoringOfficer(final Long projectId, final LegacyMonitoringOfficerResource monitoringOfficerResource); @Override @Transactional ServiceResult<Void> notifyStakeholdersOfMonitoringOfficerChange(LegacyMonitoringOfficerResource monitoringOfficer); } | @Test public void testGetMonitoringOfficerWhenMODoesNotExistInDB() { Long projectid = 1L; ServiceResult<LegacyMonitoringOfficerResource> result = service.getMonitoringOfficer(projectid); String errorKey = result.getFailure().getErrors().get(0).getErrorKey(); Assert.assertEquals(CommonFailureKeys.GENERAL_NOT_FOUND.name(), errorKey); }
@Test public void testGetMonitoringOfficerWhenMOExistsInDB() { Long projectid = 1L; LegacyMonitoringOfficer monitoringOfficerInDB = LegacyMonitoringOfficerBuilder.newLegacyMonitoringOfficer() .withFirstName("def") .withLastName("klm") .withEmail("[email protected]") .withPhoneNumber("079237439") .build(); when(monitoringOfficerRepositoryMock.findOneByProjectId(projectid)).thenReturn(monitoringOfficerInDB); ServiceResult<LegacyMonitoringOfficerResource> result = service.getMonitoringOfficer(projectid); assertTrue(result.isSuccess()); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") public boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user){ return isInternalAdmin(user); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void internalAdminTeamCanViewCompetitionStatus() { allGlobalRoleUsers.forEach(user -> { if (isInternalAdmin(user)) { assertTrue(rules.internalAdminTeamCanViewCompetitionStatus(newProjectResource().build(), user)); } else { assertFalse(rules.internalAdminTeamCanViewCompetitionStatus(newProjectResource().build(), user)); } }); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") public boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user){ return isSupport(user); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void supportCanViewCompetitionStatus() { allGlobalRoleUsers.forEach(user -> { if (isSupport(user)) { assertTrue(rules.supportCanViewCompetitionStatus(newProjectResource().build(), user)); } else { assertFalse(rules.supportCanViewCompetitionStatus(newProjectResource().build(), user)); } }); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") public boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user){ Application application = applicationRepository.findById(project.getApplication()).get(); return userIsInnovationLeadOnCompetition(application.getCompetition().getId(), user.getId()); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void assignedInnovationLeadCanViewProjectStatus() { assertTrue(rules.assignedInnovationLeadCanViewSPStatus(projectResource1, innovationLeadUserResourceOnProject1)); assertFalse(rules.assignedInnovationLeadCanViewSPStatus(projectResource1, innovationLeadUser())); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") public boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user){ Application application = applicationRepository.findById(project.getApplication()).get(); return userIsStakeholderInCompetition(application.getCompetition().getId(), user.getId()); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void assignedStakeholderCanViewSPStatus() { when(stakeholderRepository.existsByCompetitionIdAndUserId(competition.getId(), stakeholderUserResourceOnCompetition.getId())).thenReturn(true); assertTrue(rules.assignedStakeholderCanViewSPStatus(projectResource1, stakeholderUserResourceOnCompetition)); assertFalse(rules.assignedStakeholderCanViewSPStatus(projectResource1, stakeholderUser())); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") public boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user) { return isProjectManager(projectCompositeId.id(), user.getId()) && isProjectActive(projectCompositeId.id()); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void projectManagerCanCompleteSpendProfile() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); setUpUserAsProjectManager(project, user); assertTrue(rules.projectManagerCanCompleteSpendProfile(ProjectCompositeId.id(project.getId()), user)); } |
RoleProfileStatusController { @GetMapping("/{userId}/role-profile-status/{profileRole}") public RestResult<RoleProfileStatusResource> findByUserIdAndProfileRole(@PathVariable long userId, @PathVariable final ProfileRole profileRole) { return roleProfileStatusService.findByUserIdAndProfileRole(userId, profileRole).toGetResponse(); } @GetMapping("/{userId}/role-profile-status/{profileRole}") RestResult<RoleProfileStatusResource> findByUserIdAndProfileRole(@PathVariable long userId, @PathVariable final ProfileRole profileRole); @GetMapping("/{userId}/role-profile-status") RestResult<List<RoleProfileStatusResource>> findByUserId(@PathVariable long userId); @PutMapping("/{userId}/role-profile-status") RestResult<Void> updateUserStatus(@PathVariable long userId, @RequestBody RoleProfileStatusResource roleProfileStatusResource); @GetMapping("/role-profile-status/{roleProfileState}/{profileRole}") RestResult<UserPageResource> getByRoleProfileStatus(@PathVariable RoleProfileState roleProfileState,
@PathVariable ProfileRole profileRole,
@RequestParam(required = false) String filter,
@RequestParam(defaultValue = DEFAULT_PAGE_NUMBER) int page,
@RequestParam(defaultValue = DEFAULT_PAGE_SIZE) int size); static final Sort DEFAULT_SORT; } | @Test public void findByUserIdAndProfileRole() throws Exception { long userId = 1L; ProfileRole profileRole = ProfileRole.ASSESSOR; RoleProfileStatusResource roleProfileStatusResource = newRoleProfileStatusResource().withUserId(userId).build(); when(roleProfileStatusServiceMock.findByUserIdAndProfileRole(userId, profileRole)).thenReturn(serviceSuccess(roleProfileStatusResource)); mockMvc.perform(get("/user/{id}/role-profile-status/{profileRole}", userId, profileRole)) .andExpect(status().isOk()) .andExpect(content().json(toJson(roleProfileStatusResource))); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") public boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) { return isLeadPartner(projectOrganisationCompositeId.getProjectId(), user.getId()) && isProjectActive(projectOrganisationCompositeId.getProjectId()); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void leadPartnerCanIncompleteAnySpendProfile() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(project.getId(), newOrganisation().build().getId()); setupUserAsLeadPartner(project, user); assertTrue(rules.leadPartnerCanMarkSpendProfileIncomplete(projectOrganisationCompositeId, user)); }
@Test public void nonLeadPartnerCannotIncompleteSpendProfile() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(project.getId(), newOrganisation().build().getId()); setupUserNotAsLeadPartner(project, user); assertFalse(rules.leadPartnerCanMarkSpendProfileIncomplete(projectOrganisationCompositeId, user)); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") public boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) { return isLeadPartner(projectOrganisationCompositeId.getProjectId(), user.getId()); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void leadPartnerCanViewAnySpendProfileData() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(project.getId(), newOrganisation().build().getId()); setupUserAsLeadPartner(project, user); assertTrue(rules.leadPartnerCanViewAnySpendProfileData(projectOrganisationCompositeId, user)); }
@Test public void userNotLeadPartnerCannotViewSpendProfile() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(project.getId(), newOrganisation().build().getId()); setupUserNotAsLeadPartner(project, user); assertFalse(rules.leadPartnerCanViewAnySpendProfileData(projectOrganisationCompositeId, user)); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") public boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) { return isMonitoringOfficer(projectOrganisationCompositeId.getProjectId(), user.getId()); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void monitoringOfficerCanViewAnySpendProfileData() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(project.getId(), newOrganisation().build().getId()); setupUserAsMonitoringOfficer(project, user); assertTrue(rules.monitoringOfficerCanViewProjectsSpendProfileData(projectOrganisationCompositeId, user)); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") public boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) { return partnerBelongsToOrganisation(projectOrganisationCompositeId.getProjectId(), user.getId(), projectOrganisationCompositeId.getOrganisationId()); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void partnersCanViewTheirOwnSpendProfileData() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); OrganisationResource org = newOrganisationResource().build(); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(project.getId(), org.getId()); setupUserAsPartner(project, user, org); assertTrue(rules.partnersCanViewTheirOwnSpendProfileData(projectOrganisationCompositeId, user)); setupUserNotAsPartner(project, user, org); assertFalse(rules.partnersCanViewTheirOwnSpendProfileData(projectOrganisationCompositeId, user)); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") public boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) { return isProjectFinanceUser(user); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void projectFinanceUserCanViewAnySpendProfileData() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(1L, newOrganisation().build().getId()); allGlobalRoleUsers.forEach(user -> { if (user.equals(projectFinanceUser())) { assertTrue(rules.projectFinanceUserCanViewAnySpendProfileData(projectOrganisationCompositeId, user)); } else { assertFalse(rules.projectFinanceUserCanViewAnySpendProfileData(projectOrganisationCompositeId, user)); } }); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") public boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) { return partnerBelongsToOrganisation(projectOrganisationCompositeId.getProjectId(), user.getId(), projectOrganisationCompositeId.getOrganisationId()); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void partnersCanViewTheirOwnSpendProfileCsv() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); OrganisationResource org = newOrganisationResource().build(); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(project.getId(), org.getId()); setupUserAsPartner(project, user, org); assertTrue(rules.partnersCanViewTheirOwnSpendProfileCsv(projectOrganisationCompositeId, user)); setupUserNotAsPartner(project, user, org); assertFalse(rules.partnersCanViewTheirOwnSpendProfileCsv(projectOrganisationCompositeId, user)); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") public boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) { return isInternalAdmin(user); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void internalAdminUsersCanSeeSpendProfileCsv() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(1L, newOrganisation().build().getId()); allGlobalRoleUsers.forEach(user -> { if (isInternalAdmin(user)) { assertTrue(rules.internalAdminUsersCanSeeSpendProfileCsv(projectOrganisationCompositeId, user)); } else { assertFalse(rules.internalAdminUsersCanSeeSpendProfileCsv(projectOrganisationCompositeId, user)); } }); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") public boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) { return isSupport(user); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void supportUsersCanSeeSpendProfileCsv() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(1L, newOrganisation().build().getId()); allGlobalRoleUsers.forEach(user -> { if (isSupport(user)) { assertTrue(rules.supportUsersCanSeeSpendProfileCsv(projectOrganisationCompositeId, user)); } else { assertFalse(rules.supportUsersCanSeeSpendProfileCsv(projectOrganisationCompositeId, user)); } }); } |
RoleProfileStatusController { @PutMapping("/{userId}/role-profile-status") public RestResult<Void> updateUserStatus(@PathVariable long userId, @RequestBody RoleProfileStatusResource roleProfileStatusResource) { return roleProfileStatusService.updateUserStatus(userId, roleProfileStatusResource).toPutResponse(); } @GetMapping("/{userId}/role-profile-status/{profileRole}") RestResult<RoleProfileStatusResource> findByUserIdAndProfileRole(@PathVariable long userId, @PathVariable final ProfileRole profileRole); @GetMapping("/{userId}/role-profile-status") RestResult<List<RoleProfileStatusResource>> findByUserId(@PathVariable long userId); @PutMapping("/{userId}/role-profile-status") RestResult<Void> updateUserStatus(@PathVariable long userId, @RequestBody RoleProfileStatusResource roleProfileStatusResource); @GetMapping("/role-profile-status/{roleProfileState}/{profileRole}") RestResult<UserPageResource> getByRoleProfileStatus(@PathVariable RoleProfileState roleProfileState,
@PathVariable ProfileRole profileRole,
@RequestParam(required = false) String filter,
@RequestParam(defaultValue = DEFAULT_PAGE_NUMBER) int page,
@RequestParam(defaultValue = DEFAULT_PAGE_SIZE) int size); static final Sort DEFAULT_SORT; } | @Test public void updateUserStatus() throws Exception { long userId = 1L; RoleProfileStatusResource roleProfileStatusResource = new RoleProfileStatusResource(); when(roleProfileStatusServiceMock.updateUserStatus(anyLong(), any(RoleProfileStatusResource.class))).thenReturn(serviceSuccess()); mockMvc.perform(put("/user/{id}/role-profile-status", userId) .contentType(MediaType.APPLICATION_JSON) .content(toJson(roleProfileStatusResource))) .andExpect(status().isOk()); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") public boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) { Project project = projectRepository.findById(projectOrganisationCompositeId.getProjectId()).get(); return userIsStakeholderInCompetition(project.getApplication().getCompetition().getId(), user.getId()); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void stakeholdersCanSeeSpendProfileCsv() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectResource1.getId(), newOrganisation().build().getId()); when(stakeholderRepository.existsByCompetitionIdAndUserId(competition.getId(), stakeholderUserResourceOnCompetition.getId())).thenReturn(true); assertTrue(rules.stakeholdersCanSeeSpendProfileCsv(projectOrganisationCompositeId, stakeholderUserResourceOnCompetition)); assertFalse(rules.stakeholdersCanSeeSpendProfileCsv(projectOrganisationCompositeId, stakeholderUser())); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") public boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) { return isLeadPartner(projectOrganisationCompositeId.getProjectId(), user.getId()); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void leadPartnerCanViewAnySpendProfileCsv() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(project.getId(), newOrganisation().build().getId()); setupUserAsLeadPartner(project, user); assertTrue(rules.leadPartnerCanViewAnySpendProfileCsv(projectOrganisationCompositeId, user)); setupUserNotAsLeadPartner(project, user); assertFalse(rules.leadPartnerCanViewAnySpendProfileCsv(projectOrganisationCompositeId, user)); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") public boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) { return partnerBelongsToOrganisation(projectOrganisationCompositeId.getProjectId(), user.getId(), projectOrganisationCompositeId.getOrganisationId()) && isProjectActive(projectOrganisationCompositeId.getProjectId()); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void partnersCanEditTheirOwnSpendProfileData() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); OrganisationResource org = newOrganisationResource().build(); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(project.getId(), org.getId()); setupUserAsPartner(project, user, org); assertTrue(rules.partnersCanEditTheirOwnSpendProfileData(projectOrganisationCompositeId, user)); setupUserNotAsPartner(project, user, org); assertFalse(rules.partnersCanEditTheirOwnSpendProfileData(projectOrganisationCompositeId, user)); } |
SpendProfilePermissionRules extends BasePermissionRules { @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") public boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) { return partnerBelongsToOrganisation(projectOrganisationCompositeId.getProjectId(), user.getId(), projectOrganisationCompositeId.getOrganisationId()) && isProjectActive(projectOrganisationCompositeId.getProjectId()); } @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Internal admin team (comp admin and project finance) users can get the approved status of a Spend Profile for any Project") boolean internalAdminTeamCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Support users can get the approved status of a Spend Profile for any Project") boolean supportCanViewCompetitionStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Innovation lead users can get the approved status of a Spend Profile for any Project") boolean assignedInnovationLeadCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule(value = "VIEW_SPEND_PROFILE_STATUS", description = "Stakeholders can get the approved status of a Spend Profile for any Project") boolean assignedStakeholderCanViewSPStatus(ProjectResource project, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Project Finance Users can view their own Spend Profile data") boolean projectFinanceUserCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Lead partner view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE", description = "Monitoring officer can view Spend Profile data for the projects they are assigned to") boolean monitoringOfficerCanViewProjectsSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Partners can view their own Spend Profile data") boolean partnersCanViewTheirOwnSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "All internal admin users can view Spend Profile data of any applicant") boolean internalAdminUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Support users can view Spend Profile data of any applicant") boolean supportUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Innovation lead users can view Spend Profile data for project on competition assigned to them") boolean innovationLeadUsersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Stakeholders can view Spend Profile data for project on competition assigned to them") boolean stakeholdersCanSeeSpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "VIEW_SPEND_PROFILE_CSV", description = "Lead partner can view Spend Profile data") boolean leadPartnerCanViewAnySpendProfileCsv(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule( value = "EDIT_SPEND_PROFILE", description = "Partners can edit their own Spend Profile data") boolean partnersCanEditTheirOwnSpendProfileData(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_COMPLETE", description = "Any partner belonging to organisation can mark its spend profile as complete") boolean partnersCanMarkSpendProfileAsComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "Any lead partner can mark partners spend profiles as incomplete") boolean leadPartnerCanMarkSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "COMPLETE_SPEND_PROFILE_REVIEW", description = "Only a Project Manager can complete the project's spend profiles review") boolean projectManagerCanCompleteSpendProfile(ProjectCompositeId projectCompositeId, UserResource user); } | @Test public void partnersCanMarkSpendProfileAsComplete() { ProjectResource project = newProjectResource().build(); UserResource user = newUserResource().build(); OrganisationResource org = newOrganisationResource().build(); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(project.getId(), org.getId()); setupUserAsPartner(project, user, org); assertTrue(rules.partnersCanMarkSpendProfileAsComplete(projectOrganisationCompositeId, user)); setupUserNotAsPartner(project, user, org); assertFalse(rules.partnersCanMarkSpendProfileAsComplete(projectOrganisationCompositeId, user)); } |
SpendProfileController { @PostMapping("/spend-profile/generate") public RestResult<Void> generateSpendProfile(@PathVariable("projectId") final Long projectId) { return spendProfileService.generateSpendProfile(projectId).toPostCreateResponse(); } @PostMapping("/spend-profile/generate") RestResult<Void> generateSpendProfile(@PathVariable("projectId") final Long projectId); @PostMapping("/spend-profile/approval/{approvalType}") RestResult<Void> approveOrRejectSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("approvalType") final ApprovalType approvalType); @GetMapping("/spend-profile/approval") RestResult<ApprovalType> getSpendProfileStatusByProjectId(@PathVariable("projectId") final Long projectId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-table") RestResult<SpendProfileTableResource> getSpendProfileTable(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-csv") RestResult<SpendProfileCSVResource> getSpendProfileCSV(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<SpendProfileResource> getSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<Void> saveSpendProfile(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId,
@RequestBody SpendProfileTableResource table); @PostMapping("/partner-organisation/{organisationId}/spend-profile/complete") RestResult<Void> markSpendProfileComplete(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile/incomplete") RestResult<Void> markSpendProfileIncomplete(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/complete-spend-profiles-review") RestResult<Void> completeSpendProfilesReview(@PathVariable("projectId") final Long projectId); @DeleteMapping("/spend-profile/reset") RestResult<Void> deleteSpendProfile(@PathVariable("projectId") final Long projectId); } | @Test public void generateSpendProfile() throws Exception { when(spendProfileService.generateSpendProfile(123L)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/123/spend-profile/generate")).andExpect(status().isCreated()); verify(spendProfileService).generateSpendProfile(123L); } |
SpendProfileController { @DeleteMapping("/spend-profile/reset") public RestResult<Void> deleteSpendProfile(@PathVariable("projectId") final Long projectId) { return spendProfileService.deleteSpendProfile(projectId).toDeleteResponse(); } @PostMapping("/spend-profile/generate") RestResult<Void> generateSpendProfile(@PathVariable("projectId") final Long projectId); @PostMapping("/spend-profile/approval/{approvalType}") RestResult<Void> approveOrRejectSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("approvalType") final ApprovalType approvalType); @GetMapping("/spend-profile/approval") RestResult<ApprovalType> getSpendProfileStatusByProjectId(@PathVariable("projectId") final Long projectId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-table") RestResult<SpendProfileTableResource> getSpendProfileTable(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-csv") RestResult<SpendProfileCSVResource> getSpendProfileCSV(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<SpendProfileResource> getSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<Void> saveSpendProfile(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId,
@RequestBody SpendProfileTableResource table); @PostMapping("/partner-organisation/{organisationId}/spend-profile/complete") RestResult<Void> markSpendProfileComplete(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile/incomplete") RestResult<Void> markSpendProfileIncomplete(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/complete-spend-profiles-review") RestResult<Void> completeSpendProfilesReview(@PathVariable("projectId") final Long projectId); @DeleteMapping("/spend-profile/reset") RestResult<Void> deleteSpendProfile(@PathVariable("projectId") final Long projectId); } | @Test public void deleteSpendProfile() throws Exception { long projectId = 123L; when(spendProfileService.deleteSpendProfile(projectId)).thenReturn(serviceSuccess()); mockMvc.perform(delete("/project/{projectId}/spend-profile/reset", projectId)) .andExpect(status().isNoContent()). andDo(document("project/{method-name}")); verify(spendProfileService).deleteSpendProfile(projectId); } |
SpendProfileController { @PostMapping("/partner-organisation/{organisationId}/spend-profile/complete") public RestResult<Void> markSpendProfileComplete(@PathVariable("projectId") final long projectId, @PathVariable("organisationId") final long organisationId) { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); return spendProfileService.markSpendProfileComplete(projectOrganisationCompositeId).toPostResponse(); } @PostMapping("/spend-profile/generate") RestResult<Void> generateSpendProfile(@PathVariable("projectId") final Long projectId); @PostMapping("/spend-profile/approval/{approvalType}") RestResult<Void> approveOrRejectSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("approvalType") final ApprovalType approvalType); @GetMapping("/spend-profile/approval") RestResult<ApprovalType> getSpendProfileStatusByProjectId(@PathVariable("projectId") final Long projectId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-table") RestResult<SpendProfileTableResource> getSpendProfileTable(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-csv") RestResult<SpendProfileCSVResource> getSpendProfileCSV(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<SpendProfileResource> getSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<Void> saveSpendProfile(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId,
@RequestBody SpendProfileTableResource table); @PostMapping("/partner-organisation/{organisationId}/spend-profile/complete") RestResult<Void> markSpendProfileComplete(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile/incomplete") RestResult<Void> markSpendProfileIncomplete(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/complete-spend-profiles-review") RestResult<Void> completeSpendProfilesReview(@PathVariable("projectId") final Long projectId); @DeleteMapping("/spend-profile/reset") RestResult<Void> deleteSpendProfile(@PathVariable("projectId") final Long projectId); } | @Test public void markSpendProfileComplete() throws Exception { final Long projectId = 1L; final Long organisationId = 1L; final SpendProfileTableResource table = new SpendProfileTableResource(); final ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); when(spendProfileService.markSpendProfileComplete(projectOrganisationCompositeId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/partner-organisation/{organisationId}/spend-profile/complete", projectId, organisationId, true).contentType(APPLICATION_JSON).content(toJson(table))) .andExpect(status().isOk()); verify(spendProfileService).markSpendProfileComplete(projectOrganisationCompositeId); } |
SpendProfileController { @PostMapping("/partner-organisation/{organisationId}/spend-profile/incomplete") public RestResult<Void> markSpendProfileIncomplete(@PathVariable("projectId") final Long projectId, @PathVariable("organisationId") final Long organisationId) { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); return spendProfileService.markSpendProfileIncomplete(projectOrganisationCompositeId).toPostResponse(); } @PostMapping("/spend-profile/generate") RestResult<Void> generateSpendProfile(@PathVariable("projectId") final Long projectId); @PostMapping("/spend-profile/approval/{approvalType}") RestResult<Void> approveOrRejectSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("approvalType") final ApprovalType approvalType); @GetMapping("/spend-profile/approval") RestResult<ApprovalType> getSpendProfileStatusByProjectId(@PathVariable("projectId") final Long projectId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-table") RestResult<SpendProfileTableResource> getSpendProfileTable(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-csv") RestResult<SpendProfileCSVResource> getSpendProfileCSV(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<SpendProfileResource> getSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<Void> saveSpendProfile(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId,
@RequestBody SpendProfileTableResource table); @PostMapping("/partner-organisation/{organisationId}/spend-profile/complete") RestResult<Void> markSpendProfileComplete(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile/incomplete") RestResult<Void> markSpendProfileIncomplete(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/complete-spend-profiles-review") RestResult<Void> completeSpendProfilesReview(@PathVariable("projectId") final Long projectId); @DeleteMapping("/spend-profile/reset") RestResult<Void> deleteSpendProfile(@PathVariable("projectId") final Long projectId); } | @Test public void markSpendProfileIncomplete() throws Exception { final Long projectId = 1L; final Long organisationId = 2L; final SpendProfileTableResource table = new SpendProfileTableResource(); final ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); when(spendProfileService.markSpendProfileIncomplete(projectOrganisationCompositeId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/partner-organisation/{organisationId}/spend-profile/incomplete", projectId, organisationId, true) .contentType(APPLICATION_JSON) .content(toJson(table))) .andExpect(status().isOk()); verify(spendProfileService).markSpendProfileIncomplete(projectOrganisationCompositeId); } |
SpendProfileController { @GetMapping("/partner-organisation/{organisationId}/spend-profile-table") public RestResult<SpendProfileTableResource> getSpendProfileTable(@PathVariable("projectId") final Long projectId, @PathVariable("organisationId") final Long organisationId) { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); return spendProfileService.getSpendProfileTable(projectOrganisationCompositeId).toGetResponse(); } @PostMapping("/spend-profile/generate") RestResult<Void> generateSpendProfile(@PathVariable("projectId") final Long projectId); @PostMapping("/spend-profile/approval/{approvalType}") RestResult<Void> approveOrRejectSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("approvalType") final ApprovalType approvalType); @GetMapping("/spend-profile/approval") RestResult<ApprovalType> getSpendProfileStatusByProjectId(@PathVariable("projectId") final Long projectId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-table") RestResult<SpendProfileTableResource> getSpendProfileTable(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-csv") RestResult<SpendProfileCSVResource> getSpendProfileCSV(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<SpendProfileResource> getSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<Void> saveSpendProfile(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId,
@RequestBody SpendProfileTableResource table); @PostMapping("/partner-organisation/{organisationId}/spend-profile/complete") RestResult<Void> markSpendProfileComplete(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile/incomplete") RestResult<Void> markSpendProfileIncomplete(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/complete-spend-profiles-review") RestResult<Void> completeSpendProfilesReview(@PathVariable("projectId") final Long projectId); @DeleteMapping("/spend-profile/reset") RestResult<Void> deleteSpendProfile(@PathVariable("projectId") final Long projectId); } | @Test public void getSpendProfileTable() throws Exception { final Long projectId = 1L; final Long organisationId = 1L; final ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); final SpendProfileTableResource expectedTable = new SpendProfileTableResource(); expectedTable.setMonths(asList( new LocalDateResource(2016, 2, 1), new LocalDateResource(2016, 3, 1), new LocalDateResource(2016, 4, 1) )); expectedTable.setEligibleCostPerCategoryMap(asMap( 1L, new BigDecimal("100"), 2L, new BigDecimal("150"), 3L, new BigDecimal("55"))); expectedTable.setMonthlyCostsPerCategoryMap(asMap( 1L, asList(new BigDecimal("30"), new BigDecimal("30"), new BigDecimal("40")), 2L, asList(new BigDecimal("70"), new BigDecimal("50"), new BigDecimal("60")), 3L, asList(new BigDecimal("50"), new BigDecimal("5"), new BigDecimal("0")))); when(spendProfileService.getSpendProfileTable(eq(projectOrganisationCompositeId))).thenReturn(serviceSuccess(expectedTable)); mockMvc.perform(get("/project/{projectId}/partner-organisation/{organisationId}/spend-profile-table", projectId, organisationId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedTable))); } |
SpendProfileController { @GetMapping("/partner-organisation/{organisationId}/spend-profile-csv") public RestResult<SpendProfileCSVResource> getSpendProfileCSV(@PathVariable("projectId") final Long projectId, @PathVariable("organisationId") final Long organisationId) { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); return spendProfileService.getSpendProfileCSV(projectOrganisationCompositeId).toGetResponse(); } @PostMapping("/spend-profile/generate") RestResult<Void> generateSpendProfile(@PathVariable("projectId") final Long projectId); @PostMapping("/spend-profile/approval/{approvalType}") RestResult<Void> approveOrRejectSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("approvalType") final ApprovalType approvalType); @GetMapping("/spend-profile/approval") RestResult<ApprovalType> getSpendProfileStatusByProjectId(@PathVariable("projectId") final Long projectId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-table") RestResult<SpendProfileTableResource> getSpendProfileTable(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-csv") RestResult<SpendProfileCSVResource> getSpendProfileCSV(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<SpendProfileResource> getSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<Void> saveSpendProfile(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId,
@RequestBody SpendProfileTableResource table); @PostMapping("/partner-organisation/{organisationId}/spend-profile/complete") RestResult<Void> markSpendProfileComplete(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile/incomplete") RestResult<Void> markSpendProfileIncomplete(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/complete-spend-profiles-review") RestResult<Void> completeSpendProfilesReview(@PathVariable("projectId") final Long projectId); @DeleteMapping("/spend-profile/reset") RestResult<Void> deleteSpendProfile(@PathVariable("projectId") final Long projectId); } | @Test public void getSpendProfileCsv() throws Exception { final Long projectId = 1L; final Long organisationId = 1L; final ProjectResource projectResource = newProjectResource() .withName("projectName1") .withTargetStartDate(LocalDate.of(2018, 3, 1)) .withDuration(3L) .withId(projectId) .build(); final ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); final SpendProfileTableResource expectedTable = buildSpendProfileTableResource(projectResource); final SpendProfileCSVResource expectedResource = new SpendProfileCSVResource(); expectedResource.setFileName("TEST_Spend_Profile_2016-10-30_10-11_12.csv"); expectedResource.setCsvData(generateTestCSVDataUsing(expectedTable)); when(spendProfileService.getSpendProfileCSV(projectOrganisationCompositeId)).thenReturn(serviceSuccess(expectedResource)); mockMvc.perform(get("/project/{projectId}/partner-organisation/{organisationId}/spend-profile-csv", projectId, organisationId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedResource))); } |
RoleProfileStatusController { @GetMapping("/role-profile-status/{roleProfileState}/{profileRole}") public RestResult<UserPageResource> getByRoleProfileStatus(@PathVariable RoleProfileState roleProfileState, @PathVariable ProfileRole profileRole, @RequestParam(required = false) String filter, @RequestParam(defaultValue = DEFAULT_PAGE_NUMBER) int page, @RequestParam(defaultValue = DEFAULT_PAGE_SIZE) int size) { return roleProfileStatusService.findByRoleProfile(roleProfileState, profileRole, filter, PageRequest.of(page, size, DEFAULT_SORT)) .toGetResponse(); } @GetMapping("/{userId}/role-profile-status/{profileRole}") RestResult<RoleProfileStatusResource> findByUserIdAndProfileRole(@PathVariable long userId, @PathVariable final ProfileRole profileRole); @GetMapping("/{userId}/role-profile-status") RestResult<List<RoleProfileStatusResource>> findByUserId(@PathVariable long userId); @PutMapping("/{userId}/role-profile-status") RestResult<Void> updateUserStatus(@PathVariable long userId, @RequestBody RoleProfileStatusResource roleProfileStatusResource); @GetMapping("/role-profile-status/{roleProfileState}/{profileRole}") RestResult<UserPageResource> getByRoleProfileStatus(@PathVariable RoleProfileState roleProfileState,
@PathVariable ProfileRole profileRole,
@RequestParam(required = false) String filter,
@RequestParam(defaultValue = DEFAULT_PAGE_NUMBER) int page,
@RequestParam(defaultValue = DEFAULT_PAGE_SIZE) int size); static final Sort DEFAULT_SORT; } | @Test public void getByRoleProfileStatus() throws Exception { RoleProfileState roleProfileState = RoleProfileState.ACTIVE; ProfileRole profileRole = ProfileRole.ASSESSOR; String filter = "filter"; UserPageResource userPageResource = new UserPageResource(); when(roleProfileStatusServiceMock.findByRoleProfile(eq(roleProfileState), eq(profileRole), eq(filter), any(PageRequest.class))) .thenReturn(serviceSuccess(userPageResource)); mockMvc.perform(RestDocumentationRequestBuilders.get("/user/role-profile-status/{roleProfileState}/{profileRole}", roleProfileState, profileRole) .param("filter", filter)) .andExpect(status().isOk()); } |
SpendProfileController { @GetMapping("/partner-organisation/{organisationId}/spend-profile") public RestResult<SpendProfileResource> getSpendProfile(@PathVariable("projectId") final Long projectId, @PathVariable("organisationId") final Long organisationId) { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); return spendProfileService.getSpendProfile(projectOrganisationCompositeId).toGetResponse(); } @PostMapping("/spend-profile/generate") RestResult<Void> generateSpendProfile(@PathVariable("projectId") final Long projectId); @PostMapping("/spend-profile/approval/{approvalType}") RestResult<Void> approveOrRejectSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("approvalType") final ApprovalType approvalType); @GetMapping("/spend-profile/approval") RestResult<ApprovalType> getSpendProfileStatusByProjectId(@PathVariable("projectId") final Long projectId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-table") RestResult<SpendProfileTableResource> getSpendProfileTable(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-csv") RestResult<SpendProfileCSVResource> getSpendProfileCSV(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<SpendProfileResource> getSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<Void> saveSpendProfile(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId,
@RequestBody SpendProfileTableResource table); @PostMapping("/partner-organisation/{organisationId}/spend-profile/complete") RestResult<Void> markSpendProfileComplete(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile/incomplete") RestResult<Void> markSpendProfileIncomplete(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/complete-spend-profiles-review") RestResult<Void> completeSpendProfilesReview(@PathVariable("projectId") final Long projectId); @DeleteMapping("/spend-profile/reset") RestResult<Void> deleteSpendProfile(@PathVariable("projectId") final Long projectId); } | @Test public void getSpendProfile() throws Exception { final Long projectId = 1L; final Long organisationId = 1L; final ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); final SpendProfileResource spendProfileResource = SpendProfileResourceBuilder.newSpendProfileResource().build(); when(spendProfileService.getSpendProfile(projectOrganisationCompositeId)).thenReturn(serviceSuccess(spendProfileResource)); mockMvc.perform(get("/project/{projectId}/partner-organisation/{organisationId}/spend-profile", projectId, organisationId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(spendProfileResource))); } |
SpendProfileController { @PostMapping("/partner-organisation/{organisationId}/spend-profile") public RestResult<Void> saveSpendProfile(@PathVariable("projectId") final long projectId, @PathVariable("organisationId") final long organisationId, @RequestBody SpendProfileTableResource table) { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); return spendProfileService.saveSpendProfile(projectOrganisationCompositeId, table).toPostResponse(); } @PostMapping("/spend-profile/generate") RestResult<Void> generateSpendProfile(@PathVariable("projectId") final Long projectId); @PostMapping("/spend-profile/approval/{approvalType}") RestResult<Void> approveOrRejectSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("approvalType") final ApprovalType approvalType); @GetMapping("/spend-profile/approval") RestResult<ApprovalType> getSpendProfileStatusByProjectId(@PathVariable("projectId") final Long projectId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-table") RestResult<SpendProfileTableResource> getSpendProfileTable(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-csv") RestResult<SpendProfileCSVResource> getSpendProfileCSV(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<SpendProfileResource> getSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<Void> saveSpendProfile(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId,
@RequestBody SpendProfileTableResource table); @PostMapping("/partner-organisation/{organisationId}/spend-profile/complete") RestResult<Void> markSpendProfileComplete(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile/incomplete") RestResult<Void> markSpendProfileIncomplete(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/complete-spend-profiles-review") RestResult<Void> completeSpendProfilesReview(@PathVariable("projectId") final Long projectId); @DeleteMapping("/spend-profile/reset") RestResult<Void> deleteSpendProfile(@PathVariable("projectId") final Long projectId); } | @Test public void saveSpendProfile() throws Exception { final Long projectId = 1L; final Long organisationId = 1L; final SpendProfileTableResource table = new SpendProfileTableResource(); final ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); when(spendProfileService.saveSpendProfile(projectOrganisationCompositeId, table)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/partner-organisation/{organisationId}/spend-profile", projectId, organisationId) .contentType(APPLICATION_JSON) .content(toJson(table))) .andExpect(status().isOk()); } |
SpendProfileController { @PostMapping("/complete-spend-profiles-review") public RestResult<Void> completeSpendProfilesReview(@PathVariable("projectId") final Long projectId) { return spendProfileService.completeSpendProfilesReview(projectId).toPostResponse(); } @PostMapping("/spend-profile/generate") RestResult<Void> generateSpendProfile(@PathVariable("projectId") final Long projectId); @PostMapping("/spend-profile/approval/{approvalType}") RestResult<Void> approveOrRejectSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("approvalType") final ApprovalType approvalType); @GetMapping("/spend-profile/approval") RestResult<ApprovalType> getSpendProfileStatusByProjectId(@PathVariable("projectId") final Long projectId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-table") RestResult<SpendProfileTableResource> getSpendProfileTable(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile-csv") RestResult<SpendProfileCSVResource> getSpendProfileCSV(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @GetMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<SpendProfileResource> getSpendProfile(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile") RestResult<Void> saveSpendProfile(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId,
@RequestBody SpendProfileTableResource table); @PostMapping("/partner-organisation/{organisationId}/spend-profile/complete") RestResult<Void> markSpendProfileComplete(@PathVariable("projectId") final long projectId,
@PathVariable("organisationId") final long organisationId); @PostMapping("/partner-organisation/{organisationId}/spend-profile/incomplete") RestResult<Void> markSpendProfileIncomplete(@PathVariable("projectId") final Long projectId,
@PathVariable("organisationId") final Long organisationId); @PostMapping("/complete-spend-profiles-review") RestResult<Void> completeSpendProfilesReview(@PathVariable("projectId") final Long projectId); @DeleteMapping("/spend-profile/reset") RestResult<Void> deleteSpendProfile(@PathVariable("projectId") final Long projectId); } | @Test public void completeSpendProfilesReview() throws Exception { final Long projectId = 1L; when(spendProfileService.completeSpendProfilesReview(projectId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/complete-spend-profiles-review", projectId)) .andExpect(status().isOk()); } |
SpendProfileValidationUtil { public Optional<ValidationMessages> validateSpendProfileTableResource(SpendProfileTableResource tableResource) { Optional<ValidationMessages> result = Optional.empty(); BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(tableResource, "spendProfileTable"); ValidationUtils.invokeValidator(spendProfileCostValidator, tableResource, bindingResult); if (bindingResult.hasErrors()) { ValidationMessages messages = new ValidationMessages(bindingResult); result = Optional.of(messages); } return result; } Optional<ValidationMessages> validateSpendProfileTableResource(SpendProfileTableResource tableResource); } | @Test public void testValidateSpendProfileTableResource() { SpendProfileTableResource tableResource = new SpendProfileTableResource(); when(spendProfileCostValidator.supports(ArgumentMatchers.eq(SpendProfileTableResource.class))).thenReturn(Boolean.TRUE); validationUtil.validateSpendProfileTableResource(tableResource); Mockito.verify(spendProfileCostValidator).validate(ArgumentMatchers.eq(tableResource), ArgumentMatchers.anyObject()); } |
ByProjectFinanceCostCategorySummaryStrategy implements SpendProfileCostCategorySummaryStrategy { @Override public ServiceResult<SpendProfileCostCategorySummaries> getCostCategorySummaries(Long projectId, Long organisationId) { return projectService.getProjectById(projectId).andOnSuccess(project -> organisationService.findById(organisationId).andOnSuccess(organisation -> projectFinanceService.financeChecksDetails(project.getId(), organisationId).andOnSuccess(finances -> createCostCategorySummariesWithCostCategoryType(projectId, organisationId, project, organisation, finances)))); } @Override ServiceResult<SpendProfileCostCategorySummaries> getCostCategorySummaries(Long projectId, Long organisationId); } | @Test public void testGenerateSpendProfileForIndustrialOrganisation() { ProjectResource project = newProjectResource(). withDuration(10L). withCompetition(2L). build(); CompetitionResource competition = newCompetitionResource() .withIncludeJesForm(true) .build(); OrganisationResource organisation = newOrganisationResource().withOrganisationType(OrganisationTypeEnum.BUSINESS.getId()).build(); Map<FinanceRowType, FinanceRowCostCategory> finances = asMap( FinanceRowType.LABOUR, newLabourCostCategory(). withCosts( newLabourCost(). withGrossEmployeeCost(new BigDecimal("10000"), new BigDecimal("5100"), BigDecimal.ZERO). withDescription("Developers", "Testers", WORKING_DAYS_PER_YEAR). withLabourDays(100, 120, 250). build(3)). build(), FinanceRowType.MATERIALS, newDefaultCostCategory().withCosts( newMaterials(). withCost(new BigDecimal("33"), new BigDecimal("98")). withQuantity(1, 2). build(2)). build()); finances.forEach((type, category) -> category.calculateTotal()); ProjectFinanceResource projectFinance = newProjectFinanceResource(). withFinanceOrganisationDetails(finances). build(); List<CostCategory> costCategories = newCostCategory(). withName("Labour", "Materials"). build(2); CostCategoryGroup costCategoryGroup = newCostCategoryGroup(). withCostCategories(costCategories). build(); CostCategoryType costCategoryType = newCostCategoryType().withCostCategoryGroup(costCategoryGroup).build(); when(projectServiceMock.getProjectById(project.getId())).thenReturn(serviceSuccess(project)); when(organisationServiceMock.findById(organisation.getId())).thenReturn(serviceSuccess(organisation)); when(projectFinanceService.financeChecksDetails(project.getId(), organisation.getId())).thenReturn(serviceSuccess(projectFinance)); when(competitionServiceMock.getCompetitionById(project.getCompetition())).thenReturn(serviceSuccess(competition)); when(costCategoryTypeStrategyMock.getOrCreateCostCategoryTypeForSpendProfile(project.getId(), organisation.getId())).thenReturn(serviceSuccess(costCategoryType)); ServiceResult<SpendProfileCostCategorySummaries> result = service.getCostCategorySummaries(project.getId(), organisation.getId()); assertTrue(result.isSuccess()); SpendProfileCostCategorySummaries summaries = result.getSuccess(); assertEquals(costCategoryType, summaries.getCostCategoryType()); assertEquals(2, summaries.getCosts().size()); SpendProfileCostCategorySummary summary1 = simpleFindFirst(summaries.getCosts(), s -> s.getCategory().equals(costCategories.get(0))).get(); SpendProfileCostCategorySummary summary2 = simpleFindFirst(summaries.getCosts(), s -> s.getCategory().equals(costCategories.get(1))).get(); assertEquals(new BigDecimal("6448"), summary1.getTotal()); assertEquals(new BigDecimal("229"), summary2.getTotal()); }
@Test public void testGenerateSpendProfileForAcademicOrganisation() { ProjectResource project = newProjectResource(). withDuration(10L). withCompetition(2L). build(); CompetitionResource competition = newCompetitionResource() .withIncludeJesForm(true) .withFundingType(FundingType.GRANT) .build(); OrganisationResource organisation = newOrganisationResource().withOrganisationType(OrganisationTypeEnum.RESEARCH.getId()).build(); Map<FinanceRowType, FinanceRowCostCategory> finances = asMap( FinanceRowType.LABOUR, newDefaultCostCategory().withCosts( newAcademicCost(). withCost(new BigDecimal("6448"), new BigDecimal("288")). withName(DIRECTLY_INCURRED_STAFF.getFinanceRowName(), INDIRECT_COSTS_STAFF.getFinanceRowName()). build(2)). build(), FinanceRowType.OTHER_COSTS, newDefaultCostCategory().withCosts( newAcademicCost(). withCost(new BigDecimal("33"), new BigDecimal("98")). withName(DIRECTLY_INCURRED_OTHER_COSTS.getFinanceRowName(), INDIRECT_COSTS_OTHER_COSTS.getFinanceRowName()). build(2)). build()); finances.forEach((type, category) -> category.calculateTotal()); ProjectFinanceResource projectFinance = newProjectFinanceResource(). withFinanceOrganisationDetails(finances). build(); List<CostCategory> costCategories = newCostCategory(). withName(DIRECTLY_INCURRED_STAFF.getDisplayName(), INDIRECT_COSTS_STAFF.getDisplayName(), DIRECTLY_INCURRED_OTHER_COSTS.getDisplayName(), INDIRECT_COSTS_OTHER_COSTS.getDisplayName()). withLabel(DIRECTLY_INCURRED_STAFF.getLabel(), INDIRECT_COSTS_STAFF.getLabel(), DIRECTLY_INCURRED_OTHER_COSTS.getLabel(), INDIRECT_COSTS_OTHER_COSTS.getLabel()). build(4); CostCategoryGroup costCategoryGroup = newCostCategoryGroup(). withCostCategories(costCategories). build(); CostCategoryType costCategoryType = newCostCategoryType().withCostCategoryGroup(costCategoryGroup).build(); when(projectServiceMock.getProjectById(project.getId())).thenReturn(serviceSuccess(project)); when(organisationServiceMock.findById(organisation.getId())).thenReturn(serviceSuccess(organisation)); when(projectFinanceService.financeChecksDetails(project.getId(), organisation.getId())).thenReturn(serviceSuccess(projectFinance)); when(competitionServiceMock.getCompetitionById(project.getCompetition())).thenReturn(serviceSuccess(competition)); when(costCategoryTypeStrategyMock.getOrCreateCostCategoryTypeForSpendProfile(project.getId(), organisation.getId())).thenReturn(serviceSuccess(costCategoryType)); ServiceResult<SpendProfileCostCategorySummaries> result = service.getCostCategorySummaries(project.getId(), organisation.getId()); assertTrue(result.isSuccess()); SpendProfileCostCategorySummaries summaries = result.getSuccess(); assertEquals(costCategoryType, summaries.getCostCategoryType()); assertEquals(4, summaries.getCosts().size()); SpendProfileCostCategorySummary summary1 = simpleFindFirst(summaries.getCosts(), s -> s.getCategory().equals(costCategories.get(0))).get(); SpendProfileCostCategorySummary summary2 = simpleFindFirst(summaries.getCosts(), s -> s.getCategory().equals(costCategories.get(1))).get(); SpendProfileCostCategorySummary summary3 = simpleFindFirst(summaries.getCosts(), s -> s.getCategory().equals(costCategories.get(2))).get(); SpendProfileCostCategorySummary summary4 = simpleFindFirst(summaries.getCosts(), s -> s.getCategory().equals(costCategories.get(3))).get(); assertEquals(new BigDecimal("6448"), summary1.getTotal()); assertEquals(new BigDecimal("288"), summary2.getTotal()); assertEquals(new BigDecimal("33"), summary3.getTotal()); assertEquals(new BigDecimal("98"), summary4.getTotal()); }
@Test public void testGenerateSpendProfileForSbri() { ProjectResource project = newProjectResource(). withDuration(10L). withCompetition(2L). build(); CompetitionResource competition = newCompetitionResource() .withFundingType(FundingType.PROCUREMENT) .withName(SBRI_PILOT) .build(); OrganisationResource organisation = newOrganisationResource().withOrganisationType(OrganisationTypeEnum.BUSINESS.getId()).build(); Map<FinanceRowType, FinanceRowCostCategory> finances = asMap( FinanceRowType.LABOUR, newLabourCostCategory(). withCosts( newLabourCost(). withGrossEmployeeCost(new BigDecimal("10000"), new BigDecimal("5100"), BigDecimal.ZERO). withDescription("Developers", "Testers", WORKING_DAYS_PER_YEAR). withLabourDays(100, 120, 250). build(3)). build(), FinanceRowType.MATERIALS, newDefaultCostCategory().withCosts( newMaterials(). withCost(new BigDecimal("33"), new BigDecimal("98")). withQuantity(1, 2). build(2)). build()); finances.forEach((type, category) -> category.calculateTotal()); BigDecimal totalCosts = finances.values().stream().map(FinanceRowCostCategory::getTotal).reduce(BigDecimal.ZERO, BigDecimal::add); VatCostCategory vatCostCategory = newVATCategory().withCosts( VATCostBuilder.newVATCost(). withRegistered(true). withRate(new BigDecimal("0.2")). build(1)). build(); vatCostCategory.setTotalCostsWithoutVat(totalCosts); vatCostCategory.calculateTotal(); finances.put(FinanceRowType.VAT, vatCostCategory); ProjectFinanceResource projectFinance = newProjectFinanceResource(). withFinanceOrganisationDetails(finances). build(); List<CostCategory> costCategories = newCostCategory(). withName("Other costs", "VAT"). build(2); CostCategoryGroup costCategoryGroup = newCostCategoryGroup(). withCostCategories(costCategories). build(); CostCategoryType costCategoryType = newCostCategoryType().withCostCategoryGroup(costCategoryGroup).build(); when(projectServiceMock.getProjectById(project.getId())).thenReturn(serviceSuccess(project)); when(organisationServiceMock.findById(organisation.getId())).thenReturn(serviceSuccess(organisation)); when(projectFinanceService.financeChecksDetails(project.getId(), organisation.getId())).thenReturn(serviceSuccess(projectFinance)); when(competitionServiceMock.getCompetitionById(project.getCompetition())).thenReturn(serviceSuccess(competition)); when(costCategoryTypeStrategyMock.getOrCreateCostCategoryTypeForSpendProfile(project.getId(), organisation.getId())).thenReturn(serviceSuccess(costCategoryType)); ServiceResult<SpendProfileCostCategorySummaries> result = service.getCostCategorySummaries(project.getId(), organisation.getId()); assertTrue(result.isSuccess()); SpendProfileCostCategorySummaries summaries = result.getSuccess(); assertEquals(costCategoryType, summaries.getCostCategoryType()); assertEquals(2, summaries.getCosts().size()); SpendProfileCostCategorySummary summary1 = simpleFindFirst(summaries.getCosts(), s -> s.getCategory().equals(costCategories.get(0))).get(); SpendProfileCostCategorySummary summary2 = simpleFindFirst(summaries.getCosts(), s -> s.getCategory().equals(costCategories.get(1))).get(); assertEquals(new BigDecimal("6677"), summary1.getTotal()); assertEquals(new BigDecimal("1335"), summary2.getTotal()); } |
SpendProfileServiceImpl extends BaseTransactionalService implements SpendProfileService { @Override @Transactional public ServiceResult<Void> generateSpendProfile(Long projectId) { return getProject(projectId) .andOnSuccess(project -> canSpendProfileCanBeGenerated(project) .andOnSuccess(() -> partnerOrganisationService.getProjectPartnerOrganisations(projectId) .andOnSuccess(partnerOrganisationResources -> { List<Long> organisationIds = removeDuplicates(simpleMap(partnerOrganisationResources, PartnerOrganisationResource::getOrganisation)); return generateSpendProfileForPartnerOrganisations(project, organisationIds); })) .andOnSuccess(() -> getCurrentlyLoggedInUser().andOnSuccess(user -> { if (spendProfileWorkflowHandler.spendProfileGenerated(project, user)) { return serviceSuccess(project); } else { LOG.error(String.format(SPEND_PROFILE_STATE_ERROR, project.getId())); return serviceFailure(GENERAL_UNEXPECTED_ERROR); } }) ) ) .andOnSuccess(project -> { if (!competitionHasSpendProfileStage(project)) { List<ServiceResult<Void>> markAsCompleteResults = project.getPartnerOrganisations() .stream() .map(po -> markSpendProfileComplete(ProjectOrganisationCompositeId.id(project.getId(), po.getOrganisation().getId()))) .collect(toList()); return aggregate(markAsCompleteResults) .andOnSuccess(() -> completeSpendProfilesReview(projectId)) .andOnSuccess(() -> approveOrRejectSpendProfile(projectId, APPROVED)); } return serviceSuccess(); }); } @Override @Transactional ServiceResult<Void> generateSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> approveOrRejectSpendProfile(Long projectId, ApprovalType approvalType); @Override ServiceResult<ApprovalType> getSpendProfileStatusByProjectId(Long projectId); @Override ServiceResult<ApprovalType> getSpendProfileStatus(Long projectId); @Override ServiceResult<SpendProfileTableResource> getSpendProfileTable(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileCSVResource> getSpendProfileCSV(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileResource> getSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> saveSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId, SpendProfileTableResource table); @Override @Transactional ServiceResult<Void> markSpendProfileComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> deleteSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> completeSpendProfilesReview(Long projectId); static final String EMPTY_CELL; } | @Test public void generateSpendProfile() { GenerateSpendProfileData generateSpendProfileData = new GenerateSpendProfileData().build(); Project project = generateSpendProfileData.getProject(); Organisation organisation1 = generateSpendProfileData.getOrganisation1(); Organisation organisation2 = generateSpendProfileData.getOrganisation2(); PartnerOrganisation partnerOrganisation1 = project.getPartnerOrganisations().get(0); PartnerOrganisation partnerOrganisation2 = project.getPartnerOrganisations().get(1); CostCategoryType costCategoryType1 = generateSpendProfileData.getCostCategoryType1(); CostCategoryType costCategoryType2 = generateSpendProfileData.getCostCategoryType2(); CostCategory type1Cat1 = generateSpendProfileData.type1Cat1; CostCategory type1Cat2 = generateSpendProfileData.type1Cat2; CostCategory type2Cat1 = generateSpendProfileData.type2Cat1; setupGenerateSpendProfilesExpectations(generateSpendProfileData, project, organisation1, organisation2); when(viabilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(ViabilityState.APPROVED); when(viabilityWorkflowHandler.getState(partnerOrganisation2)).thenReturn(ViabilityState.APPROVED); when(eligibilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(EligibilityState.APPROVED); when(eligibilityWorkflowHandler.getState(partnerOrganisation2)).thenReturn(EligibilityState.APPROVED); when(spendProfileWorkflowHandler.isAlreadyGenerated(project)).thenReturn(false); when(spendProfileWorkflowHandler.projectHasNoPendingPartners(project)).thenReturn(true); when(spendProfileWorkflowHandler.spendProfileGenerated(eq(project), any())).thenReturn(true); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(project.getId(), organisation1.getId())).thenReturn(Optional.empty()); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(project.getId(), organisation2.getId())).thenReturn(Optional.empty()); User generatedBy = generateSpendProfileData.getUser(); List<Cost> expectedOrganisation1EligibleCosts = asList( new Cost("100").withCategory(type1Cat1), new Cost("200").withCategory(type1Cat2)); List<Cost> expectedOrganisation1SpendProfileFigures = asList( new Cost("34").withCategory(type1Cat1).withTimePeriod(0, MONTH, 1, MONTH), new Cost("33").withCategory(type1Cat1).withTimePeriod(1, MONTH, 1, MONTH), new Cost("33").withCategory(type1Cat1).withTimePeriod(2, MONTH, 1, MONTH), new Cost("68").withCategory(type1Cat2).withTimePeriod(0, MONTH, 1, MONTH), new Cost("66").withCategory(type1Cat2).withTimePeriod(1, MONTH, 1, MONTH), new Cost("66").withCategory(type1Cat2).withTimePeriod(2, MONTH, 1, MONTH)); Calendar generatedDate = Calendar.getInstance(); SpendProfile expectedOrganisation1Profile = new SpendProfile(organisation1, project, costCategoryType1, expectedOrganisation1EligibleCosts, expectedOrganisation1SpendProfileFigures, generatedBy, generatedDate, false); List<Cost> expectedOrganisation2EligibleCosts = singletonList( new Cost("301").withCategory(type2Cat1)); List<Cost> expectedOrganisation2SpendProfileFigures = asList( new Cost("101").withCategory(type2Cat1).withTimePeriod(0, MONTH, 1, MONTH), new Cost("100").withCategory(type2Cat1).withTimePeriod(1, MONTH, 1, MONTH), new Cost("100").withCategory(type2Cat1).withTimePeriod(2, MONTH, 1, MONTH)); SpendProfile expectedOrganisation2Profile = new SpendProfile(organisation2, project, costCategoryType2, expectedOrganisation2EligibleCosts, expectedOrganisation2SpendProfileFigures, generatedBy, generatedDate, false); when(spendProfileRepository.save(spendProfileExpectations(expectedOrganisation1Profile))).thenReturn(null); when(spendProfileRepository.save(spendProfileExpectations(expectedOrganisation2Profile))).thenReturn(null); User financeContactUser1 = newUser().withEmailAddress("[email protected]").withFirstName("A").withLastName("Z").build(); ProjectUser financeContact1 = newProjectUser().withUser(financeContactUser1).build(); User financeContactUser2 = newUser().withEmailAddress("[email protected]").withFirstName("A").withLastName("A").build(); ProjectUser financeContact2 = newProjectUser().withUser(financeContactUser2).build(); when(projectUsersHelper.getFinanceContact(project.getId(), organisation1.getId())).thenReturn(Optional.of(financeContact1)); when(projectUsersHelper.getFinanceContact(project.getId(), organisation2.getId())).thenReturn(Optional.of(financeContact2)); Map<String, Object> expectedNotificationArguments = asMap( "dashboardUrl", "https: "applicationId", project.getApplication().getId(), "competitionName", "Competition 1" ); NotificationTarget to1 = new UserNotificationTarget("A Z", "[email protected]"); NotificationTarget to2 = new UserNotificationTarget("A A", "[email protected]"); Notification notification1 = new Notification(systemNotificationSource, to1, SpendProfileNotifications.FINANCE_CONTACT_SPEND_PROFILE_AVAILABLE, expectedNotificationArguments); Notification notification2 = new Notification(systemNotificationSource, to2, SpendProfileNotifications.FINANCE_CONTACT_SPEND_PROFILE_AVAILABLE, expectedNotificationArguments); when(notificationService.sendNotificationWithFlush(notification1, EMAIL)).thenReturn(serviceSuccess()); when(notificationService.sendNotificationWithFlush(notification2, EMAIL)).thenReturn(serviceSuccess()); ServiceResult<Void> generateResult = service.generateSpendProfile(projectId); assertTrue(generateResult.isSuccess()); verify(spendProfileRepository).save(spendProfileExpectations(expectedOrganisation1Profile)); verify(spendProfileRepository).save(spendProfileExpectations(expectedOrganisation2Profile)); verify(notificationService).sendNotificationWithFlush(notification1, EMAIL); verify(notificationService).sendNotificationWithFlush(notification2, EMAIL); }
@Test public void generateSbriPilotSpendProfile() { GenerateSpendProfileData generateSpendProfileData = new GenerateSpendProfileData().build(); Project project = generateSpendProfileData.getProject(); project.getPartnerOrganisations().removeIf(po -> po.getOrganisation().getId().equals(generateSpendProfileData.getOrganisation2().getId())); Organisation organisation1 = generateSpendProfileData.getOrganisation1(); PartnerOrganisation partnerOrganisation1 = project.getPartnerOrganisations().get(0); CostCategoryType sbriPilotCategoryType = generateSpendProfileData.getSbriPilotCategoryType(); CostCategory sbriPilotCategoryOtherCosts = generateSpendProfileData.sbriPilotCategoryOtherCosts; CostCategory sbriPilotCategoryVat = generateSpendProfileData.sbriPilotCategoryVat; Competition competition = project.getApplication().getCompetition(); competition.setProjectStages(new ArrayList<>()); competition.setName(ApplicationConfiguration.SBRI_PILOT); setupGenerateSpendProfilesExpectations(generateSpendProfileData, project, organisation1, null); when(viabilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(ViabilityState.APPROVED); when(eligibilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(EligibilityState.APPROVED); when(spendProfileWorkflowHandler.isAlreadyGenerated(project)).thenReturn(false); when(spendProfileWorkflowHandler.projectHasNoPendingPartners(project)).thenReturn(true); when(spendProfileWorkflowHandler.spendProfileGenerated(eq(project), any())).thenReturn(true); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(project.getId(), organisation1.getId())).thenReturn(Optional.empty()); User generatedBy = generateSpendProfileData.getUser(); List<Cost> expectedOrganisation1EligibleCosts = asList( new Cost("100").withCategory(sbriPilotCategoryOtherCosts), new Cost("200").withCategory(sbriPilotCategoryVat)); List<Cost> expectedOrganisation1SpendProfileFigures = asList( new Cost("25").withCategory(sbriPilotCategoryOtherCosts).withTimePeriod(0, MONTH, 1, MONTH), new Cost("0").withCategory(sbriPilotCategoryOtherCosts).withTimePeriod(1, MONTH, 1, MONTH), new Cost("75").withCategory(sbriPilotCategoryOtherCosts).withTimePeriod(2, MONTH, 1, MONTH), new Cost("50").withCategory(sbriPilotCategoryVat).withTimePeriod(0, MONTH, 1, MONTH), new Cost("0").withCategory(sbriPilotCategoryVat).withTimePeriod(1, MONTH, 1, MONTH), new Cost("150").withCategory(sbriPilotCategoryVat).withTimePeriod(2, MONTH, 1, MONTH)); Calendar generatedDate = Calendar.getInstance(); SpendProfile expectedOrganisation1Profile = new SpendProfile(organisation1, project, sbriPilotCategoryType, expectedOrganisation1EligibleCosts, expectedOrganisation1SpendProfileFigures, generatedBy, generatedDate, false); when(spendProfileRepository.save(spendProfileExpectations(expectedOrganisation1Profile))).thenReturn(null); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(projectId, organisation1.getId())).thenReturn(Optional.of(expectedOrganisation1Profile)); when(spendProfileWorkflowHandler.submit(project)).thenReturn(true); when(spendProfileWorkflowHandler.isReadyToApprove(project)).thenReturn(true); Long userId = 1234L; UserResource loggedInUser = newUserResource().withId(userId).build(); User user = newUser().withId(loggedInUser.getId()).build(); setLoggedInUser(loggedInUser); when(userRepository.findById(userId)).thenReturn(Optional.of(user)); when(spendProfileWorkflowHandler.spendProfileApproved(project, user)).thenReturn(true); ServiceResult<Void> generateResult = service.generateSpendProfile(projectId); assertTrue(generateResult.isSuccess()); assertTrue(expectedOrganisation1Profile.isMarkedAsComplete()); verify(spendProfileRepository).save(spendProfileExpectations(expectedOrganisation1Profile)); verify(spendProfileWorkflowHandler).submit(project); verify(spendProfileWorkflowHandler).spendProfileApproved(project, user); verifyZeroInteractions(notificationService); }
@Test public void generateSpendProfileButNotAllViabilityApproved() { GenerateSpendProfileData generateSpendProfileData = new GenerateSpendProfileData().build(); Project project = generateSpendProfileData.getProject(); Organisation organisation1 = generateSpendProfileData.getOrganisation1(); Organisation organisation2 = generateSpendProfileData.getOrganisation2(); PartnerOrganisation partnerOrganisation1 = project.getPartnerOrganisations().get(0); PartnerOrganisation partnerOrganisation2 = project.getPartnerOrganisations().get(1); setupGenerateSpendProfilesExpectations(generateSpendProfileData, project, organisation1, organisation2); when(viabilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(ViabilityState.APPROVED); when(viabilityWorkflowHandler.getState(partnerOrganisation2)).thenReturn(ViabilityState.REVIEW); ServiceResult<Void> generateResult = service.generateSpendProfile(projectId); assertTrue(generateResult.isFailure()); assertTrue(generateResult.getFailure().is(SPEND_PROFILE_CANNOT_BE_GENERATED_UNTIL_ALL_VIABILITY_APPROVED)); verify(spendProfileRepository, never()).save(isA(SpendProfile.class)); verifyNoMoreInteractions(spendProfileRepository); }
@Test public void generateSpendProfileButWithPendingPartner() { GenerateSpendProfileData generateSpendProfileData = new GenerateSpendProfileData().build(); Project project = generateSpendProfileData.getProject(); Organisation organisation1 = generateSpendProfileData.getOrganisation1(); Organisation organisation2 = generateSpendProfileData.getOrganisation2(); PartnerOrganisation partnerOrganisation1 = project.getPartnerOrganisations().get(0); PartnerOrganisation partnerOrganisation2 = project.getPartnerOrganisations().get(1); setupGenerateSpendProfilesExpectations(generateSpendProfileData, project, organisation1, organisation2); when(viabilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(ViabilityState.APPROVED); when(viabilityWorkflowHandler.getState(partnerOrganisation2)).thenReturn(ViabilityState.NOT_APPLICABLE); when(eligibilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(EligibilityState.APPROVED); when(eligibilityWorkflowHandler.getState(partnerOrganisation2)).thenReturn(EligibilityState.APPROVED); when(spendProfileWorkflowHandler.isAlreadyGenerated(project)).thenReturn(false); when(spendProfileWorkflowHandler.projectHasNoPendingPartners(project)).thenReturn(false); ServiceResult<Void> generateResult = service.generateSpendProfile(projectId); assertTrue(generateResult.isFailure()); assertTrue(generateResult.getFailure().is(SPEND_PROFILE_CANNOT_BE_GENERATED_UNTIL_ALL_PARTNERS_ARE_NO_LONGER_PENDING)); verify(spendProfileRepository, never()).save(isA(SpendProfile.class)); verifyNoMoreInteractions(spendProfileRepository); }
@Test public void generateSpendProfileWhenNotAllEligibilityApproved() { GenerateSpendProfileData generateSpendProfileData = new GenerateSpendProfileData().build(); Project project = generateSpendProfileData.getProject(); Organisation organisation1 = generateSpendProfileData.getOrganisation1(); Organisation organisation2 = generateSpendProfileData.getOrganisation2(); PartnerOrganisation partnerOrganisation1 = project.getPartnerOrganisations().get(0); PartnerOrganisation partnerOrganisation2 = project.getPartnerOrganisations().get(1); setupGenerateSpendProfilesExpectations(generateSpendProfileData, project, organisation1, organisation2); when(viabilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(ViabilityState.APPROVED); when(viabilityWorkflowHandler.getState(partnerOrganisation2)).thenReturn(ViabilityState.APPROVED); when(eligibilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(EligibilityState.APPROVED); when(eligibilityWorkflowHandler.getState(partnerOrganisation2)).thenReturn(EligibilityState.REVIEW); ServiceResult<Void> generateResult = service.generateSpendProfile(projectId); assertTrue(generateResult.isFailure()); assertTrue(generateResult.getFailure().is(SPEND_PROFILE_CANNOT_BE_GENERATED_UNTIL_ALL_ELIGIBILITY_APPROVED)); verify(spendProfileRepository, never()).save(isA(SpendProfile.class)); verifyNoMoreInteractions(spendProfileRepository); }
@Test public void generateSpendProfileWhenSpendProfileAlreadyGenerated() { GenerateSpendProfileData generateSpendProfileData = new GenerateSpendProfileData().build(); Project project = generateSpendProfileData.getProject(); Organisation organisation1 = generateSpendProfileData.getOrganisation1(); Organisation organisation2 = generateSpendProfileData.getOrganisation2(); PartnerOrganisation partnerOrganisation1 = project.getPartnerOrganisations().get(0); PartnerOrganisation partnerOrganisation2 = project.getPartnerOrganisations().get(1); setupGenerateSpendProfilesExpectations(generateSpendProfileData, project, organisation1, organisation2); when(viabilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(ViabilityState.APPROVED); when(viabilityWorkflowHandler.getState(partnerOrganisation2)).thenReturn(ViabilityState.APPROVED); when(eligibilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(EligibilityState.APPROVED); when(eligibilityWorkflowHandler.getState(partnerOrganisation2)).thenReturn(EligibilityState.APPROVED); when(spendProfileWorkflowHandler.isAlreadyGenerated(project)).thenReturn(true); SpendProfile spendProfileForOrganisation1 = new SpendProfile(); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(project.getId(), organisation1.getId())).thenReturn(Optional.of(spendProfileForOrganisation1)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(project.getId(), organisation2.getId())).thenReturn(Optional.empty()); ServiceResult<Void> generateResult = service.generateSpendProfile(projectId); assertTrue(generateResult.isFailure()); assertTrue(generateResult.getFailure().is(SPEND_PROFILE_HAS_ALREADY_BEEN_GENERATED)); verify(spendProfileRepository, never()).save(isA(SpendProfile.class)); }
@Test public void generateSpendProfileWhenSendingEmailFails() { GenerateSpendProfileData generateSpendProfileData = new GenerateSpendProfileData().build(); Project project = generateSpendProfileData.getProject(); Organisation organisation1 = generateSpendProfileData.getOrganisation1(); Organisation organisation2 = generateSpendProfileData.getOrganisation2(); PartnerOrganisation partnerOrganisation1 = project.getPartnerOrganisations().get(0); PartnerOrganisation partnerOrganisation2 = project.getPartnerOrganisations().get(1); setupGenerateSpendProfilesExpectations(generateSpendProfileData, project, organisation1, organisation2); when(viabilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(ViabilityState.APPROVED); when(viabilityWorkflowHandler.getState(partnerOrganisation2)).thenReturn(ViabilityState.NOT_APPLICABLE); when(eligibilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(EligibilityState.APPROVED); when(eligibilityWorkflowHandler.getState(partnerOrganisation2)).thenReturn(EligibilityState.APPROVED); when(spendProfileWorkflowHandler.isAlreadyGenerated(project)).thenReturn(false); when(spendProfileWorkflowHandler.projectHasNoPendingPartners(project)).thenReturn(true); when(spendProfileWorkflowHandler.spendProfileGenerated(eq(project), any())).thenReturn(true); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(project.getId(), organisation1.getId())).thenReturn(Optional.empty()); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(project.getId(), organisation2.getId())).thenReturn(Optional.empty()); User financeContactUser1 = newUser().withEmailAddress("[email protected]").withFirstName("A").withLastName("Z").build(); ProjectUser financeContact1 = newProjectUser().withUser(financeContactUser1).build(); User financeContactUser2 = newUser().withEmailAddress("[email protected]").withFirstName("A").withLastName("A").build(); ProjectUser financeContact2 = newProjectUser().withUser(financeContactUser2).build(); when(projectUsersHelper.getFinanceContact(project.getId(), organisation1.getId())).thenReturn(Optional.of(financeContact1)); when(projectUsersHelper.getFinanceContact(project.getId(), organisation2.getId())).thenReturn(Optional.of(financeContact2)); Map<String, Object> expectedNotificationArguments = asMap( "dashboardUrl", "https: "competitionName", "Competition 1", "applicationId", project.getApplication().getId() ); NotificationTarget to1 = new UserNotificationTarget("A Z", "[email protected]"); NotificationTarget to2 = new UserNotificationTarget("A A", "[email protected]"); Notification notification1 = new Notification(systemNotificationSource, to1, SpendProfileNotifications.FINANCE_CONTACT_SPEND_PROFILE_AVAILABLE, expectedNotificationArguments); Notification notification2 = new Notification(systemNotificationSource, to2, SpendProfileNotifications.FINANCE_CONTACT_SPEND_PROFILE_AVAILABLE, expectedNotificationArguments); when(notificationService.sendNotificationWithFlush(notification1, EMAIL)).thenReturn(serviceSuccess()); when(notificationService.sendNotificationWithFlush(notification2, EMAIL)).thenReturn(serviceFailure(CommonFailureKeys.NOTIFICATIONS_UNABLE_TO_SEND_SINGLE)); ServiceResult<Void> generateResult = service.generateSpendProfile(projectId); assertTrue(generateResult.isFailure()); assertTrue(generateResult.getFailure().is(CommonFailureKeys.NOTIFICATIONS_UNABLE_TO_SEND_SINGLE)); verify(spendProfileRepository, times(2)).save(isA(SpendProfile.class)); verify(notificationService).sendNotificationWithFlush(notification1, EMAIL); verify(notificationService).sendNotificationWithFlush(notification2, EMAIL); }
@Test public void generateSpendProfileSendEmailFailsDueToNoFinanceContact() { GenerateSpendProfileData generateSpendProfileData = new GenerateSpendProfileData().build(); Project project = generateSpendProfileData.getProject(); Organisation organisation1 = generateSpendProfileData.getOrganisation1(); Organisation organisation2 = generateSpendProfileData.getOrganisation2(); PartnerOrganisation partnerOrganisation1 = project.getPartnerOrganisations().get(0); PartnerOrganisation partnerOrganisation2 = project.getPartnerOrganisations().get(1); setupGenerateSpendProfilesExpectations(generateSpendProfileData, project, organisation1, organisation2); when(viabilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(ViabilityState.APPROVED); when(viabilityWorkflowHandler.getState(partnerOrganisation2)).thenReturn(ViabilityState.NOT_APPLICABLE); when(eligibilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(EligibilityState.APPROVED); when(eligibilityWorkflowHandler.getState(partnerOrganisation2)).thenReturn(EligibilityState.APPROVED); when(spendProfileWorkflowHandler.isAlreadyGenerated(project)).thenReturn(false); when(spendProfileWorkflowHandler.projectHasNoPendingPartners(project)).thenReturn(true); when(spendProfileWorkflowHandler.spendProfileGenerated(eq(project), any())).thenReturn(true); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(project.getId(), organisation1.getId())).thenReturn(Optional.empty()); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(project.getId(), organisation2.getId())).thenReturn(Optional.empty()); ProjectUser financeContact2 = newProjectUser().withUser((User[]) null).build(); when(projectUsersHelper.getFinanceContact(project.getId(), organisation1.getId())).thenReturn(Optional.empty()); when(projectUsersHelper.getFinanceContact(project.getId(), organisation2.getId())).thenReturn(Optional.of(financeContact2)); ServiceResult<Void> generateResult = service.generateSpendProfile(projectId); assertTrue(generateResult.isFailure()); assertTrue(generateResult.getFailure().is(CommonFailureKeys.SPEND_PROFILE_FINANCE_CONTACT_NOT_PRESENT, CommonFailureKeys.SPEND_PROFILE_FINANCE_CONTACT_NOT_PRESENT)); verify(spendProfileRepository, times(2)).save(isA(SpendProfile.class)); }
@Test public void generateSpendProfileNotReadyToGenerate() { GenerateSpendProfileData generateSpendProfileData = new GenerateSpendProfileData().build(); Project project = generateSpendProfileData.getProject(); Organisation organisation1 = generateSpendProfileData.getOrganisation1(); Organisation organisation2 = generateSpendProfileData.getOrganisation2(); PartnerOrganisation partnerOrganisation1 = project.getPartnerOrganisations().get(0); PartnerOrganisation partnerOrganisation2 = project.getPartnerOrganisations().get(1); setupGenerateSpendProfilesExpectations(generateSpendProfileData, project, organisation1, organisation2); when(viabilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(ViabilityState.APPROVED); when(viabilityWorkflowHandler.getState(partnerOrganisation2)).thenReturn(ViabilityState.NOT_APPLICABLE); when(eligibilityWorkflowHandler.getState(partnerOrganisation1)).thenReturn(EligibilityState.APPROVED); when(eligibilityWorkflowHandler.getState(partnerOrganisation2)).thenReturn(EligibilityState.APPROVED); when(spendProfileWorkflowHandler.isAlreadyGenerated(project)).thenReturn(true); ServiceResult<Void> generateResult = service.generateSpendProfile(projectId); assertTrue(generateResult.isFailure()); assertTrue(generateResult.getFailure().is(CommonFailureKeys.SPEND_PROFILE_HAS_ALREADY_BEEN_GENERATED)); } |
AgreementController { @GetMapping("/find-current") public RestResult<AgreementResource> findCurrent() { return agreementService.getCurrent().toGetResponse(); } @GetMapping("/find-current") RestResult<AgreementResource> findCurrent(); } | @Test public void findCurrent() throws Exception { String agreementText = "agreement text"; when(agreementServiceMock.getCurrent()).thenReturn(serviceSuccess(newAgreementResource().withText(agreementText).build())); mockMvc.perform(get("/agreement/find-current")) .andExpect(status().isOk()) .andExpect(jsonPath("$.text", is(agreementText))); } |
SpendProfileServiceImpl extends BaseTransactionalService implements SpendProfileService { @Override public ServiceResult<SpendProfileCSVResource> getSpendProfileCSV(ProjectOrganisationCompositeId projectOrganisationCompositeId) { SpendProfileTableResource spendProfileTableResource = getSpendProfileTable(projectOrganisationCompositeId).getSuccess(); try { return serviceSuccess(generateSpendProfileCSVData(spendProfileTableResource, projectOrganisationCompositeId)); } catch (IOException ioe) { LOG.error("exception thrown getting spend profile", ioe); return serviceFailure(SPEND_PROFILE_CSV_GENERATION_FAILURE); } } @Override @Transactional ServiceResult<Void> generateSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> approveOrRejectSpendProfile(Long projectId, ApprovalType approvalType); @Override ServiceResult<ApprovalType> getSpendProfileStatusByProjectId(Long projectId); @Override ServiceResult<ApprovalType> getSpendProfileStatus(Long projectId); @Override ServiceResult<SpendProfileTableResource> getSpendProfileTable(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileCSVResource> getSpendProfileCSV(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileResource> getSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> saveSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId, SpendProfileTableResource table); @Override @Transactional ServiceResult<Void> markSpendProfileComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> deleteSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> completeSpendProfilesReview(Long projectId); static final String EMPTY_CELL; } | @Test public void generateSpendProfileCSV() { Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).build(); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); SpendProfile spendProfileInDB = createSpendProfile(project, asMap( 1L, new BigDecimal("100"), 2L, new BigDecimal("180"), 3L, new BigDecimal("55")), asMap( 1L, asList(new BigDecimal("30"), new BigDecimal("30"), new BigDecimal("50")), 2L, asList(new BigDecimal("70"), new BigDecimal("50"), new BigDecimal("60")), 3L, asList(new BigDecimal("50"), new BigDecimal("5"), new BigDecimal("0"))) ); CostCategory testCostCategory = new CostCategory(); testCostCategory.setId(1L); testCostCategory.setName("Category One"); testCostCategory.setLabel("Group Name"); OrganisationType organisationType = newOrganisationType().withOrganisationType(BUSINESS).build(); Organisation organisation1 = newOrganisation().withId(organisationId).withOrganisationType(organisationType).withName("TEST").build(); when(organisationRepository.findById(organisation1.getId())).thenReturn(Optional.of(organisation1)); when(projectRepository.findById(projectId)).thenReturn(Optional.of(project)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(Optional.of(spendProfileInDB)); when(costCategoryRepository.findById(anyLong())).thenReturn(Optional.of(testCostCategory)); Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); ServiceResult<SpendProfileCSVResource> serviceResult = service.getSpendProfileCSV(projectOrganisationCompositeId); assertTrue(serviceResult.getSuccess().getFileName().startsWith("TEST_Spend_Profile_" + dateFormat.format(date))); assertTrue(serviceResult.getSuccess().getCsvData().contains("Category One")); assertEquals(6, Arrays.stream(serviceResult.getSuccess().getCsvData().split("\n")).filter(s -> s.contains("Category One") && !s.contains("Month") && !s.contains("TOTAL")).count()); }
@Test public void generateSpendProfileCSVWithCategoryGroupLabelEmpty() { Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).build(); ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); SpendProfile spendProfileInDB = createSpendProfile(project, asMap( 1L, new BigDecimal("100"), 2L, new BigDecimal("180"), 3L, new BigDecimal("55")), asMap( 1L, asList(new BigDecimal("30"), new BigDecimal("30"), new BigDecimal("50")), 2L, asList(new BigDecimal("70"), new BigDecimal("50"), new BigDecimal("60")), 3L, asList(new BigDecimal("50"), new BigDecimal("5"), new BigDecimal("0"))) ); CostCategory testCostCategory = new CostCategory(); testCostCategory.setId(1L); testCostCategory.setName("One"); OrganisationType organisationType = newOrganisationType().withOrganisationType(BUSINESS).build(); Organisation organisation1 = newOrganisation().withId(organisationId).withOrganisationType(organisationType).withName("TEST").build(); when(organisationRepository.findById(organisation1.getId())).thenReturn(Optional.of(organisation1)); when(projectRepository.findById(projectId)).thenReturn(Optional.of(project)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(Optional.of(spendProfileInDB)); when(costCategoryRepository.findById(anyLong())).thenReturn(Optional.of(testCostCategory)); Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); ServiceResult<SpendProfileCSVResource> serviceResult = service.getSpendProfileCSV(projectOrganisationCompositeId); assertTrue(serviceResult.getSuccess().getFileName().startsWith("TEST_Spend_Profile_" + dateFormat.format(date))); assertFalse(serviceResult.getSuccess().getCsvData().contains("Group Name")); assertEquals(Arrays.stream(serviceResult.getSuccess().getCsvData().split("\n")).filter(s -> s.contains("Group Name") && !s.contains("Month") && !s.contains("TOTAL")).count(), 0); } |
SpendProfileServiceImpl extends BaseTransactionalService implements SpendProfileService { @Override public ServiceResult<ApprovalType> getSpendProfileStatusByProjectId(Long projectId) { return serviceSuccess(getSpendProfileStatusBy(projectId)); } @Override @Transactional ServiceResult<Void> generateSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> approveOrRejectSpendProfile(Long projectId, ApprovalType approvalType); @Override ServiceResult<ApprovalType> getSpendProfileStatusByProjectId(Long projectId); @Override ServiceResult<ApprovalType> getSpendProfileStatus(Long projectId); @Override ServiceResult<SpendProfileTableResource> getSpendProfileTable(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileCSVResource> getSpendProfileCSV(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileResource> getSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> saveSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId, SpendProfileTableResource table); @Override @Transactional ServiceResult<Void> markSpendProfileComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> deleteSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> completeSpendProfilesReview(Long projectId); static final String EMPTY_CELL; } | @Test public void getSpendProfileStatusByProjectIdApproved() { Project project = newProject().build(); when(projectRepository.findById(projectId)).thenReturn(Optional.of(project)); when(spendProfileWorkflowHandler.getApproval(project)).thenReturn(ApprovalType.APPROVED); ServiceResult<ApprovalType> result = service.getSpendProfileStatusByProjectId(projectId); assertTrue(result.isSuccess()); assertEquals(ApprovalType.APPROVED, result.getSuccess()); }
@Test public void getSpendProfileStatusByProjectIdRejected() { Project project = newProject().build(); when(projectRepository.findById(projectId)).thenReturn(Optional.of(project)); when(spendProfileWorkflowHandler.getApproval(project)).thenReturn(ApprovalType.REJECTED); ServiceResult<ApprovalType> result = service.getSpendProfileStatusByProjectId(projectId); assertTrue(result.isSuccess()); assertEquals(ApprovalType.REJECTED, result.getSuccess()); }
@Test public void getSpendProfileStatusByProjectIdUnset() { List<SpendProfile> spendProfileList = newSpendProfile().build(3); when(spendProfileRepository.findByProjectId(projectId)).thenReturn(spendProfileList); ServiceResult<ApprovalType> result = service.getSpendProfileStatusByProjectId(projectId); assertTrue(result.isSuccess()); assertEquals(ApprovalType.UNSET, result.getSuccess()); } |
UserController { @PutMapping("/" + URL_RESEND_EMAIL_VERIFICATION_NOTIFICATION + "/{emailAddress}/") public RestResult<Void> resendEmailVerificationNotification(@PathVariable String emailAddress) { return userService.findInactiveByEmail(emailAddress) .andOnSuccessReturn(user -> registrationService.resendUserVerificationEmail(user)) .toPutResponse(); } @GetMapping("/uid/{uid}") RestResult<UserResource> getUserByUid(@PathVariable String uid); @GetMapping("/id/{id}") RestResult<UserResource> getUserById(@PathVariable long id); @PostMapping RestResult<UserResource> createUser(@RequestBody UserCreationResource userCreationResource); @GetMapping("/find-by-role/{userRole}") RestResult<List<UserResource>> findByRole(@PathVariable Role userRole); @GetMapping("/find-by-role-and-status/{userRole}/status/{userStatus}") RestResult<List<UserResource>> findByRoleAndUserStatus(@PathVariable Role userRole, @PathVariable UserStatus userStatus); @GetMapping("/active") RestResult<ManageUserPageResource> findActiveUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @GetMapping("/inactive") RestResult<ManageUserPageResource> findInactiveUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @GetMapping("/external/active") RestResult<ManageUserPageResource> findActiveExternalUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @GetMapping("/external/inactive") RestResult<ManageUserPageResource> findInactiveExternalUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @PostMapping("/internal/create/{inviteHash}") RestResult<Void> createInternalUser(@PathVariable("inviteHash") String inviteHash, @Valid @RequestBody InternalUserRegistrationResource internalUserRegistrationResource); @PostMapping("/internal/edit") RestResult<Void> editInternalUser(@Valid @RequestBody EditUserResource editUserResource); @GetMapping("/find-all/") RestResult<List<UserResource>> findAll(); @GetMapping("/find-external-users") RestResult<List<UserOrganisationResource>> findExternalUsers(@RequestParam String searchString,
@RequestParam SearchCategory searchCategory); @GetMapping("/find-by-email/{email}/") RestResult<UserResource> findByEmail(@PathVariable String email); @GetMapping("/find-assignable-users/{applicationId}") RestResult<Set<UserResource>> findAssignableUsers(@PathVariable long applicationId); @GetMapping("/find-related-users/{applicationId}") RestResult<Set<UserResource>> findRelatedUsers(@PathVariable long applicationId); @GetMapping("/" + URL_SEND_PASSWORD_RESET_NOTIFICATION + "/{emailAddress}/") RestResult<Void> sendPasswordResetNotification(@PathVariable String emailAddress); @GetMapping("/" + URL_CHECK_PASSWORD_RESET_HASH + "/{hash}") RestResult<Void> checkPasswordReset(@PathVariable String hash); @PostMapping("/" + URL_PASSWORD_RESET + "/{hash}") RestResult<Void> resetPassword(@PathVariable String hash, @RequestBody final String password); @GetMapping("/" + URL_VERIFY_EMAIL + "/{hash}") RestResult<Void> verifyEmail(@PathVariable String hash); @PutMapping("/" + URL_RESEND_EMAIL_VERIFICATION_NOTIFICATION + "/{emailAddress}/") RestResult<Void> resendEmailVerificationNotification(@PathVariable String emailAddress); @PostMapping("/id/{userId}/agree-new-site-terms-and-conditions") RestResult<Void> agreeNewSiteTermsAndConditions(@PathVariable long userId); @PostMapping("/update-details") RestResult<Void> updateDetails(@RequestBody UserResource userResource); @PutMapping("{id}/update-email/{email:.+}") RestResult<Void> updateEmail(@PathVariable long id, @PathVariable String email); @PostMapping("/id/{id}/deactivate") RestResult<Void> deactivateUser(@PathVariable long id); @PostMapping("/id/{id}/reactivate") RestResult<Void> reactivateUser(@PathVariable long id); @PostMapping("{id}/grant/{role}") RestResult<Void> grantRole(@PathVariable long id, @PathVariable Role role); static final Sort DEFAULT_USER_SORT; } | @Test public void resendEmailVerificationNotification() throws Exception { final String emailAddress = "[email protected]"; final UserResource userResource = newUserResource().build(); when(userServiceMock.findInactiveByEmail(emailAddress)).thenReturn(serviceSuccess(userResource)); when(registrationServiceMock.resendUserVerificationEmail(userResource)).thenReturn(serviceSuccess()); mockMvc.perform(put("/user/resend-email-verification-notification/{emailAddress}/", emailAddress)) .andExpect(status().isOk()); verify(registrationServiceMock, only()).resendUserVerificationEmail(userResource); } |
SpendProfileServiceImpl extends BaseTransactionalService implements SpendProfileService { private ServiceResult<Void> approveSpendProfile(ApprovalType approvalType, Project project) { return getCurrentlyLoggedInUser().andOnSuccess(user -> { if (approvalType.equals(APPROVED)) { if (spendProfileWorkflowHandler.spendProfileApproved(project, user)) return serviceSuccess(); else return serviceFailure(SPEND_PROFILE_CANNOT_BE_APPROVED); } if (approvalType.equals(REJECTED)) { if (spendProfileWorkflowHandler.spendProfileRejected(project, user)) return serviceSuccess(); else return serviceFailure(SPEND_PROFILE_CANNOT_BE_REJECTED); } return serviceFailure(SPEND_PROFILE_NOT_READY_TO_APPROVE); }); } @Override @Transactional ServiceResult<Void> generateSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> approveOrRejectSpendProfile(Long projectId, ApprovalType approvalType); @Override ServiceResult<ApprovalType> getSpendProfileStatusByProjectId(Long projectId); @Override ServiceResult<ApprovalType> getSpendProfileStatus(Long projectId); @Override ServiceResult<SpendProfileTableResource> getSpendProfileTable(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileCSVResource> getSpendProfileCSV(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileResource> getSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> saveSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId, SpendProfileTableResource table); @Override @Transactional ServiceResult<Void> markSpendProfileComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> deleteSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> completeSpendProfilesReview(Long projectId); static final String EMPTY_CELL; } | @Test public void approveSpendProfile() { List<SpendProfile> spendProfileList = getSpendProfilesAndSetWhenSpendProfileRepositoryMock(projectId); Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).withSpendProfileSubmittedDate(ZonedDateTime.now()).build(); when(projectRepository.findById(projectId)).thenReturn(Optional.of(project)); when(spendProfileWorkflowHandler.isReadyToApprove(project)).thenReturn(true); Long userId = 1234L; User user = newUser().withId(userId).build(); UserResource loggedInUser = newUserResource().withId(user.getId()).build(); setLoggedInUser(loggedInUser); when(userRepository.findById(userId)).thenReturn(Optional.of(user)); when(spendProfileWorkflowHandler.spendProfileApproved(project, user)).thenReturn(true); ServiceResult<Void> result = service.approveOrRejectSpendProfile(projectId, ApprovalType.APPROVED); assertTrue(result.isSuccess()); verify(spendProfileRepository).saveAll(spendProfileList); verify(spendProfileWorkflowHandler).spendProfileApproved(project, user); } |
SpendProfileServiceImpl extends BaseTransactionalService implements SpendProfileService { @Override @Transactional public ServiceResult<Void> approveOrRejectSpendProfile(Long projectId, ApprovalType approvalType) { Project project = projectRepository.findById(projectId).orElse(null); if (null != project && spendProfileWorkflowHandler.isReadyToApprove(project) && (APPROVED.equals(approvalType) || REJECTED.equals(approvalType))) { updateApprovalOfSpendProfile(projectId, approvalType); return approveSpendProfile(approvalType, project); } else { return serviceFailure(SPEND_PROFILE_NOT_READY_TO_APPROVE); } } @Override @Transactional ServiceResult<Void> generateSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> approveOrRejectSpendProfile(Long projectId, ApprovalType approvalType); @Override ServiceResult<ApprovalType> getSpendProfileStatusByProjectId(Long projectId); @Override ServiceResult<ApprovalType> getSpendProfileStatus(Long projectId); @Override ServiceResult<SpendProfileTableResource> getSpendProfileTable(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileCSVResource> getSpendProfileCSV(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileResource> getSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> saveSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId, SpendProfileTableResource table); @Override @Transactional ServiceResult<Void> markSpendProfileComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> deleteSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> completeSpendProfilesReview(Long projectId); static final String EMPTY_CELL; } | @Test public void rejectSpendProfile() { Long projectId = 4234L; List<SpendProfile> spendProfileList = getSpendProfilesAndSetWhenSpendProfileRepositoryMock(projectId); Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).withSpendProfileSubmittedDate(ZonedDateTime.now()).build(); when(spendProfileWorkflowHandler.isReadyToApprove(project)).thenReturn(true); when(projectRepository.findById(projectId)).thenReturn(Optional.of(project)); Long userId = 1234L; UserResource loggedInUser = newUserResource().withId(userId).build(); User user = newUser().withId(loggedInUser.getId()).build(); setLoggedInUser(loggedInUser); when(userRepository.findById(userId)).thenReturn(Optional.of(user)); when(spendProfileWorkflowHandler.spendProfileRejected(project, user)).thenReturn(true); ServiceResult<Void> resultNew = service.approveOrRejectSpendProfile(projectId, ApprovalType.REJECTED); assertTrue(resultNew.isSuccess()); assertNull(project.getSpendProfileSubmittedDate()); verify(spendProfileRepository).saveAll(spendProfileList); verify(spendProfileWorkflowHandler).spendProfileRejected(project, user); }
@Test public void approveSpendProfileProcessNotApproved() { List<SpendProfile> spendProfileList = getSpendProfilesAndSetWhenSpendProfileRepositoryMock(projectId); Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).withSpendProfileSubmittedDate(ZonedDateTime.now()).build(); when(projectRepository.findById(projectId)).thenReturn(Optional.of(project)); when(spendProfileWorkflowHandler.isReadyToApprove(project)).thenReturn(true); Long userId = 1234L; User user = newUser().withId(userId).build(); UserResource loggedInUser = newUserResource().withId(user.getId()).build(); setLoggedInUser(loggedInUser); when(userRepository.findById(userId)).thenReturn(Optional.of(user)); when(spendProfileWorkflowHandler.spendProfileApproved(project, user)).thenReturn(false); ServiceResult<Void> result = service.approveOrRejectSpendProfile(projectId, ApprovalType.APPROVED); assertFalse(result.isSuccess()); assertEquals(SPEND_PROFILE_CANNOT_BE_APPROVED.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); verify(spendProfileRepository).saveAll(spendProfileList); verify(spendProfileWorkflowHandler).spendProfileApproved(project, user); }
@Test public void rejectSpendProfileNotReadyToApprove() { Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).withSpendProfileSubmittedDate(ZonedDateTime.now()).build(); when(projectRepository.findById(projectId)).thenReturn(Optional.of(project)); when(spendProfileWorkflowHandler.isReadyToApprove(project)).thenReturn(false); ServiceResult<Void> result = service.approveOrRejectSpendProfile(projectId, ApprovalType.REJECTED); assertFalse(result.isSuccess()); assertEquals(SPEND_PROFILE_NOT_READY_TO_APPROVE.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); }
@Test public void approveSpendProfileInvalidApprovalType() { Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).withSpendProfileSubmittedDate(ZonedDateTime.now()).build(); when(projectRepository.findById(projectId)).thenReturn(Optional.of(project)); when(spendProfileWorkflowHandler.isReadyToApprove(project)).thenReturn(true); ServiceResult<Void> result = service.approveOrRejectSpendProfile(projectId, ApprovalType.UNSET); assertFalse(result.isSuccess()); assertEquals(SPEND_PROFILE_NOT_READY_TO_APPROVE.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); }
@Test public void approveSpendProfileNotReadyToApprove() { Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).withSpendProfileSubmittedDate(ZonedDateTime.now()).build(); when(projectRepository.findById(projectId)).thenReturn(Optional.of(project)); when(spendProfileWorkflowHandler.isReadyToApprove(project)).thenReturn(false); ServiceResult<Void> result = service.approveOrRejectSpendProfile(projectId, ApprovalType.APPROVED); assertFalse(result.isSuccess()); assertEquals(SPEND_PROFILE_NOT_READY_TO_APPROVE.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); }
@Test public void rejectSpendProfileFails() { Long projectId = 4234L; Project project = newProject().withId(projectId).withDuration(3L).withTargetStartDate(LocalDate.of(2018, 3, 1)).withSpendProfileSubmittedDate(ZonedDateTime.now()).build(); when(spendProfileWorkflowHandler.isReadyToApprove(project)).thenReturn(true); when(projectRepository.findById(projectId)).thenReturn(Optional.of(project)); Long userId = 1234L; UserResource loggedInUser = newUserResource().withId(userId).build(); User user = newUser().withId(loggedInUser.getId()).build(); setLoggedInUser(loggedInUser); when(userRepository.findById(userId)).thenReturn(Optional.of(user)); when(spendProfileWorkflowHandler.spendProfileRejected(project, user)).thenReturn(false); ServiceResult<Void> result = service.approveOrRejectSpendProfile(projectId, ApprovalType.REJECTED); assertFalse(result.isSuccess()); assertEquals(SPEND_PROFILE_CANNOT_BE_REJECTED.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); }
@Test public void approveSpendProfileNoProject() { when(projectRepository.findById(projectId)).thenReturn(Optional.empty()); ServiceResult<Void> result = service.approveOrRejectSpendProfile(projectId, ApprovalType.APPROVED); assertFalse(result.isSuccess()); assertEquals(SPEND_PROFILE_NOT_READY_TO_APPROVE.getErrorKey(), result.getFailure().getErrors().get(0).getErrorKey()); } |
SpendProfileServiceImpl extends BaseTransactionalService implements SpendProfileService { @Override @Transactional public ServiceResult<Void> deleteSpendProfile(Long projectId) { List<SpendProfile> spendProfiles = spendProfileRepository.findByProjectId(projectId); Project project = getProject(projectId).getSuccess(); project.getSpendProfiles().removeAll(spendProfiles); project.setSpendProfileSubmittedDate(null); spendProfileRepository.deleteAll(spendProfiles); spendProfileWorkflowHandler.spendProfileDeleted(getProject(projectId).getSuccess(), getCurrentlyLoggedInUser().getSuccess()); return serviceSuccess(); } @Override @Transactional ServiceResult<Void> generateSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> approveOrRejectSpendProfile(Long projectId, ApprovalType approvalType); @Override ServiceResult<ApprovalType> getSpendProfileStatusByProjectId(Long projectId); @Override ServiceResult<ApprovalType> getSpendProfileStatus(Long projectId); @Override ServiceResult<SpendProfileTableResource> getSpendProfileTable(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileCSVResource> getSpendProfileCSV(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileResource> getSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> saveSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId, SpendProfileTableResource table); @Override @Transactional ServiceResult<Void> markSpendProfileComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> deleteSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> completeSpendProfilesReview(Long projectId); static final String EMPTY_CELL; } | @Test public void deleteSpendProfile() { Long userId = 1234L; UserResource loggedInUser = newUserResource().withId(userId).build(); User user = newUser().withId(loggedInUser.getId()).build(); setLoggedInUser(loggedInUser); Long projectId = 4234L; List<SpendProfile> spendProfileList = getSpendProfilesAndSetWhenSpendProfileRepositoryMock(projectId); Project project = newProject().withId(projectId).withSpendProfileSubmittedDate(ZonedDateTime.now()).build(); when(projectRepository.findById(projectId)).thenReturn(Optional.of(project)); when(userRepository.findById(userId)).thenReturn(Optional.of(user)); when(spendProfileRepository.findByProjectId(projectId)).thenReturn(spendProfileList); when(spendProfileWorkflowHandler.spendProfileDeleted(project, user)).thenReturn(true); ServiceResult<Void> result = service.deleteSpendProfile(projectId); assertTrue(result.isSuccess()); assertNull(project.getSpendProfileSubmittedDate()); } |
UserController { @GetMapping("/find-all/") public RestResult<List<UserResource>> findAll() { return baseUserService.findAll().toGetResponse(); } @GetMapping("/uid/{uid}") RestResult<UserResource> getUserByUid(@PathVariable String uid); @GetMapping("/id/{id}") RestResult<UserResource> getUserById(@PathVariable long id); @PostMapping RestResult<UserResource> createUser(@RequestBody UserCreationResource userCreationResource); @GetMapping("/find-by-role/{userRole}") RestResult<List<UserResource>> findByRole(@PathVariable Role userRole); @GetMapping("/find-by-role-and-status/{userRole}/status/{userStatus}") RestResult<List<UserResource>> findByRoleAndUserStatus(@PathVariable Role userRole, @PathVariable UserStatus userStatus); @GetMapping("/active") RestResult<ManageUserPageResource> findActiveUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @GetMapping("/inactive") RestResult<ManageUserPageResource> findInactiveUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @GetMapping("/external/active") RestResult<ManageUserPageResource> findActiveExternalUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @GetMapping("/external/inactive") RestResult<ManageUserPageResource> findInactiveExternalUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @PostMapping("/internal/create/{inviteHash}") RestResult<Void> createInternalUser(@PathVariable("inviteHash") String inviteHash, @Valid @RequestBody InternalUserRegistrationResource internalUserRegistrationResource); @PostMapping("/internal/edit") RestResult<Void> editInternalUser(@Valid @RequestBody EditUserResource editUserResource); @GetMapping("/find-all/") RestResult<List<UserResource>> findAll(); @GetMapping("/find-external-users") RestResult<List<UserOrganisationResource>> findExternalUsers(@RequestParam String searchString,
@RequestParam SearchCategory searchCategory); @GetMapping("/find-by-email/{email}/") RestResult<UserResource> findByEmail(@PathVariable String email); @GetMapping("/find-assignable-users/{applicationId}") RestResult<Set<UserResource>> findAssignableUsers(@PathVariable long applicationId); @GetMapping("/find-related-users/{applicationId}") RestResult<Set<UserResource>> findRelatedUsers(@PathVariable long applicationId); @GetMapping("/" + URL_SEND_PASSWORD_RESET_NOTIFICATION + "/{emailAddress}/") RestResult<Void> sendPasswordResetNotification(@PathVariable String emailAddress); @GetMapping("/" + URL_CHECK_PASSWORD_RESET_HASH + "/{hash}") RestResult<Void> checkPasswordReset(@PathVariable String hash); @PostMapping("/" + URL_PASSWORD_RESET + "/{hash}") RestResult<Void> resetPassword(@PathVariable String hash, @RequestBody final String password); @GetMapping("/" + URL_VERIFY_EMAIL + "/{hash}") RestResult<Void> verifyEmail(@PathVariable String hash); @PutMapping("/" + URL_RESEND_EMAIL_VERIFICATION_NOTIFICATION + "/{emailAddress}/") RestResult<Void> resendEmailVerificationNotification(@PathVariable String emailAddress); @PostMapping("/id/{userId}/agree-new-site-terms-and-conditions") RestResult<Void> agreeNewSiteTermsAndConditions(@PathVariable long userId); @PostMapping("/update-details") RestResult<Void> updateDetails(@RequestBody UserResource userResource); @PutMapping("{id}/update-email/{email:.+}") RestResult<Void> updateEmail(@PathVariable long id, @PathVariable String email); @PostMapping("/id/{id}/deactivate") RestResult<Void> deactivateUser(@PathVariable long id); @PostMapping("/id/{id}/reactivate") RestResult<Void> reactivateUser(@PathVariable long id); @PostMapping("{id}/grant/{role}") RestResult<Void> grantRole(@PathVariable long id, @PathVariable Role role); static final Sort DEFAULT_USER_SORT; } | @Test public void userControllerShouldReturnAllUsers() throws Exception { UserResource testUser1 = newUserResource().withId(1L).withFirstName("test").withLastName("User1").withEmail("[email protected]").build(); UserResource testUser2 = newUserResource().withId(2L).withFirstName("test").withLastName("User2").withEmail("[email protected]").build(); UserResource testUser3 = newUserResource().withId(3L).withFirstName("test").withLastName("User3").withEmail("[email protected]").build(); List<UserResource> users = new ArrayList<>(); users.add(testUser1); users.add(testUser2); users.add(testUser3); when(baseUserServiceMock.findAll()).thenReturn(serviceSuccess(users)); mockMvc.perform(get("/user/find-all/") .header("IFS_AUTH_TOKEN", "123abc")) .andExpect(status().isOk()) .andExpect(jsonPath("[0]id", is((Number) testUser1.getId().intValue()))) .andExpect(jsonPath("[0]firstName", is(testUser1.getFirstName()))) .andExpect(jsonPath("[0]lastName", is(testUser1.getLastName()))) .andExpect(jsonPath("[0]imageUrl", is(testUser1.getImageUrl()))) .andExpect(jsonPath("[0]uid", is(testUser1.getUid()))) .andExpect(jsonPath("[1]id", is((Number) testUser2.getId().intValue()))) .andExpect(jsonPath("[1]firstName", is(testUser2.getFirstName()))) .andExpect(jsonPath("[1]lastName", is(testUser2.getLastName()))) .andExpect(jsonPath("[1]imageUrl", is(testUser2.getImageUrl()))) .andExpect(jsonPath("[1]uid", is(testUser2.getUid()))) .andExpect(jsonPath("[2]id", is((Number) testUser3.getId().intValue()))) .andExpect(jsonPath("[2]firstName", is(testUser3.getFirstName()))) .andExpect(jsonPath("[2]lastName", is(testUser3.getLastName()))) .andExpect(jsonPath("[2]imageUrl", is(testUser3.getImageUrl()))) .andExpect(jsonPath("[2]uid", is(testUser3.getUid()))) .andDo(document("user/get-all-users")); } |
SpendProfileServiceImpl extends BaseTransactionalService implements SpendProfileService { @Override @Transactional public ServiceResult<Void> saveSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId, SpendProfileTableResource table) { return validateSpendProfileCosts(table) .andOnSuccess(() -> saveSpendProfileData(projectOrganisationCompositeId, table, false)); } @Override @Transactional ServiceResult<Void> generateSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> approveOrRejectSpendProfile(Long projectId, ApprovalType approvalType); @Override ServiceResult<ApprovalType> getSpendProfileStatusByProjectId(Long projectId); @Override ServiceResult<ApprovalType> getSpendProfileStatus(Long projectId); @Override ServiceResult<SpendProfileTableResource> getSpendProfileTable(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileCSVResource> getSpendProfileCSV(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileResource> getSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> saveSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId, SpendProfileTableResource table); @Override @Transactional ServiceResult<Void> markSpendProfileComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> deleteSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> completeSpendProfilesReview(Long projectId); static final String EMPTY_CELL; } | @Test public void saveSpendProfileWhenValidationFails() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); SpendProfileTableResource table = new SpendProfileTableResource(); table.setMonthlyCostsPerCategoryMap(Collections.emptyMap()); ValidationMessages validationMessages = new ValidationMessages(); validationMessages.setErrors(Collections.singletonList(mockedError)); when(validationUtil.validateSpendProfileTableResource(eq(table))).thenReturn(Optional.of(validationMessages)); ServiceResult<Void> result = service.saveSpendProfile(projectOrganisationCompositeId, table); assertFalse(result.isSuccess()); }
@Test public void saveSpendProfileEnsureSpendProfileDomainIsCorrectlyUpdated() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); SpendProfileTableResource table = new SpendProfileTableResource(); table.setEligibleCostPerCategoryMap(asMap( 173L, new BigDecimal("100"), 174L, new BigDecimal("180"), 175L, new BigDecimal("55"))); table.setMonthlyCostsPerCategoryMap(asMap( 173L, asList(new BigDecimal("30"), new BigDecimal("30"), new BigDecimal("40")), 174L, asList(new BigDecimal("70"), new BigDecimal("50"), new BigDecimal("60")), 175L, asList(new BigDecimal("50"), new BigDecimal("5"), new BigDecimal("0")))); List<Cost> spendProfileFigures = buildCostsForCategories(Arrays.asList(173L, 174L, 175L), 3); User generatedBy = newUser().build(); Calendar generatedDate = Calendar.getInstance(); SpendProfile spendProfileInDB = new SpendProfile(null, newProject().build(), null, Collections.emptyList(), spendProfileFigures, generatedBy, generatedDate, false); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(Optional.of(spendProfileInDB)); when(validationUtil.validateSpendProfileTableResource(eq(table))).thenReturn(Optional.empty()); assertCostForCategoryForGivenMonth(spendProfileInDB, 173L, 0, BigDecimal.ONE); assertCostForCategoryForGivenMonth(spendProfileInDB, 173L, 1, BigDecimal.ONE); assertCostForCategoryForGivenMonth(spendProfileInDB, 173L, 2, BigDecimal.ONE); assertCostForCategoryForGivenMonth(spendProfileInDB, 174L, 0, BigDecimal.ONE); assertCostForCategoryForGivenMonth(spendProfileInDB, 174L, 1, BigDecimal.ONE); assertCostForCategoryForGivenMonth(spendProfileInDB, 174L, 2, BigDecimal.ONE); assertCostForCategoryForGivenMonth(spendProfileInDB, 175L, 0, BigDecimal.ONE); assertCostForCategoryForGivenMonth(spendProfileInDB, 175L, 1, BigDecimal.ONE); assertCostForCategoryForGivenMonth(spendProfileInDB, 175L, 2, BigDecimal.ONE); ServiceResult<Void> result = service.saveSpendProfile(projectOrganisationCompositeId, table); assertTrue(result.isSuccess()); assertCostForCategoryForGivenMonth(spendProfileInDB, 173L, 0, new BigDecimal("30")); assertCostForCategoryForGivenMonth(spendProfileInDB, 173L, 1, new BigDecimal("30")); assertCostForCategoryForGivenMonth(spendProfileInDB, 173L, 2, new BigDecimal("40")); assertCostForCategoryForGivenMonth(spendProfileInDB, 174L, 0, new BigDecimal("70")); assertCostForCategoryForGivenMonth(spendProfileInDB, 174L, 1, new BigDecimal("50")); assertCostForCategoryForGivenMonth(spendProfileInDB, 174L, 2, new BigDecimal("60")); assertCostForCategoryForGivenMonth(spendProfileInDB, 175L, 0, new BigDecimal("50")); assertCostForCategoryForGivenMonth(spendProfileInDB, 175L, 1, new BigDecimal("5")); assertCostForCategoryForGivenMonth(spendProfileInDB, 175L, 2, new BigDecimal("0")); verify(spendProfileRepository).save(spendProfileInDB); } |
SpendProfileServiceImpl extends BaseTransactionalService implements SpendProfileService { @Override @Transactional public ServiceResult<Void> markSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId) { SpendProfileTableResource table = getSpendProfileTable(projectOrganisationCompositeId).getSuccess(); return saveSpendProfileData(projectOrganisationCompositeId, table, false); } @Override @Transactional ServiceResult<Void> generateSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> approveOrRejectSpendProfile(Long projectId, ApprovalType approvalType); @Override ServiceResult<ApprovalType> getSpendProfileStatusByProjectId(Long projectId); @Override ServiceResult<ApprovalType> getSpendProfileStatus(Long projectId); @Override ServiceResult<SpendProfileTableResource> getSpendProfileTable(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileCSVResource> getSpendProfileCSV(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileResource> getSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> saveSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId, SpendProfileTableResource table); @Override @Transactional ServiceResult<Void> markSpendProfileComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> deleteSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> completeSpendProfilesReview(Long projectId); static final String EMPTY_CELL; } | @Test public void markSpendProfileIncomplete() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); Project projectInDB = ProjectBuilder.newProject() .withDuration(3L) .withTargetStartDate(LocalDate.of(2018, 3, 1)) .withId(projectId) .build(); SpendProfile spendProfileInDB = createSpendProfile(projectInDB, asMap( 1L, new BigDecimal("100"), 2L, new BigDecimal("180"), 3L, new BigDecimal("55")), asMap( 1L, asList(new BigDecimal("30"), new BigDecimal("30"), new BigDecimal("50")), 2L, asList(new BigDecimal("70"), new BigDecimal("50"), new BigDecimal("60")), 3L, asList(new BigDecimal("50"), new BigDecimal("5"), new BigDecimal("0"))) ); spendProfileInDB.setMarkedAsComplete(true); OrganisationType organisationType = newOrganisationType().withOrganisationType(BUSINESS).build(); Organisation organisation1 = newOrganisation().withId(organisationId).withOrganisationType(organisationType).withName("TEST").build(); when(organisationRepository.findById(organisation1.getId())).thenReturn(Optional.of(organisation1)); when(projectRepository.findById(projectId)).thenReturn(Optional.of(projectInDB)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(Optional.of(spendProfileInDB)); ServiceResult<Void> result = service.markSpendProfileIncomplete(projectOrganisationCompositeId); assertTrue(result.isSuccess()); assertFalse(spendProfileInDB.isMarkedAsComplete()); } |
SpendProfileServiceImpl extends BaseTransactionalService implements SpendProfileService { @Override @Transactional public ServiceResult<Void> markSpendProfileComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId) { SpendProfileTableResource table = getSpendProfileTable(projectOrganisationCompositeId).getSuccess(); if (table.getValidationMessages().hasErrors()) { return serviceFailure(SPEND_PROFILE_CANNOT_MARK_AS_COMPLETE_BECAUSE_SPEND_HIGHER_THAN_ELIGIBLE); } else { return saveSpendProfileData(projectOrganisationCompositeId, table, true); } } @Override @Transactional ServiceResult<Void> generateSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> approveOrRejectSpendProfile(Long projectId, ApprovalType approvalType); @Override ServiceResult<ApprovalType> getSpendProfileStatusByProjectId(Long projectId); @Override ServiceResult<ApprovalType> getSpendProfileStatus(Long projectId); @Override ServiceResult<SpendProfileTableResource> getSpendProfileTable(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileCSVResource> getSpendProfileCSV(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileResource> getSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> saveSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId, SpendProfileTableResource table); @Override @Transactional ServiceResult<Void> markSpendProfileComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> deleteSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> completeSpendProfilesReview(Long projectId); static final String EMPTY_CELL; } | @Test public void markSpendProfileWhenActualTotalsGreaterThanEligibleCosts() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); Project projectInDB = ProjectBuilder.newProject() .withDuration(3L) .withTargetStartDate(LocalDate.of(2018, 3, 1)) .build(); SpendProfile spendProfileInDB = createSpendProfile(projectInDB, asMap( 1L, new BigDecimal("100"), 2L, new BigDecimal("180"), 3L, new BigDecimal("55")), asMap( 1L, asList(new BigDecimal("30"), new BigDecimal("30"), new BigDecimal("50")), 2L, asList(new BigDecimal("70"), new BigDecimal("50"), new BigDecimal("60")), 3L, asList(new BigDecimal("50"), new BigDecimal("5"), new BigDecimal("0"))) ); OrganisationType organisationType = newOrganisationType().withOrganisationType(BUSINESS).build(); Organisation organisation1 = newOrganisation().withId(organisationId).withOrganisationType(organisationType).withName("TEST").build(); when(organisationRepository.findById(organisation1.getId())).thenReturn(Optional.of(organisation1)); when(projectRepository.findById(projectId)).thenReturn(Optional.of(projectInDB)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(Optional.of(spendProfileInDB)); ServiceResult<Void> result = service.markSpendProfileComplete(projectOrganisationCompositeId); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(SPEND_PROFILE_CANNOT_MARK_AS_COMPLETE_BECAUSE_SPEND_HIGHER_THAN_ELIGIBLE)); }
@Test public void markSpendProfileSuccessWhenActualTotalsAreLessThanEligibleCosts() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(projectId, organisationId); Project projectInDB = ProjectBuilder.newProject() .withDuration(3L) .withTargetStartDate(LocalDate.of(2018, 3, 1)) .build(); SpendProfile spendProfileInDB = createSpendProfile(projectInDB, asMap( 1L, new BigDecimal("100"), 2L, new BigDecimal("180"), 3L, new BigDecimal("55")), asMap( 1L, asList(new BigDecimal("30"), new BigDecimal("30"), new BigDecimal("40")), 2L, asList(new BigDecimal("70"), new BigDecimal("10"), new BigDecimal("60")), 3L, asList(new BigDecimal("50"), new BigDecimal("5"), new BigDecimal("0"))) ); OrganisationType organisationType = newOrganisationType().withOrganisationType(BUSINESS).build(); Organisation organisation1 = newOrganisation().withId(organisationId).withOrganisationType(organisationType).withName("TEST").build(); when(organisationRepository.findById(organisation1.getId())).thenReturn(Optional.of(organisation1)); when(projectRepository.findById(projectId)).thenReturn(Optional.of(projectInDB)); when(spendProfileRepository.findOneByProjectIdAndOrganisationId(projectId, organisationId)).thenReturn(Optional.of(spendProfileInDB)); ServiceResult<Void> result = service.markSpendProfileComplete(projectOrganisationCompositeId); assertTrue(result.isSuccess()); } |
SpendProfileServiceImpl extends BaseTransactionalService implements SpendProfileService { @Override @Transactional public ServiceResult<Void> completeSpendProfilesReview(Long projectId) { return getProject(projectId).andOnSuccess(project -> { if (project.getSpendProfiles().stream().anyMatch(spendProfile -> !spendProfile.isMarkedAsComplete())) { return serviceFailure(SPEND_PROFILES_MUST_BE_COMPLETE_BEFORE_SUBMISSION); } if (spendProfileWorkflowHandler.submit(project)) { project.setSpendProfileSubmittedDate(ZonedDateTime.now()); updateApprovalOfSpendProfile(projectId, ApprovalType.UNSET); return serviceSuccess(); } else { return serviceFailure(SPEND_PROFILES_HAVE_ALREADY_BEEN_SUBMITTED); } }); } @Override @Transactional ServiceResult<Void> generateSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> approveOrRejectSpendProfile(Long projectId, ApprovalType approvalType); @Override ServiceResult<ApprovalType> getSpendProfileStatusByProjectId(Long projectId); @Override ServiceResult<ApprovalType> getSpendProfileStatus(Long projectId); @Override ServiceResult<SpendProfileTableResource> getSpendProfileTable(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileCSVResource> getSpendProfileCSV(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override ServiceResult<SpendProfileResource> getSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> saveSpendProfile(ProjectOrganisationCompositeId projectOrganisationCompositeId, SpendProfileTableResource table); @Override @Transactional ServiceResult<Void> markSpendProfileComplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> markSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId); @Override @Transactional ServiceResult<Void> deleteSpendProfile(Long projectId); @Override @Transactional ServiceResult<Void> completeSpendProfilesReview(Long projectId); static final String EMPTY_CELL; } | @Test public void completeSpendProfilesReviewSuccess() { Project projectInDb = new Project(); projectInDb.setSpendProfileSubmittedDate(null); SpendProfile spendProfileInDb = new SpendProfile(); spendProfileInDb.setMarkedAsComplete(true); projectInDb.setSpendProfiles(singletonList(spendProfileInDb)); when(projectRepository.findById(projectId)).thenReturn(Optional.of(projectInDb)); assertThat(projectInDb.getSpendProfileSubmittedDate(), nullValue()); when(spendProfileWorkflowHandler.submit(projectInDb)).thenReturn(true); ServiceResult<Void> result = service.completeSpendProfilesReview(projectId); assertTrue(result.isSuccess()); assertThat(projectInDb.getSpendProfileSubmittedDate(), notNullValue()); }
@Test public void completeSpendProfilesReviewFailureWhenSpendProfileIncomplete() { Project projectInDb = new Project(); projectInDb.setSpendProfileSubmittedDate(null); SpendProfile spendProfileInDb = new SpendProfile(); spendProfileInDb.setMarkedAsComplete(false); projectInDb.setSpendProfiles(singletonList(spendProfileInDb)); when(projectRepository.findById(projectId)).thenReturn(Optional.of(projectInDb)); assertThat(projectInDb.getSpendProfileSubmittedDate(), nullValue()); ServiceResult<Void> result = service.completeSpendProfilesReview(projectId); assertTrue(result.isFailure()); }
@Test public void completeSpendProfilesReviewFailureWhenAlreadySubmitted() { Project projectInDb = new Project(); projectInDb.setSpendProfileSubmittedDate(ZonedDateTime.now()); SpendProfile spendProfileInDb = new SpendProfile(); spendProfileInDb.setMarkedAsComplete(true); projectInDb.setSpendProfiles(singletonList(spendProfileInDb)); when(projectRepository.findById(projectId)).thenReturn(Optional.of(projectInDb)); ServiceResult<Void> result = service.completeSpendProfilesReview(projectId); assertTrue(result.isFailure()); } |
ProjectPartnerInviteServiceImpl extends BaseTransactionalService implements ProjectPartnerInviteService { @Override @Transactional public ServiceResult<Void> invitePartnerOrganisation(long projectId, SendProjectPartnerInviteResource invite) { return find(projectRepository.findById(projectId), notFoundError(Project.class, projectId)).andOnSuccess(project -> projectInviteValidator.validate(projectId, invite).andOnSuccess(() -> { InviteOrganisation inviteOrganisation = new InviteOrganisation(); inviteOrganisation.setOrganisationName(invite.getOrganisationName()); inviteOrganisation = inviteOrganisationRepository.save(inviteOrganisation); ProjectPartnerInvite projectPartnerInvite = new ProjectPartnerInvite(); projectPartnerInvite.setInviteOrganisation(inviteOrganisation); projectPartnerInvite.setEmail(invite.getEmail()); projectPartnerInvite.setName(invite.getUserName()); projectPartnerInvite.setHash(generateInviteHash()); projectPartnerInvite.setTarget(project); projectPartnerInvite = projectPartnerInviteRepository.save(projectPartnerInvite); return sendInviteNotification(projectPartnerInvite) .andOnSuccessReturnVoid((sentInvite) -> sentInvite.send(loggedInUserSupplier.get(), ZonedDateTime.now())); }) ); } @Override @Transactional ServiceResult<Void> invitePartnerOrganisation(long projectId, SendProjectPartnerInviteResource invite); @Override ServiceResult<List<SentProjectPartnerInviteResource>> getPartnerInvites(long projectId); @Override @Transactional ServiceResult<Void> resendInvite(long inviteId); @Override @Transactional ServiceResult<Void> deleteInvite(long inviteId); @Override ServiceResult<SentProjectPartnerInviteResource> getInviteByHash(String hash); @Override @Transactional ServiceResult<Void> acceptInvite(long inviteId, long organisationId); } | @Test public void invite() { setField(service, "webBaseUrl", "webBaseUrl"); long projectId = 1L; String organisationName = "Org"; String userName = "Someone"; String email = "[email protected]"; Application application = newApplication().build(); Organisation leadOrg = newOrganisation() .withName("Lead org") .build(); SendProjectPartnerInviteResource invite = new SendProjectPartnerInviteResource(organisationName, userName, email); Project project = newProject() .withName("Project") .withApplication(application) .withPartnerOrganisations(newPartnerOrganisation() .withOrganisation(leadOrg) .withLeadOrganisation(true) .build(1)) .build(); Map<String, Object> notificationArguments = new HashMap<>(); notificationArguments.put("applicationId", application.getId()); notificationArguments.put("projectName", "Project"); notificationArguments.put("leadOrganisationName", "Lead org"); when(projectRepository.findById(projectId)).thenReturn(of(project)); when(projectInviteValidator.validate(projectId, invite)).thenReturn(serviceSuccess()); when(inviteOrganisationRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); when(projectPartnerInviteRepository.save(any())).thenAnswer(invocation -> { ProjectPartnerInvite projectPartnerInvite = invocation.getArgument(0); notificationArguments.put("inviteUrl", String.format("webBaseUrl/project-setup/project/%d/partner-invite/%s/accept", project.getId(), projectPartnerInvite.getHash())); return projectPartnerInvite; }); NotificationTarget to = new UserNotificationTarget(userName, email); Notification notification = new Notification(systemNotificationSource, singletonList(to), ProjectPartnerInviteServiceImpl.Notifications.INVITE_PROJECT_PARTNER_ORGANISATION, notificationArguments); when(notificationService.sendNotificationWithFlush(notification, NotificationMedium.EMAIL)).thenReturn(serviceSuccess()); User loggedInUser = newUser().build(); when(loggedInUserSupplier.get()).thenReturn(loggedInUser); ServiceResult<Void> result = service.invitePartnerOrganisation(projectId, invite); assertTrue(result.isSuccess()); verify(notificationService).sendNotificationWithFlush(notification, NotificationMedium.EMAIL); } |
ProjectPartnerInviteServiceImpl extends BaseTransactionalService implements ProjectPartnerInviteService { @Override public ServiceResult<List<SentProjectPartnerInviteResource>> getPartnerInvites(long projectId) { return serviceSuccess(projectPartnerInviteRepository.findByProjectId(projectId).stream() .filter(invite -> invite.getStatus() == InviteStatus.SENT) .map(this::mapToSentResource) .collect(toList())); } @Override @Transactional ServiceResult<Void> invitePartnerOrganisation(long projectId, SendProjectPartnerInviteResource invite); @Override ServiceResult<List<SentProjectPartnerInviteResource>> getPartnerInvites(long projectId); @Override @Transactional ServiceResult<Void> resendInvite(long inviteId); @Override @Transactional ServiceResult<Void> deleteInvite(long inviteId); @Override ServiceResult<SentProjectPartnerInviteResource> getInviteByHash(String hash); @Override @Transactional ServiceResult<Void> acceptInvite(long inviteId, long organisationId); } | @Test public void getPartnerInvites() { long projectId = 1L; long inviteId = 2L; long applicationId = 3L; long competitionId = 4L; String email = "[email protected]"; String userName = "Partner"; String organisationName = "Partners Ltd."; ZonedDateTime sentOn = now(); ProjectPartnerInvite invite = new ProjectPartnerInvite(); InviteOrganisation inviteOrganisation = new InviteOrganisation(); invite.setEmail(email); invite.setId(inviteId); invite.setName(userName); invite.setProject(newProject() .withName("project") .withApplication(newApplication() .withId(applicationId) .withCompetition(newCompetition().withId(competitionId).build()) .build()) .build()); setField(invite, "status", InviteStatus.SENT); setField(invite, "sentOn", sentOn); invite.setInviteOrganisation(inviteOrganisation); inviteOrganisation.setOrganisationName(organisationName); when(projectPartnerInviteRepository.findByProjectId(projectId)).thenReturn(singletonList(invite)); ServiceResult<List<SentProjectPartnerInviteResource>> result = service.getPartnerInvites(projectId); SentProjectPartnerInviteResource resource = result.getSuccess().get(0); assertEquals(inviteId, resource.getId()); assertEquals(email, resource.getEmail()); assertEquals(userName, resource.getUserName()); assertEquals(organisationName, resource.getOrganisationName()); assertEquals(sentOn, resource.getSentOn()); assertEquals("project", resource.getProjectName()); assertEquals(applicationId, resource.getApplicationId()); assertEquals(competitionId, resource.getCompetitionId()); } |
UserController { @GetMapping("/id/{id}") public RestResult<UserResource> getUserById(@PathVariable long id) { return baseUserService.getUserById(id).toGetResponse(); } @GetMapping("/uid/{uid}") RestResult<UserResource> getUserByUid(@PathVariable String uid); @GetMapping("/id/{id}") RestResult<UserResource> getUserById(@PathVariable long id); @PostMapping RestResult<UserResource> createUser(@RequestBody UserCreationResource userCreationResource); @GetMapping("/find-by-role/{userRole}") RestResult<List<UserResource>> findByRole(@PathVariable Role userRole); @GetMapping("/find-by-role-and-status/{userRole}/status/{userStatus}") RestResult<List<UserResource>> findByRoleAndUserStatus(@PathVariable Role userRole, @PathVariable UserStatus userStatus); @GetMapping("/active") RestResult<ManageUserPageResource> findActiveUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @GetMapping("/inactive") RestResult<ManageUserPageResource> findInactiveUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @GetMapping("/external/active") RestResult<ManageUserPageResource> findActiveExternalUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @GetMapping("/external/inactive") RestResult<ManageUserPageResource> findInactiveExternalUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @PostMapping("/internal/create/{inviteHash}") RestResult<Void> createInternalUser(@PathVariable("inviteHash") String inviteHash, @Valid @RequestBody InternalUserRegistrationResource internalUserRegistrationResource); @PostMapping("/internal/edit") RestResult<Void> editInternalUser(@Valid @RequestBody EditUserResource editUserResource); @GetMapping("/find-all/") RestResult<List<UserResource>> findAll(); @GetMapping("/find-external-users") RestResult<List<UserOrganisationResource>> findExternalUsers(@RequestParam String searchString,
@RequestParam SearchCategory searchCategory); @GetMapping("/find-by-email/{email}/") RestResult<UserResource> findByEmail(@PathVariable String email); @GetMapping("/find-assignable-users/{applicationId}") RestResult<Set<UserResource>> findAssignableUsers(@PathVariable long applicationId); @GetMapping("/find-related-users/{applicationId}") RestResult<Set<UserResource>> findRelatedUsers(@PathVariable long applicationId); @GetMapping("/" + URL_SEND_PASSWORD_RESET_NOTIFICATION + "/{emailAddress}/") RestResult<Void> sendPasswordResetNotification(@PathVariable String emailAddress); @GetMapping("/" + URL_CHECK_PASSWORD_RESET_HASH + "/{hash}") RestResult<Void> checkPasswordReset(@PathVariable String hash); @PostMapping("/" + URL_PASSWORD_RESET + "/{hash}") RestResult<Void> resetPassword(@PathVariable String hash, @RequestBody final String password); @GetMapping("/" + URL_VERIFY_EMAIL + "/{hash}") RestResult<Void> verifyEmail(@PathVariable String hash); @PutMapping("/" + URL_RESEND_EMAIL_VERIFICATION_NOTIFICATION + "/{emailAddress}/") RestResult<Void> resendEmailVerificationNotification(@PathVariable String emailAddress); @PostMapping("/id/{userId}/agree-new-site-terms-and-conditions") RestResult<Void> agreeNewSiteTermsAndConditions(@PathVariable long userId); @PostMapping("/update-details") RestResult<Void> updateDetails(@RequestBody UserResource userResource); @PutMapping("{id}/update-email/{email:.+}") RestResult<Void> updateEmail(@PathVariable long id, @PathVariable String email); @PostMapping("/id/{id}/deactivate") RestResult<Void> deactivateUser(@PathVariable long id); @PostMapping("/id/{id}/reactivate") RestResult<Void> reactivateUser(@PathVariable long id); @PostMapping("{id}/grant/{role}") RestResult<Void> grantRole(@PathVariable long id, @PathVariable Role role); static final Sort DEFAULT_USER_SORT; } | @Test public void userControllerShouldReturnUserById() throws Exception { UserResource testUser1 = newUserResource().withId(1L).withFirstName("test").withLastName("User1").withEmail("[email protected]").build(); when(baseUserServiceMock.getUserById(testUser1.getId())).thenReturn(serviceSuccess(testUser1)); mockMvc.perform(get("/user/id/" + testUser1.getId()) .header("IFS_AUTH_TOKEN", "123abc")) .andExpect(status().isOk()) .andExpect(jsonPath("id", is((Number) testUser1.getId().intValue()))) .andExpect(jsonPath("firstName", is(testUser1.getFirstName()))) .andExpect(jsonPath("lastName", is(testUser1.getLastName()))) .andExpect(jsonPath("imageUrl", is(testUser1.getImageUrl()))) .andExpect(jsonPath("uid", is(testUser1.getUid()))) .andDo(document("user/get-user")); } |
ProjectPartnerInviteServiceImpl extends BaseTransactionalService implements ProjectPartnerInviteService { @Override @Transactional public ServiceResult<Void> resendInvite(long inviteId) { return find(projectPartnerInviteRepository.findById(inviteId), notFoundError(ProjectPartnerInvite.class, inviteId)) .andOnSuccess(this::sendInviteNotification) .andOnSuccessReturnVoid((sentInvite) -> sentInvite.resend(loggedInUserSupplier.get(), ZonedDateTime.now())); } @Override @Transactional ServiceResult<Void> invitePartnerOrganisation(long projectId, SendProjectPartnerInviteResource invite); @Override ServiceResult<List<SentProjectPartnerInviteResource>> getPartnerInvites(long projectId); @Override @Transactional ServiceResult<Void> resendInvite(long inviteId); @Override @Transactional ServiceResult<Void> deleteInvite(long inviteId); @Override ServiceResult<SentProjectPartnerInviteResource> getInviteByHash(String hash); @Override @Transactional ServiceResult<Void> acceptInvite(long inviteId, long organisationId); } | @Test public void resendInvite() { setField(service, "webBaseUrl", "webBaseUrl"); long inviteId = 2L; String userName = "Someone"; String email = "[email protected]"; Application application = newApplication().build(); Organisation leadOrg = newOrganisation() .withName("Lead org") .build(); Project project = newProject() .withName("Project") .withApplication(application) .withPartnerOrganisations(newPartnerOrganisation() .withOrganisation(leadOrg) .withLeadOrganisation(true) .build(1)) .build(); ProjectPartnerInvite invite = spy(new ProjectPartnerInvite()); invite.setEmail(email); invite.setName(userName); invite.setTarget(project); invite.setHash("hash"); when(projectPartnerInviteRepository.findById(inviteId)).thenReturn(of(invite)); Map<String, Object> notificationArguments = new HashMap<>(); notificationArguments.put("inviteUrl", String.format("webBaseUrl/project-setup/project/%d/partner-invite/%s/accept", project.getId(), invite.getHash())); notificationArguments.put("applicationId", application.getId()); notificationArguments.put("projectName", "Project"); notificationArguments.put("leadOrganisationName", "Lead org"); NotificationTarget to = new UserNotificationTarget(userName, email); Notification notification = new Notification(systemNotificationSource, singletonList(to), ProjectPartnerInviteServiceImpl.Notifications.INVITE_PROJECT_PARTNER_ORGANISATION, notificationArguments); when(notificationService.sendNotificationWithFlush(notification, NotificationMedium.EMAIL)).thenReturn(serviceSuccess()); User loggedInUser = newUser().build(); when(loggedInUserSupplier.get()).thenReturn(loggedInUser); service.resendInvite(inviteId); verify(invite).resend(eq(loggedInUser), any()); verify(notificationService).sendNotificationWithFlush(notification, NotificationMedium.EMAIL); } |
ProjectPartnerInviteServiceImpl extends BaseTransactionalService implements ProjectPartnerInviteService { @Override @Transactional public ServiceResult<Void> deleteInvite(long inviteId) { return find(projectPartnerInviteRepository.findById(inviteId), notFoundError(ProjectPartnerInvite.class, inviteId)) .andOnSuccessReturnVoid(projectPartnerInviteRepository::delete); } @Override @Transactional ServiceResult<Void> invitePartnerOrganisation(long projectId, SendProjectPartnerInviteResource invite); @Override ServiceResult<List<SentProjectPartnerInviteResource>> getPartnerInvites(long projectId); @Override @Transactional ServiceResult<Void> resendInvite(long inviteId); @Override @Transactional ServiceResult<Void> deleteInvite(long inviteId); @Override ServiceResult<SentProjectPartnerInviteResource> getInviteByHash(String hash); @Override @Transactional ServiceResult<Void> acceptInvite(long inviteId, long organisationId); } | @Test public void deleteInvite() { long inviteId = 2L; ProjectPartnerInvite invite = new ProjectPartnerInvite(); when(projectPartnerInviteRepository.findById(inviteId)).thenReturn(of(invite)); service.deleteInvite(inviteId); verify(projectPartnerInviteRepository).delete(invite); } |
ProjectPartnerInviteServiceImpl extends BaseTransactionalService implements ProjectPartnerInviteService { @Override public ServiceResult<SentProjectPartnerInviteResource> getInviteByHash(String hash) { return find(projectPartnerInviteRepository.getByHash(hash), notFoundError(ProjectPartnerInvite.class, hash)) .andOnSuccessReturn(this::mapToSentResource); } @Override @Transactional ServiceResult<Void> invitePartnerOrganisation(long projectId, SendProjectPartnerInviteResource invite); @Override ServiceResult<List<SentProjectPartnerInviteResource>> getPartnerInvites(long projectId); @Override @Transactional ServiceResult<Void> resendInvite(long inviteId); @Override @Transactional ServiceResult<Void> deleteInvite(long inviteId); @Override ServiceResult<SentProjectPartnerInviteResource> getInviteByHash(String hash); @Override @Transactional ServiceResult<Void> acceptInvite(long inviteId, long organisationId); } | @Test public void getInviteByHash() { String hash = "hash"; String email = "[email protected]"; String userName = "Partner"; String organisationName = "Partners Ltd."; long applicationId = 3L; long competitionId = 4L; ZonedDateTime sentOn = now(); ProjectPartnerInvite invite = new ProjectPartnerInvite(); InviteOrganisation inviteOrganisation = new InviteOrganisation(); invite.setEmail(email); invite.setId(1L); invite.setName(userName); invite.setProject(newProject() .withName("project") .withApplication(newApplication() .withId(applicationId) .withCompetition(newCompetition().withId(competitionId).build()) .build()) .build()); setField(invite, "status", InviteStatus.SENT); setField(invite, "sentOn", sentOn); invite.setInviteOrganisation(inviteOrganisation); inviteOrganisation.setOrganisationName(organisationName); when(projectPartnerInviteRepository.getByHash("hash")).thenReturn(invite); ServiceResult<SentProjectPartnerInviteResource> result = service.getInviteByHash(hash); SentProjectPartnerInviteResource resource = result.getSuccess(); assertEquals(1L, resource.getId()); assertEquals(email, resource.getEmail()); assertEquals(userName, resource.getUserName()); assertEquals(organisationName, resource.getOrganisationName()); assertEquals(sentOn, resource.getSentOn()); assertEquals("project", resource.getProjectName()); assertEquals(applicationId, resource.getApplicationId()); assertEquals(competitionId, resource.getCompetitionId()); } |
ProjectPartnerInviteServiceImpl extends BaseTransactionalService implements ProjectPartnerInviteService { @Override @Transactional public ServiceResult<Void> acceptInvite(long inviteId, long organisationId) { return find(projectPartnerInviteRepository.findById(inviteId), notFoundError(ProjectPartnerInvite.class, inviteId)) .andOnSuccess(invite -> find(organisation(organisationId)) .andOnSuccess((organisation) -> { Project project = invite.getProject(); invite.getInviteOrganisation().setOrganisation(organisation); PartnerOrganisation partnerOrganisation = new PartnerOrganisation(project, organisation, false); if (partnerOrganisationRepository.findOneByProjectIdAndOrganisationId(project.getId(), organisation.getId()) != null) { return serviceFailure(ORGANISATION_ALREADY_EXISTS_FOR_PROJECT); } partnerOrganisation = partnerOrganisationRepository.save(partnerOrganisation); linkAddressesToOrganisation(organisation, partnerOrganisation); pendingPartnerProgressRepository.save(new PendingPartnerProgress(partnerOrganisation)); ProjectUser projectUser = new ProjectUser(invite.getUser(), project, ProjectParticipantRole.PROJECT_PARTNER, organisation); projectUser = projectUserRepository.save(projectUser); projectPartnerChangeService.updateProjectWhenPartnersChange(project.getId()); projectFinanceService.createProjectFinance(project.getId(), organisation.getId()); eligibilityWorkflowHandler.projectCreated(partnerOrganisation, projectUser); viabilityWorkflowHandler.projectCreated(partnerOrganisation, projectUser); if (project.getApplication().getCompetition().applicantNotRequiredForViabilityChecks(organisation.getOrganisationTypeEnum())) { viabilityWorkflowHandler.viabilityNotApplicable(partnerOrganisation, null); } invite.open(); activityLogService.recordActivityByProjectIdAndOrganisationIdAndAuthorId(project.getId(), organisationId, invite.getSentBy().getId(), ActivityType.ORGANISATION_ADDED); return serviceSuccess(); })); } @Override @Transactional ServiceResult<Void> invitePartnerOrganisation(long projectId, SendProjectPartnerInviteResource invite); @Override ServiceResult<List<SentProjectPartnerInviteResource>> getPartnerInvites(long projectId); @Override @Transactional ServiceResult<Void> resendInvite(long inviteId); @Override @Transactional ServiceResult<Void> deleteInvite(long inviteId); @Override ServiceResult<SentProjectPartnerInviteResource> getInviteByHash(String hash); @Override @Transactional ServiceResult<Void> acceptInvite(long inviteId, long organisationId); } | @Test public void acceptInvite() { long inviteId = 1L; long organisationId = 2L; Competition competition = newCompetition().withIncludeJesForm(true).build(); Application application = newApplication().withCompetition(competition).build(); Project project = newProject().withApplication(application).build(); ProjectPartnerInvite invite = new ProjectPartnerInvite(); InviteOrganisation inviteOrganisation = newInviteOrganisation().build(); invite.setInviteOrganisation(inviteOrganisation); invite.setProject(project); invite.send(newUser().withId(1l).build(), ZonedDateTime.now()); Organisation organisation = newOrganisation().withId(organisationId).withOrganisationType(OrganisationTypeEnum.RESEARCH) .build(); when(organisationRepository.findById(organisationId)).thenReturn(of(organisation)); when(projectPartnerInviteRepository.findById(inviteId)).thenReturn(of(invite)); when(partnerOrganisationRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); when(projectUserRepository.save(any())).thenAnswer(invocation -> invocation.getArgument(0)); ServiceResult<Void> result = service.acceptInvite(inviteId, organisationId); assertTrue(result.isSuccess()); assertEquals(inviteOrganisation.getOrganisation(), organisation); verify(projectPartnerChangeService, times(1)).updateProjectWhenPartnersChange(project.getId()); verify(projectFinanceService, times(1)).createProjectFinance(project.getId(), organisationId); verify(viabilityWorkflowHandler, times(1)).projectCreated(any(), any()); verify(eligibilityWorkflowHandler, times(1)).projectCreated(any(), any()); verify(viabilityWorkflowHandler, times(1)).viabilityNotApplicable(any(), any()); verify(pendingPartnerProgressRepository, times(1)).save(any()); verifyNoMoreInteractions(projectPartnerChangeService, projectFinanceService, viabilityWorkflowHandler, eligibilityWorkflowHandler, pendingPartnerProgressRepository); } |
ApplicationFundingDecisionController { @PostMapping(value="/{competitionId}") public RestResult<Void> saveFundingDecisionData(@PathVariable("competitionId") final Long competitionId, @RequestBody Map<Long, FundingDecision> applicationFundingDecisions) { return applicationFundingService.saveFundingDecisionData(competitionId, applicationFundingDecisions). toPutResponse(); } @PostMapping(value="/send-notifications") RestResult<Void> sendFundingDecisions(@RequestBody FundingNotificationResource fundingNotificationResource); @PostMapping(value="/{competitionId}") RestResult<Void> saveFundingDecisionData(@PathVariable("competitionId") final Long competitionId, @RequestBody Map<Long, FundingDecision> applicationFundingDecisions); @GetMapping("/notifications-to-send") RestResult<List<FundingDecisionToSendApplicationResource>> getNotificationResourceForApplications(@RequestParam("applicationIds") List<Long> applicationIds); } | @Test public void testSaveApplicationFundingDecisionData() throws Exception { Long competitionId = 1L; Map<Long, FundingDecision> decision = asMap(1L, FundingDecision.FUNDED, 2L, FundingDecision.UNFUNDED); when(applicationFundingServiceMock.saveFundingDecisionData(competitionId, decision)).thenReturn(serviceSuccess()); mockMvc.perform(post("/applicationfunding/1") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(decision))) .andExpect(status().isOk()) .andExpect(content().string("")); verify(applicationFundingServiceMock).saveFundingDecisionData(competitionId, decision); } |
ApplicationNotificationTemplateController { @GetMapping("/successful/{competitionId}") public RestResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(@PathVariable("competitionId") long competitionId) { return applicationNotificationTemplateService.getSuccessfulNotificationTemplate(competitionId).toGetResponse(); } @GetMapping("/successful/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(@PathVariable("competitionId") long competitionId); @GetMapping("/unsuccessful/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(@PathVariable("competitionId") long competitionId); @GetMapping("/ineligible/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(@PathVariable("competitionId") long competitionId); } | @Test public void getSuccessfulNotificationTemplate() throws Exception { Long competitionId = 1L; ApplicationNotificationTemplateResource resource = new ApplicationNotificationTemplateResource(); when(applicationNotificationTemplateService.getSuccessfulNotificationTemplate(competitionId)).thenReturn(serviceSuccess(resource)); mockMvc.perform(get("/application-notification-template/successful/1") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(toJson(resource))); } |
ApplicationNotificationTemplateController { @GetMapping("/unsuccessful/{competitionId}") public RestResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(@PathVariable("competitionId") long competitionId) { return applicationNotificationTemplateService.getUnsuccessfulNotificationTemplate(competitionId).toGetResponse(); } @GetMapping("/successful/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(@PathVariable("competitionId") long competitionId); @GetMapping("/unsuccessful/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(@PathVariable("competitionId") long competitionId); @GetMapping("/ineligible/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(@PathVariable("competitionId") long competitionId); } | @Test public void getUnsuccessfulNotificationTemplate() throws Exception { Long competitionId = 1L; ApplicationNotificationTemplateResource resource = new ApplicationNotificationTemplateResource(); when(applicationNotificationTemplateService.getUnsuccessfulNotificationTemplate(competitionId)).thenReturn(serviceSuccess(resource)); mockMvc.perform(get("/application-notification-template/unsuccessful/1") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(toJson(resource))); } |
ApplicationNotificationTemplateController { @GetMapping("/ineligible/{competitionId}") public RestResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(@PathVariable("competitionId") long competitionId) { return applicationNotificationTemplateService.getIneligibleNotificationTemplate(competitionId).toGetResponse(); } @GetMapping("/successful/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(@PathVariable("competitionId") long competitionId); @GetMapping("/unsuccessful/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(@PathVariable("competitionId") long competitionId); @GetMapping("/ineligible/{competitionId}") RestResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(@PathVariable("competitionId") long competitionId); } | @Test public void getIneligibleNotificationTemplate() throws Exception { long competitionId = 1L; long userId = 2L; ApplicationNotificationTemplateResource resource = new ApplicationNotificationTemplateResource(); when(applicationNotificationTemplateService.getIneligibleNotificationTemplate(competitionId)).thenReturn(serviceSuccess(resource)); mockMvc.perform(get("/application-notification-template/ineligible/1") .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(toJson(resource))); } |
FundingDecisionMapper { public FundingDecisionStatus mapToDomain(FundingDecision source){ return FundingDecisionStatus.valueOf(source.name()); } FundingDecision mapToResource(FundingDecisionStatus source); FundingDecisionStatus mapToDomain(FundingDecision source); } | @Test public void testConvertFromResourceToDomain() { for(FundingDecision decision: FundingDecision.values()){ FundingDecisionStatus status = mapper.mapToDomain(decision); assertEquals(decision.name(), status.name()); } } |
FundingDecisionMapper { public FundingDecision mapToResource(FundingDecisionStatus source){ return FundingDecision.valueOf(source.name()); } FundingDecision mapToResource(FundingDecisionStatus source); FundingDecisionStatus mapToDomain(FundingDecision source); } | @Test public void testConvertFromDomainToResource() { for(FundingDecisionStatus status: FundingDecisionStatus.values()){ FundingDecision decision = mapper.mapToResource(status); assertEquals(status.name(), decision.name()); } } |
UserController { @GetMapping("/" + URL_VERIFY_EMAIL + "/{hash}") public RestResult<Void> verifyEmail(@PathVariable String hash) { final ServiceResult<Token> result = tokenService.getEmailToken(hash); LOG.debug(String.format("UserController verifyHash: %s", hash)); return result.handleSuccessOrFailure( failure -> restFailure(failure.getErrors()), token -> { registrationService.activateApplicantAndSendDiversitySurvey(token.getClassPk()).andOnSuccessReturnVoid(v -> { tokenService.handleExtraAttributes(token); tokenService.removeToken(token); crmService.syncCrmContact(token.getClassPk()); }); return restSuccess(); }); } @GetMapping("/uid/{uid}") RestResult<UserResource> getUserByUid(@PathVariable String uid); @GetMapping("/id/{id}") RestResult<UserResource> getUserById(@PathVariable long id); @PostMapping RestResult<UserResource> createUser(@RequestBody UserCreationResource userCreationResource); @GetMapping("/find-by-role/{userRole}") RestResult<List<UserResource>> findByRole(@PathVariable Role userRole); @GetMapping("/find-by-role-and-status/{userRole}/status/{userStatus}") RestResult<List<UserResource>> findByRoleAndUserStatus(@PathVariable Role userRole, @PathVariable UserStatus userStatus); @GetMapping("/active") RestResult<ManageUserPageResource> findActiveUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @GetMapping("/inactive") RestResult<ManageUserPageResource> findInactiveUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @GetMapping("/external/active") RestResult<ManageUserPageResource> findActiveExternalUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @GetMapping("/external/inactive") RestResult<ManageUserPageResource> findInactiveExternalUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @PostMapping("/internal/create/{inviteHash}") RestResult<Void> createInternalUser(@PathVariable("inviteHash") String inviteHash, @Valid @RequestBody InternalUserRegistrationResource internalUserRegistrationResource); @PostMapping("/internal/edit") RestResult<Void> editInternalUser(@Valid @RequestBody EditUserResource editUserResource); @GetMapping("/find-all/") RestResult<List<UserResource>> findAll(); @GetMapping("/find-external-users") RestResult<List<UserOrganisationResource>> findExternalUsers(@RequestParam String searchString,
@RequestParam SearchCategory searchCategory); @GetMapping("/find-by-email/{email}/") RestResult<UserResource> findByEmail(@PathVariable String email); @GetMapping("/find-assignable-users/{applicationId}") RestResult<Set<UserResource>> findAssignableUsers(@PathVariable long applicationId); @GetMapping("/find-related-users/{applicationId}") RestResult<Set<UserResource>> findRelatedUsers(@PathVariable long applicationId); @GetMapping("/" + URL_SEND_PASSWORD_RESET_NOTIFICATION + "/{emailAddress}/") RestResult<Void> sendPasswordResetNotification(@PathVariable String emailAddress); @GetMapping("/" + URL_CHECK_PASSWORD_RESET_HASH + "/{hash}") RestResult<Void> checkPasswordReset(@PathVariable String hash); @PostMapping("/" + URL_PASSWORD_RESET + "/{hash}") RestResult<Void> resetPassword(@PathVariable String hash, @RequestBody final String password); @GetMapping("/" + URL_VERIFY_EMAIL + "/{hash}") RestResult<Void> verifyEmail(@PathVariable String hash); @PutMapping("/" + URL_RESEND_EMAIL_VERIFICATION_NOTIFICATION + "/{emailAddress}/") RestResult<Void> resendEmailVerificationNotification(@PathVariable String emailAddress); @PostMapping("/id/{userId}/agree-new-site-terms-and-conditions") RestResult<Void> agreeNewSiteTermsAndConditions(@PathVariable long userId); @PostMapping("/update-details") RestResult<Void> updateDetails(@RequestBody UserResource userResource); @PutMapping("{id}/update-email/{email:.+}") RestResult<Void> updateEmail(@PathVariable long id, @PathVariable String email); @PostMapping("/id/{id}/deactivate") RestResult<Void> deactivateUser(@PathVariable long id); @PostMapping("/id/{id}/reactivate") RestResult<Void> reactivateUser(@PathVariable long id); @PostMapping("{id}/grant/{role}") RestResult<Void> grantRole(@PathVariable long id, @PathVariable Role role); static final Sort DEFAULT_USER_SORT; } | @Test public void verifyEmail() throws Exception { final String hash = "8eda60ad3441ee883cc95417e2abaa036c308dd9eb19468fcc8597fb4cb167c32a7e5daf5e237385"; final Long userId = 1L; final Token token = new Token(VERIFY_EMAIL_ADDRESS, User.class.getName(), userId, hash, now(), null); when(tokenServiceMock.getEmailToken(hash)).thenReturn(serviceSuccess((token))); when(registrationServiceMock.activateApplicantAndSendDiversitySurvey(1L)).thenReturn(serviceSuccess()); mockMvc.perform(get("/user/" + URL_VERIFY_EMAIL + "/{hash}", hash) .header("IFS_AUTH_TOKEN", "123abc")) .andExpect(status().isOk()) .andExpect(content().string("")) .andDo(document("user/verify-email", pathParameters( parameterWithName("hash").description("The hash to validate the legitimacy of the request") )) ); verify(crmService).syncCrmContact(userId); } |
ApplicationNotificationTemplateServiceImpl extends BaseTransactionalService implements ApplicationNotificationTemplateService { @Override public ServiceResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(long competitionId) { return getCompetition(competitionId).andOnSuccess(competition -> { String successfulTemplate = competition.isKtp() ? "successful_funding_decision_ktp.html" : "successful_funding_decision.html"; return renderTemplate(competitionId, successfulTemplate, (c) -> { Map<String, Object> arguments = new HashMap<>(); arguments.put("competitionName", c.getName()); arguments.put("dashboardUrl", webBaseUrl); arguments.put("feedbackDate", toUkTimeZone(c.getReleaseFeedbackDate()).format(formatter)); arguments.put("competitionId", c.getId()); return arguments; }); }); } @Override ServiceResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(long competitionId); @Override ServiceResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(long competitionId); @Override ServiceResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(long competitionId); } | @Test public void getSuccessfulNotificationTemplate() { ZonedDateTime feedbackDate = ZonedDateTime.now(); Competition competition = newCompetition() .withName("Competition") .withFundingType(GRANT) .withReleaseFeedbackDate(feedbackDate) .build(); Map<String, Object> arguments = new HashMap<>(); arguments.put("competitionName", competition.getName()); arguments.put("dashboardUrl", webBaseUrl); arguments.put("feedbackDate", toUkTimeZone(competition.getReleaseFeedbackDate()).format(formatter)); arguments.put("competitionId", competition.getId()); when(competitionRepository.findById(competitionId)).thenReturn(Optional.of(competition)); when(renderer.renderTemplate(eq(systemNotificationSource), any(), eq(DEFAULT_NOTIFICATION_TEMPLATES_PATH + "successful_funding_decision.html"), eq(arguments))) .thenReturn(serviceSuccess("MessageBody")); ServiceResult<ApplicationNotificationTemplateResource> result = service.getSuccessfulNotificationTemplate(competitionId); assertTrue(result.isSuccess()); assertEquals("MessageBody", result.getSuccess().getMessageBody()); } |
ApplicationNotificationTemplateServiceImpl extends BaseTransactionalService implements ApplicationNotificationTemplateService { @Override public ServiceResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(long competitionId) { return getCompetition(competitionId).andOnSuccess(competition -> { String unsuccessfulTemplate = competition.isKtp() ? "unsuccessful_funding_decision_ktp.html" : "unsuccessful_funding_decision.html"; return renderTemplate(competitionId, unsuccessfulTemplate, (c) -> { Map<String, Object> arguments = new HashMap<>(); arguments.put("competitionName", c.getName()); arguments.put("dashboardUrl", webBaseUrl); arguments.put("feedbackDate", toUkTimeZone(c.getReleaseFeedbackDate()).format(formatter)); arguments.put("competitionId", c.getId()); return arguments; }); }); } @Override ServiceResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(long competitionId); @Override ServiceResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(long competitionId); @Override ServiceResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(long competitionId); } | @Test public void getUnsuccessfulNotificationTemplate() { ZonedDateTime feedbackDate = ZonedDateTime.now(); Competition competition = newCompetition() .withName("Competition") .withFundingType(GRANT) .withReleaseFeedbackDate(feedbackDate) .build(); Map<String, Object> arguments = new HashMap<>(); arguments.put("competitionName", competition.getName()); arguments.put("dashboardUrl", webBaseUrl); arguments.put("feedbackDate", toUkTimeZone(competition.getReleaseFeedbackDate()).format(formatter)); arguments.put("competitionId", competition.getId()); when(competitionRepository.findById(competitionId)).thenReturn(Optional.of(competition)); when(renderer.renderTemplate(eq(systemNotificationSource), any(), eq(DEFAULT_NOTIFICATION_TEMPLATES_PATH + "unsuccessful_funding_decision.html"), eq(arguments))) .thenReturn(serviceSuccess("MessageBody")); ServiceResult<ApplicationNotificationTemplateResource> result = service.getUnsuccessfulNotificationTemplate(competitionId); assertTrue(result.isSuccess()); assertEquals("MessageBody", result.getSuccess().getMessageBody()); } |
ApplicationNotificationTemplateServiceImpl extends BaseTransactionalService implements ApplicationNotificationTemplateService { @Override public ServiceResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(long competitionId) { return renderTemplate(competitionId, "ineligible_application.html", (competition) -> { Map<String, Object> arguments = new HashMap<>(); arguments.put("competitionName", competition.getName()); return arguments; }); } @Override ServiceResult<ApplicationNotificationTemplateResource> getSuccessfulNotificationTemplate(long competitionId); @Override ServiceResult<ApplicationNotificationTemplateResource> getUnsuccessfulNotificationTemplate(long competitionId); @Override ServiceResult<ApplicationNotificationTemplateResource> getIneligibleNotificationTemplate(long competitionId); } | @Test public void getIneligibleNotificationTemplate() { Competition competition = newCompetition().withName("Competition").build(); Map<String, Object> arguments = new HashMap<>(); arguments.put("competitionName", competition.getName()); when(competitionRepository.findById(competitionId)).thenReturn(Optional.of(competition)); when(renderer.renderTemplate(eq(systemNotificationSource), any(), eq(DEFAULT_NOTIFICATION_TEMPLATES_PATH + "ineligible_application.html"), eq(arguments))) .thenReturn(serviceSuccess("MessageBody")); ServiceResult<ApplicationNotificationTemplateResource> result = service.getIneligibleNotificationTemplate(competitionId); assertTrue(result.isSuccess()); assertEquals("MessageBody", result.getSuccess().getMessageBody()); } |
ApplicationFundingServiceImpl extends BaseTransactionalService implements ApplicationFundingService { @Override @Transactional public ServiceResult<Void> notifyApplicantsOfFundingDecisions(FundingNotificationResource fundingNotificationResource) { List<Application> applications = getFundingApplications(fundingNotificationResource.getFundingDecisions()); setApplicationState(fundingNotificationResource.getFundingDecisions(), applications); List<ServiceResult<Pair<Long, NotificationTarget>>> fundingNotificationTargets = getApplicantNotificationTargets(fundingNotificationResource.calculateApplicationIds()); ServiceResult<List<Pair<Long, NotificationTarget>>> aggregatedFundingTargets = aggregate(fundingNotificationTargets); return aggregatedFundingTargets.handleSuccessOrFailure( failure -> serviceFailure(NOTIFICATIONS_UNABLE_TO_DETERMINE_NOTIFICATION_TARGETS), success -> { Notification fundingNotification = createFundingDecisionNotification(applications, fundingNotificationResource, aggregatedFundingTargets.getSuccess()); ServiceResult<Void> fundedEmailSendResult = notificationService.sendNotificationWithFlush(fundingNotification, EMAIL); ServiceResult<Void> setEmailDateTimeResult = fundedEmailSendResult.andOnSuccess(() -> aggregate(simpleMap( applications, application -> applicationService.setApplicationFundingEmailDateTime(application.getId(), ZonedDateTime.now())))) .andOnSuccessReturnVoid(); return setEmailDateTimeResult.andOnSuccess(() -> { if (!applications.isEmpty()) { return competitionService.manageInformState( applications.get(0) .getCompetition() .getId()); } return serviceSuccess(); }); }); } @Override @Transactional ServiceResult<Void> saveFundingDecisionData(Long competitionId, Map<Long, FundingDecision> applicationFundingDecisions); @Override ServiceResult<List<FundingDecisionToSendApplicationResource>> getNotificationResourceForApplications(List<Long> applicationIds); @Override @Transactional ServiceResult<Void> notifyApplicantsOfFundingDecisions(FundingNotificationResource fundingNotificationResource); } | @Test public void testNotifyLeadApplicantsOfFundingDecisions() { CompetitionAssessmentConfig competitionAssessmentConfig = new CompetitionAssessmentConfig(); Competition competition = newCompetition() .withCompetitionAssessmentConfig(competitionAssessmentConfig) .build(); Application application1 = newApplication().withCompetition(competition).build(); Application application2 = newApplication().withCompetition(competition).build(); Application application3 = newApplication().withCompetition(competition).build(); User application1LeadApplicant = newUser().build(); User application2LeadApplicant = newUser().build(); User application3LeadApplicant = newUser().build(); User inactiveapplicant = newUser().withStatus(UserStatus.INACTIVE).build(); List<ProcessRole> leadApplicantProcessRoles = newProcessRole(). withUser(application1LeadApplicant, application2LeadApplicant, application3LeadApplicant, inactiveapplicant). withApplication(application1, application2, application3, application3). withRole(Role.LEADAPPLICANT, Role.LEADAPPLICANT, Role.LEADAPPLICANT, Role.COLLABORATOR). build(4); UserNotificationTarget application1LeadApplicantTarget = new UserNotificationTarget(application1LeadApplicant.getName(), application1LeadApplicant.getEmail()); UserNotificationTarget application2LeadApplicantTarget = new UserNotificationTarget(application2LeadApplicant.getName(), application2LeadApplicant.getEmail()); UserNotificationTarget application3LeadApplicantTarget = new UserNotificationTarget(application3LeadApplicant.getName(), application3LeadApplicant.getEmail()); List<NotificationTarget> expectedLeadApplicants = asList(application1LeadApplicantTarget, application2LeadApplicantTarget, application3LeadApplicantTarget); Map<Long, FundingDecision> decisions = MapFunctions.asMap( application1.getId(), FundingDecision.FUNDED, application2.getId(), FundingDecision.UNFUNDED, application3.getId(), FundingDecision.ON_HOLD); FundingNotificationResource fundingNotificationResource = new FundingNotificationResource("The message body.", decisions); Map<String, Object> expectedGlobalNotificationArguments = asMap("message", fundingNotificationResource.getMessageBody()); Map<NotificationTarget, Map<String, Object>> expectedTargetSpecificNotificationArguments = asMap( application1LeadApplicantTarget, asMap( "applicationName", application1.getName(), "competitionName", application1.getCompetition().getName(), "applicationId", application1.getId()), application2LeadApplicantTarget, asMap( "applicationName", application2.getName(), "competitionName", application2.getCompetition().getName(), "applicationId", application2.getId()), application3LeadApplicantTarget, asMap( "applicationName", application3.getName(), "competitionName", application3.getCompetition().getName(), "applicationId", application3.getId())); Notification expectedFundingNotification = new Notification(systemNotificationSource, expectedLeadApplicants, APPLICATION_FUNDING, expectedGlobalNotificationArguments, expectedTargetSpecificNotificationArguments); List<Long> applicationIds = asList(application1.getId(), application2.getId(), application3.getId()); List<Application> applications = asList(application1, application2, application3); when(applicationRepository.findAllById(applicationIds)).thenReturn(applications); leadApplicantProcessRoles.forEach(processRole -> when(processRoleRepository.findByApplicationIdAndRole(processRole.getApplicationId(), processRole.getRole())).thenReturn(singletonList(processRole)) ); when(notificationService.sendNotificationWithFlush(createNotificationExpectationsWithGlobalArgs(expectedFundingNotification), eq(EMAIL))).thenReturn(serviceSuccess()); when(applicationService.setApplicationFundingEmailDateTime(any(Long.class), any(ZonedDateTime.class))).thenReturn(serviceSuccess(new ApplicationResource())); when(competitionService.manageInformState(competition.getId())).thenReturn(serviceSuccess()); ServiceResult<Void> result = service.notifyApplicantsOfFundingDecisions(fundingNotificationResource); assertTrue(result.isSuccess()); verify(notificationService).sendNotificationWithFlush(createNotificationExpectationsWithGlobalArgs(expectedFundingNotification), eq(EMAIL)); verifyNoMoreInteractions(notificationService); verify(applicationService).setApplicationFundingEmailDateTime(eq(application1.getId()), any(ZonedDateTime.class)); verify(applicationService).setApplicationFundingEmailDateTime(eq(application2.getId()), any(ZonedDateTime.class)); verify(applicationService).setApplicationFundingEmailDateTime(eq(application3.getId()), any(ZonedDateTime.class)); verifyNoMoreInteractions(applicationService); }
@Test public void testNotifyLeadApplicantsOfFundingDecisionsWithAverageAssessorScore() { CompetitionAssessmentConfig competitionAssessmentConfig = new CompetitionAssessmentConfig(); competitionAssessmentConfig.setIncludeAverageAssessorScoreInNotifications(true); Competition competition = newCompetition().withCompetitionAssessmentConfig(competitionAssessmentConfig).build(); Application application1 = newApplication().withCompetition(competition).build(); Application application2 = newApplication().withCompetition(competition).build(); Application application3 = newApplication().withCompetition(competition).build(); User application1LeadApplicant = newUser().build(); User application2LeadApplicant = newUser().build(); User application3LeadApplicant = newUser().build(); List<ProcessRole> leadApplicantProcessRoles = newProcessRole(). withUser(application1LeadApplicant, application2LeadApplicant, application3LeadApplicant). withApplication(application1, application2, application3). withRole(Role.LEADAPPLICANT). build(3); UserNotificationTarget application1LeadApplicantTarget = new UserNotificationTarget(application1LeadApplicant.getName(), application1LeadApplicant.getEmail()); UserNotificationTarget application2LeadApplicantTarget = new UserNotificationTarget(application2LeadApplicant.getName(), application2LeadApplicant.getEmail()); UserNotificationTarget application3LeadApplicantTarget = new UserNotificationTarget(application3LeadApplicant.getName(), application3LeadApplicant.getEmail()); List<NotificationTarget> expectedLeadApplicants = asList(application1LeadApplicantTarget, application2LeadApplicantTarget, application3LeadApplicantTarget); AverageAssessorScore averageAssessorScore1 = new AverageAssessorScore(application1, BigDecimal.valueOf(90)); AverageAssessorScore averageAssessorScore2 = new AverageAssessorScore(application2, BigDecimal.valueOf(60)); AverageAssessorScore averageAssessorScore3 = new AverageAssessorScore(application3, BigDecimal.valueOf(70)); Map<Long, FundingDecision> decisions = MapFunctions.asMap( application1.getId(), FundingDecision.FUNDED, application2.getId(), FundingDecision.UNFUNDED, application3.getId(), FundingDecision.ON_HOLD); FundingNotificationResource fundingNotificationResource = new FundingNotificationResource("The message body.", decisions); Map<String, Object> expectedGlobalNotificationArguments = asMap("message", fundingNotificationResource.getMessageBody()); Map<NotificationTarget, Map<String, Object>> expectedTargetSpecificNotificationArguments = asMap( application1LeadApplicantTarget, asMap( "applicationName", application1.getName(), "competitionName", application1.getCompetition().getName(), "applicationId", application1.getId(), "averageAssessorScore", "Average assessor score: " + averageAssessorScore1.getScore() + "%"), application2LeadApplicantTarget, asMap( "applicationName", application2.getName(), "competitionName", application2.getCompetition().getName(), "applicationId", application2.getId(), "averageAssessorScore", "Average assessor score: " + averageAssessorScore2.getScore() + "%"), application3LeadApplicantTarget, asMap( "applicationName", application3.getName(), "competitionName", application3.getCompetition().getName(), "applicationId", application3.getId(), "averageAssessorScore", "Average assessor score: " + averageAssessorScore3.getScore() + "%")); Notification expectedFundingNotification = new Notification(systemNotificationSource, expectedLeadApplicants, APPLICATION_FUNDING, expectedGlobalNotificationArguments, expectedTargetSpecificNotificationArguments); List<Long> applicationIds = asList(application1.getId(), application2.getId(), application3.getId()); List<Application> applications = asList(application1, application2, application3); when(applicationRepository.findAllById(applicationIds)).thenReturn(applications); leadApplicantProcessRoles.forEach(processRole -> when(processRoleRepository.findByApplicationIdAndRole(processRole.getApplicationId(), processRole.getRole())).thenReturn(singletonList(processRole)) ); when(averageAssessorScoreRepository.findByApplicationId(application1.getId())).thenReturn(Optional.of(averageAssessorScore1)); when(averageAssessorScoreRepository.findByApplicationId(application2.getId())).thenReturn(Optional.of(averageAssessorScore2)); when(averageAssessorScoreRepository.findByApplicationId(application3.getId())).thenReturn(Optional.of(averageAssessorScore3)); when(notificationService.sendNotificationWithFlush(createNotificationExpectationsWithGlobalArgs(expectedFundingNotification), eq(EMAIL))).thenReturn(serviceSuccess()); when(applicationService.setApplicationFundingEmailDateTime(any(Long.class), any(ZonedDateTime.class))).thenReturn(serviceSuccess(new ApplicationResource())); when(competitionService.manageInformState(competition.getId())).thenReturn(serviceSuccess()); ServiceResult<Void> result = service.notifyApplicantsOfFundingDecisions(fundingNotificationResource); assertTrue(result.isSuccess()); verify(notificationService).sendNotificationWithFlush(createNotificationExpectationsWithGlobalArgs(expectedFundingNotification), eq(EMAIL)); verifyNoMoreInteractions(notificationService); verify(applicationService).setApplicationFundingEmailDateTime(eq(application1.getId()), any(ZonedDateTime.class)); verify(applicationService).setApplicationFundingEmailDateTime(eq(application2.getId()), any(ZonedDateTime.class)); verify(applicationService).setApplicationFundingEmailDateTime(eq(application3.getId()), any(ZonedDateTime.class)); verifyNoMoreInteractions(applicationService); }
@Test public void testNotifyAllApplicantsOfFundingDecisions() { CompetitionAssessmentConfig competitionAssessmentConfig = new CompetitionAssessmentConfig(); Competition competition = newCompetition().withCompetitionAssessmentConfig(competitionAssessmentConfig).build(); Application application1 = newApplication().withCompetition(competition).build(); Application application2 = newApplication().withCompetition(competition).build(); User application1LeadApplicant = newUser().build(); User application1Collaborator = newUser().build(); User application1Applicant = newUser().build(); User application2LeadApplicant = newUser().build(); User application2Collaborator = newUser().build(); User application2Applicant = newUser().build(); List<ProcessRole> allProcessRoles = newProcessRole(). withUser(application1LeadApplicant, application1Collaborator, application1Applicant, application2LeadApplicant, application2Collaborator, application2Applicant). withApplication(application1, application1, application1, application2, application2, application2). withRole(Role.LEADAPPLICANT, Role.COLLABORATOR, Role.APPLICANT, Role.LEADAPPLICANT, Role.COLLABORATOR, Role.APPLICANT). build(6); UserNotificationTarget application1LeadApplicantTarget = new UserNotificationTarget(application1LeadApplicant.getName(), application1LeadApplicant.getEmail()); UserNotificationTarget application2LeadApplicantTarget = new UserNotificationTarget(application2LeadApplicant.getName(), application2LeadApplicant.getEmail()); UserNotificationTarget application1CollaboratorTarget = new UserNotificationTarget(application1Collaborator.getName(), application1Collaborator.getEmail()); UserNotificationTarget application2CollaboratorTarget = new UserNotificationTarget(application2Collaborator.getName(), application2Collaborator.getEmail()); List<NotificationTarget> expectedApplicants = asList(application1LeadApplicantTarget, application2LeadApplicantTarget, application1CollaboratorTarget, application2CollaboratorTarget); Map<Long, FundingDecision> decisions = MapFunctions.asMap( application1.getId(), FundingDecision.FUNDED, application2.getId(), FundingDecision.UNFUNDED); FundingNotificationResource fundingNotificationResource = new FundingNotificationResource("The message body.", decisions); Notification expectedFundingNotification = new Notification(systemNotificationSource, expectedApplicants, APPLICATION_FUNDING, emptyMap()); List<Long> applicationIds = asList(application1.getId(), application2.getId()); List<Application> applications = asList(application1, application2); when(applicationRepository.findAllById(applicationIds)).thenReturn(applications); asList(application1, application2).forEach(application -> when(applicationRepository.findById(application.getId())).thenReturn(Optional.of(application)) ); allProcessRoles.forEach(processRole -> when(processRoleRepository.findByApplicationIdAndRole(processRole.getApplicationId(), processRole.getRole())).thenReturn(singletonList(processRole)) ); when(notificationService.sendNotificationWithFlush(createSimpleNotificationExpectations(expectedFundingNotification), eq(EMAIL))).thenReturn(serviceSuccess()); when(applicationService.setApplicationFundingEmailDateTime(any(Long.class), any(ZonedDateTime.class))).thenReturn(serviceSuccess(new ApplicationResource())); when(competitionService.manageInformState(competition.getId())).thenReturn(serviceSuccess()); ServiceResult<Void> result = service.notifyApplicantsOfFundingDecisions(fundingNotificationResource); assertTrue(result.isSuccess()); verify(notificationService).sendNotificationWithFlush(createSimpleNotificationExpectations(expectedFundingNotification), eq(EMAIL)); verifyNoMoreInteractions(notificationService); verify(applicationService).setApplicationFundingEmailDateTime(eq(application1.getId()), any(ZonedDateTime.class)); verify(applicationService).setApplicationFundingEmailDateTime(eq(application2.getId()), any(ZonedDateTime.class)); verifyNoMoreInteractions(applicationService); } |
ApplicationFundingServiceImpl extends BaseTransactionalService implements ApplicationFundingService { @Override @Transactional public ServiceResult<Void> saveFundingDecisionData(Long competitionId, Map<Long, FundingDecision> applicationFundingDecisions) { if (applicationFundingDecisions.isEmpty()) { return serviceFailure(FUNDING_PANEL_DECISION_NONE_PROVIDED); } return getCompetition(competitionId).andOnSuccess(competition -> { List<Application> applications = findValidApplications(applicationFundingDecisions, competitionId); return saveFundingDecisionData(applications, applicationFundingDecisions); }); } @Override @Transactional ServiceResult<Void> saveFundingDecisionData(Long competitionId, Map<Long, FundingDecision> applicationFundingDecisions); @Override ServiceResult<List<FundingDecisionToSendApplicationResource>> getNotificationResourceForApplications(List<Long> applicationIds); @Override @Transactional ServiceResult<Void> notifyApplicantsOfFundingDecisions(FundingNotificationResource fundingNotificationResource); } | @Test public void testSaveFundingDecisionData() { Application application1 = newApplication().withId(1L).withCompetition(competition).withFundingDecision(FundingDecisionStatus.FUNDED).withApplicationState(ApplicationState.OPENED).build(); Application application2 = newApplication().withId(2L).withCompetition(competition).withFundingDecision(FundingDecisionStatus.UNFUNDED).withApplicationState(ApplicationState.OPENED).build(); when(applicationRepository.findAllowedApplicationsForCompetition(new HashSet<>(singletonList(1L)), competition.getId())).thenReturn(asList(application1, application2)); Map<Long, FundingDecision> decision = asMap(1L, UNDECIDED); ServiceResult<Void> result = service.saveFundingDecisionData(competition.getId(), decision); assertTrue(result.isSuccess()); verify(applicationRepository).findAllowedApplicationsForCompetition(new HashSet<>(singletonList(1L)), competition.getId()); assertEquals(ApplicationState.OPENED, application1.getApplicationProcess().getProcessState()); assertEquals(ApplicationState.OPENED, application2.getApplicationProcess().getProcessState()); assertEquals(FundingDecisionStatus.UNDECIDED, application1.getFundingDecision()); assertEquals(FundingDecisionStatus.UNFUNDED, application2.getFundingDecision()); assertNull(competition.getFundersPanelEndDate()); }
@Test public void testSaveFundingDecisionDataWillResetEmailDate() { Long applicationId = 1L; Long competitionId = competition.getId(); Application application1 = newApplication().withId(applicationId).withCompetition(competition).withFundingDecision(FundingDecisionStatus.FUNDED).withApplicationState(ApplicationState.OPENED).build(); when(applicationRepository.findAllowedApplicationsForCompetition(new HashSet<>(singletonList(applicationId)), competitionId)).thenReturn(singletonList(application1)); Map<Long, FundingDecision> applicationDecisions = asMap(applicationId, UNDECIDED); ServiceResult<Void> result = service.saveFundingDecisionData(competitionId, applicationDecisions); assertTrue(result.isSuccess()); verify(applicationRepository).findAllowedApplicationsForCompetition(new HashSet<>(singletonList(applicationId)), competitionId); verify(applicationService).setApplicationFundingEmailDateTime(applicationId, null); }
@Test public void testSaveFundingDecisionDataWhenDecisionIsChanged() { Long applicationId = 1L; Long competitionId = competition.getId(); Application application1 = newApplication() .withId(applicationId) .withCompetition(competition) .withFundingDecision(FundingDecisionStatus.UNDECIDED) .withApplicationState(ApplicationState.OPENED) .build(); when(applicationRepository.findAllowedApplicationsForCompetition(new HashSet<>(singletonList(applicationId)), competitionId)) .thenReturn(singletonList(application1)); Map<Long, FundingDecision> applicationDecisions = asMap(applicationId, FUNDED); ServiceResult<Void> result = service.saveFundingDecisionData(competitionId, applicationDecisions); Map<Long, FundingDecision> changedApplicationDecisions = asMap(applicationId, UNFUNDED); ServiceResult<Void> changedResult = service.saveFundingDecisionData(competitionId, changedApplicationDecisions); assertTrue(result.isSuccess()); assertTrue(changedResult.isSuccess()); verify(applicationRepository, times(2)).findAllowedApplicationsForCompetition(new HashSet<>(singletonList(applicationId)), competitionId); verify(applicationService, times(2)).setApplicationFundingEmailDateTime(applicationId, null); verifyZeroInteractions(applicationWorkflowHandler); assertTrue(FundingDecisionStatus.UNFUNDED.equals(application1.getFundingDecision())); }
@Test public void testSaveFundingDecisionDataWontResetEmailDateForSameDecision() { Long applicationId = 1L; Long competitionId = competition.getId(); Application application1 = newApplication().withId(applicationId).withCompetition(competition).withFundingDecision(FundingDecisionStatus.FUNDED).withApplicationState(ApplicationState.OPENED).build(); when(applicationRepository.findAllowedApplicationsForCompetition(new HashSet<>(singletonList(applicationId)), competitionId)).thenReturn(singletonList(application1)); Map<Long, FundingDecision> applicationDecisions = asMap(applicationId, FUNDED); ServiceResult<Void> result = service.saveFundingDecisionData(competitionId, applicationDecisions); assertTrue(result.isSuccess()); verify(applicationRepository).findAllowedApplicationsForCompetition(new HashSet<>(singletonList(applicationId)), competitionId); verify(applicationService, never()).setApplicationFundingEmailDateTime(any(Long.class), any(ZonedDateTime.class)); }
@Test public void testSaveFundingDecisionDataForCompetitionInProjectSetup() { Long unsuccessfulApplicationId = 246L; Long projectSetupCompetitionId = 456L; CompetitionType competitionType = newCompetitionType() .withName("Sector") .build(); Competition projectSetupCompetition = newCompetition() .withCompetitionStatus(CompetitionStatus.PROJECT_SETUP) .withCompetitionType(competitionType) .withId(projectSetupCompetitionId) .build(); projectSetupCompetition.setReleaseFeedbackDate(ZonedDateTime.now().minusDays(2L)); when(competitionRepository.findById(projectSetupCompetitionId)).thenReturn(Optional.of(projectSetupCompetition)); Application unsuccessfulApplication = newApplication() .withId(unsuccessfulApplicationId) .withCompetition(projectSetupCompetition) .withFundingDecision(FundingDecisionStatus.UNFUNDED) .withApplicationState(ApplicationState.SUBMITTED) .build(); assertTrue(projectSetupCompetition.getCompetitionStatus().equals(CompetitionStatus.PROJECT_SETUP)); when(applicationRepository.findAllowedApplicationsForCompetition(new HashSet<>(singletonList(unsuccessfulApplicationId)), projectSetupCompetitionId)).thenReturn(singletonList(unsuccessfulApplication)); when(applicationWorkflowHandler.approve(unsuccessfulApplication)).thenReturn(true); Map<Long, FundingDecision> applicationDecision = asMap(unsuccessfulApplicationId, FUNDED); ServiceResult<Void> result = service.saveFundingDecisionData(projectSetupCompetitionId, applicationDecision); assertTrue(result.isSuccess()); verify(applicationRepository).findAllowedApplicationsForCompetition(new HashSet<>(singletonList(unsuccessfulApplicationId)), projectSetupCompetitionId); verify(applicationService).setApplicationFundingEmailDateTime(unsuccessfulApplicationId, null); verify(applicationWorkflowHandler).approve(any(Application.class)); assertTrue(FundingDecisionStatus.FUNDED.equals(unsuccessfulApplication.getFundingDecision())); }
@Test public void testSaveFundingDecisionDataWithNoDecisions() { Application application1 = newApplication().withId(1L).withCompetition(competition).withFundingDecision(FundingDecisionStatus.FUNDED).withApplicationState(ApplicationState.OPENED).build(); Application application2 = newApplication().withId(2L).withCompetition(competition).withFundingDecision(FundingDecisionStatus.UNFUNDED).withApplicationState(ApplicationState.OPENED).build(); when(applicationRepository.findAllowedApplicationsForCompetition(new HashSet<>(singletonList(1L)), competition.getId())).thenReturn(asList(application1, application2)); Map<Long, FundingDecision> decision = new HashMap<>(); ServiceResult<Void> result = service.saveFundingDecisionData(competition.getId(), decision); assertTrue(result.isFailure()); assertEquals(1, result.getFailure().getErrors().size()); assertEquals("FUNDING_PANEL_DECISION_NONE_PROVIDED", result.getFailure().getErrors().get(0).getErrorKey()); assertEquals(HttpStatus.BAD_REQUEST, result.getFailure().getErrors().get(0).getStatusCode()); verify(applicationRepository, never()).findAllowedApplicationsForCompetition(anySet(), anyLong()); } |
UserController { @GetMapping("/find-by-email/{email}/") public RestResult<UserResource> findByEmail(@PathVariable String email) { return userService.findByEmail(email).toGetResponse(); } @GetMapping("/uid/{uid}") RestResult<UserResource> getUserByUid(@PathVariable String uid); @GetMapping("/id/{id}") RestResult<UserResource> getUserById(@PathVariable long id); @PostMapping RestResult<UserResource> createUser(@RequestBody UserCreationResource userCreationResource); @GetMapping("/find-by-role/{userRole}") RestResult<List<UserResource>> findByRole(@PathVariable Role userRole); @GetMapping("/find-by-role-and-status/{userRole}/status/{userStatus}") RestResult<List<UserResource>> findByRoleAndUserStatus(@PathVariable Role userRole, @PathVariable UserStatus userStatus); @GetMapping("/active") RestResult<ManageUserPageResource> findActiveUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @GetMapping("/inactive") RestResult<ManageUserPageResource> findInactiveUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @GetMapping("/external/active") RestResult<ManageUserPageResource> findActiveExternalUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @GetMapping("/external/inactive") RestResult<ManageUserPageResource> findInactiveExternalUsers(@RequestParam(required = false) String filter,
@RequestParam(value = "page", defaultValue = DEFAULT_PAGE_NUMBER) int pageIndex,
@RequestParam(value = "size", defaultValue = DEFAULT_PAGE_SIZE) int pageSize); @PostMapping("/internal/create/{inviteHash}") RestResult<Void> createInternalUser(@PathVariable("inviteHash") String inviteHash, @Valid @RequestBody InternalUserRegistrationResource internalUserRegistrationResource); @PostMapping("/internal/edit") RestResult<Void> editInternalUser(@Valid @RequestBody EditUserResource editUserResource); @GetMapping("/find-all/") RestResult<List<UserResource>> findAll(); @GetMapping("/find-external-users") RestResult<List<UserOrganisationResource>> findExternalUsers(@RequestParam String searchString,
@RequestParam SearchCategory searchCategory); @GetMapping("/find-by-email/{email}/") RestResult<UserResource> findByEmail(@PathVariable String email); @GetMapping("/find-assignable-users/{applicationId}") RestResult<Set<UserResource>> findAssignableUsers(@PathVariable long applicationId); @GetMapping("/find-related-users/{applicationId}") RestResult<Set<UserResource>> findRelatedUsers(@PathVariable long applicationId); @GetMapping("/" + URL_SEND_PASSWORD_RESET_NOTIFICATION + "/{emailAddress}/") RestResult<Void> sendPasswordResetNotification(@PathVariable String emailAddress); @GetMapping("/" + URL_CHECK_PASSWORD_RESET_HASH + "/{hash}") RestResult<Void> checkPasswordReset(@PathVariable String hash); @PostMapping("/" + URL_PASSWORD_RESET + "/{hash}") RestResult<Void> resetPassword(@PathVariable String hash, @RequestBody final String password); @GetMapping("/" + URL_VERIFY_EMAIL + "/{hash}") RestResult<Void> verifyEmail(@PathVariable String hash); @PutMapping("/" + URL_RESEND_EMAIL_VERIFICATION_NOTIFICATION + "/{emailAddress}/") RestResult<Void> resendEmailVerificationNotification(@PathVariable String emailAddress); @PostMapping("/id/{userId}/agree-new-site-terms-and-conditions") RestResult<Void> agreeNewSiteTermsAndConditions(@PathVariable long userId); @PostMapping("/update-details") RestResult<Void> updateDetails(@RequestBody UserResource userResource); @PutMapping("{id}/update-email/{email:.+}") RestResult<Void> updateEmail(@PathVariable long id, @PathVariable String email); @PostMapping("/id/{id}/deactivate") RestResult<Void> deactivateUser(@PathVariable long id); @PostMapping("/id/{id}/reactivate") RestResult<Void> reactivateUser(@PathVariable long id); @PostMapping("{id}/grant/{role}") RestResult<Void> grantRole(@PathVariable long id, @PathVariable Role role); static final Sort DEFAULT_USER_SORT; } | @Test public void userControllerShouldReturnListOfSingleUserWhenFoundByEmail() throws Exception { User user = new User(); user.setEmail("[email protected]"); user.setFirstName("testFirstName"); user.setLastName("testLastName"); user.setPhoneNumber("testPhoneNumber"); user.setFirstName("testFirstName"); user.setLastName("testLastName"); user.setTitle(Mr); when(userServiceMock.findByEmail(user.getEmail())).thenReturn(serviceFailure(notFoundError(User.class, user.getEmail()))); mockMvc.perform(get("/user/find-by-email/" + user.getEmail() + "/", "json") .contentType(APPLICATION_JSON)) .andExpect(status().isNotFound()); }
@Test public void userControllerShouldReturnEmptyListWhenNoUserIsFoundByEmail() throws Exception { String email = "[email protected]"; when(userServiceMock.findByEmail(email)).thenReturn(serviceFailure(notFoundError(User.class, email))); mockMvc.perform(get("/user/find-by-email/" + email + "/", "json") .contentType(APPLICATION_JSON)) .andExpect(status().isNotFound()); } |
RestSilEmailEndpoint implements SilEmailEndpoint { @Override public ServiceResult<SilEmailMessage> sendEmail(SilEmailMessage message) { return handlingErrors(() -> { final Either<ResponseEntity<Void>, ResponseEntity<Void>> response = adaptor.restPostWithEntity(silRestServiceUrl + silSendmailPath, message, Void.class, Void.class, HttpStatus.ACCEPTED); return response.mapLeftOrRight( failure -> serviceFailure(new Error(EMAILS_NOT_SENT_MULTIPLE, failure.getStatusCode())), success -> serviceSuccess(message)); }); } @Override ServiceResult<SilEmailMessage> sendEmail(SilEmailMessage message); } | @Test public void testSendEmail() { SilEmailAddress from = new SilEmailAddress("Sender", "[email protected]"); List<SilEmailAddress> to = singletonList(new SilEmailAddress("Recipient", "[email protected]")); SilEmailBody plainTextBody = new SilEmailBody("text/plain", "Some plain text"); SilEmailBody htmlBody = new SilEmailBody("text/html", "Some HTML"); SilEmailMessage silEmail = new SilEmailMessage(from, to, "A subject", plainTextBody, htmlBody); String expectedUrl = "http: ResponseEntity<String> returnedEntity = new ResponseEntity<>(ACCEPTED); when(mockRestTemplate.postForEntity(expectedUrl, adaptor.jsonEntity(silEmail), String.class)).thenReturn(returnedEntity); ServiceResult<SilEmailMessage> sendMailResult = service.sendEmail(silEmail); assertTrue(sendMailResult.isSuccess()); assertEquals(silEmail, sendMailResult.getSuccess()); }
@Test public void testSendEmailNotAccepted() { SilEmailAddress from = new SilEmailAddress("Sender", "[email protected]"); List<SilEmailAddress> to = singletonList(new SilEmailAddress("Recipient", "[email protected]")); SilEmailBody plainTextBody = new SilEmailBody("text/plain", "Some plain text"); SilEmailBody htmlBody = new SilEmailBody("text/html", "Some HTML"); SilEmailMessage silEmail = new SilEmailMessage(from, to, "A subject", plainTextBody, htmlBody); String expectedUrl = "http: ResponseEntity<String> returnedEntity = new ResponseEntity<>("Failure!", BAD_REQUEST); when(mockRestTemplate.postForEntity(expectedUrl, adaptor.jsonEntity(silEmail), String.class)).thenReturn(returnedEntity); ServiceResult<SilEmailMessage> sendMailResult = service.sendEmail(silEmail); assertTrue(sendMailResult.isFailure()); assertTrue(sendMailResult.getFailure().is(EMAILS_NOT_SENT_MULTIPLE)); }
@Test public void testSendEmailButRestTemplateThrowsException() { SilEmailMessage silEmail = new SilEmailMessage(null, null, "A subject"); when(mockRestTemplate.postForEntity("http: ServiceResult<SilEmailMessage> sendMailResult = service.sendEmail(silEmail); assertTrue(sendMailResult.isFailure()); assertTrue(sendMailResult.getFailure().is(internalServerErrorError())); } |
AffiliationController { @GetMapping("/id/{userId}/get-user-affiliations") public RestResult<AffiliationListResource> getUserAffiliations(@PathVariable("userId") long userId) { return affiliationService.getUserAffiliations(userId).toGetResponse(); } @GetMapping("/id/{userId}/get-user-affiliations") RestResult<AffiliationListResource> getUserAffiliations(@PathVariable("userId") long userId); @PutMapping("/id/{userId}/update-user-affiliations") RestResult<Void> updateUserAffiliations(@PathVariable("userId") long userId,
@Valid @RequestBody AffiliationListResource affiliations); } | @Test public void getUserAffiliations() throws Exception { Long userId = 1L; List<AffiliationResource> affiliations = newAffiliationResource().build(2); AffiliationListResource affiliationListResource = newAffiliationListResource() .withAffiliationList(affiliations) .build(); when(affiliationServiceMock.getUserAffiliations(userId)).thenReturn(serviceSuccess(affiliationListResource)); mockMvc.perform(get("/affiliation/id/{id}/get-user-affiliations", userId) .contentType(APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().string(toJson(affiliationListResource))); verify(affiliationServiceMock, only()).getUserAffiliations(userId); } |
AffiliationController { @PutMapping("/id/{userId}/update-user-affiliations") public RestResult<Void> updateUserAffiliations(@PathVariable("userId") long userId, @Valid @RequestBody AffiliationListResource affiliations) { return affiliationService.updateUserAffiliations(userId, affiliations).toPutResponse(); } @GetMapping("/id/{userId}/get-user-affiliations") RestResult<AffiliationListResource> getUserAffiliations(@PathVariable("userId") long userId); @PutMapping("/id/{userId}/update-user-affiliations") RestResult<Void> updateUserAffiliations(@PathVariable("userId") long userId,
@Valid @RequestBody AffiliationListResource affiliations); } | @Test public void updateUserAffiliations() throws Exception { Long userId = 1L; List<AffiliationResource> affiliations = newAffiliationResource().build(2); AffiliationListResource affiliationListResource = newAffiliationListResource() .withAffiliationList(affiliations) .build(); when(affiliationServiceMock.updateUserAffiliations(userId, affiliationListResource)).thenReturn(serviceSuccess()); mockMvc.perform(put("/affiliation/id/{id}/update-user-affiliations", userId) .contentType(APPLICATION_JSON) .content(objectMapper.writeValueAsString(affiliationListResource))) .andExpect(status().isOk()); verify(affiliationServiceMock, only()).updateUserAffiliations(userId, affiliationListResource); } |
AffiliationServiceImpl extends BaseTransactionalService implements AffiliationService { @Override public ServiceResult<AffiliationListResource> getUserAffiliations(long userId) { return find(userRepository.findById(userId), notFoundError(User.class, userId)).andOnSuccess(user -> serviceSuccess(new AffiliationListResource( simpleMap(user.getAffiliations(), affiliationMapper::mapToResource) )) ); } @Override ServiceResult<AffiliationListResource> getUserAffiliations(long userId); @Override @Transactional ServiceResult<Void> updateUserAffiliations(long userId, AffiliationListResource affiliations); } | @Test public void getUserAffiliations() throws Exception { Long userId = 1L; List<Affiliation> affiliations = newAffiliation().build(2); List<AffiliationResource> affiliationResources = newAffiliationResource().build(2); when(affiliationMapperMock.mapToResource(affiliations.get(0))).thenReturn(affiliationResources.get(0)); when(affiliationMapperMock.mapToResource(affiliations.get(1))).thenReturn(affiliationResources.get(1)); User user = newUser() .withAffiliations(affiliations) .build(); when(userRepositoryMock.findById(userId)).thenReturn(Optional.of(user)); List<AffiliationResource> response = service.getUserAffiliations(userId).getSuccess().getAffiliationResourceList(); assertEquals(affiliationResources, response); InOrder inOrder = inOrder(userRepositoryMock, affiliationMapperMock); inOrder.verify(userRepositoryMock).findById(userId); inOrder.verify(affiliationMapperMock, times(2)).mapToResource(isA(Affiliation.class)); inOrder.verifyNoMoreInteractions(); }
@Test public void getUserAffiliations_userDoesNotExist() throws Exception { Long userIdNotExists = 1L; ServiceResult<AffiliationListResource> response = service.getUserAffiliations(userIdNotExists); assertTrue(response.getFailure().is(notFoundError(User.class, userIdNotExists))); verify(userRepositoryMock, only()).findById(userIdNotExists); verifyZeroInteractions(affiliationMapperMock); }
@Test public void getUserAffiliations_noAffiliations() throws Exception { Long userId = 1L; List<Affiliation> affiliations = emptyList(); User user = newUser() .withAffiliations(affiliations) .build(); when(userRepositoryMock.findById(userId)).thenReturn(Optional.of(user)); List<AffiliationResource> response = service.getUserAffiliations(userId).getSuccess().getAffiliationResourceList(); assertTrue(response.isEmpty()); verify(userRepositoryMock, only()).findById(userId); verifyZeroInteractions(affiliationMapperMock); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.