src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
AdditionalCompanyCostCategory implements FinanceRowCostCategory { @Override public void addCost(FinanceRowItem costItem) { AdditionalCompanyCost cost = (AdditionalCompanyCost) costItem; switch (cost.getType()) { case ASSOCIATE_SALARY: associateSalary = cost; break; case MANAGEMENT_SUPERVISION: managementSupervision = cost; break; case OTHER_STAFF: otherStaff = cost; break; case CAPITAL_EQUIPMENT: capitalEquipment = cost; break; case CONSUMABLES: consumables = cost; break; case OTHER_COSTS: otherCosts = cost; break; } } AdditionalCompanyCost getAssociateSalary(); void setAssociateSalary(AdditionalCompanyCost associateSalary); AdditionalCompanyCost getManagementSupervision(); void setManagementSupervision(AdditionalCompanyCost managementSupervision); AdditionalCompanyCost getOtherStaff(); void setOtherStaff(AdditionalCompanyCost otherStaff); AdditionalCompanyCost getCapitalEquipment(); void setCapitalEquipment(AdditionalCompanyCost capitalEquipment); AdditionalCompanyCost getConsumables(); void setConsumables(AdditionalCompanyCost consumables); AdditionalCompanyCost getOtherCosts(); void setOtherCosts(AdditionalCompanyCost otherCosts); void setTotal(BigDecimal total); @Override @JsonIgnore List<FinanceRowItem> getCosts(); @Override BigDecimal getTotal(); @Override void calculateTotal(); @Override void addCost(FinanceRowItem costItem); @Override boolean excludeFromTotalCost(); }
@Test public void addCost() { AdditionalCompanyCost newConsumables = newAdditionalCompanyCost() .withType(AdditionalCompanyCost.AdditionalCompanyCostType.CONSUMABLES) .withDescription("newAdditionalCompanyCost") .withCost(BigInteger.valueOf(700)) .build(); BigDecimal newResult = associateSalary.getTotal() .add(managementSupervision.getTotal()) .add(otherStaff.getTotal()) .add(capitalEquipment.getTotal()) .add(newConsumables.getTotal()) .add(otherCosts.getTotal()); additionalCompanyCostCategory.addCost(newConsumables); assertEquals(newConsumables, additionalCompanyCostCategory.getConsumables()); additionalCompanyCostCategory.calculateTotal(); assertEquals(newResult, additionalCompanyCostCategory.getTotal()); }
AdditionalCompanyCostCategory implements FinanceRowCostCategory { @Override public boolean excludeFromTotalCost() { return true; } AdditionalCompanyCost getAssociateSalary(); void setAssociateSalary(AdditionalCompanyCost associateSalary); AdditionalCompanyCost getManagementSupervision(); void setManagementSupervision(AdditionalCompanyCost managementSupervision); AdditionalCompanyCost getOtherStaff(); void setOtherStaff(AdditionalCompanyCost otherStaff); AdditionalCompanyCost getCapitalEquipment(); void setCapitalEquipment(AdditionalCompanyCost capitalEquipment); AdditionalCompanyCost getConsumables(); void setConsumables(AdditionalCompanyCost consumables); AdditionalCompanyCost getOtherCosts(); void setOtherCosts(AdditionalCompanyCost otherCosts); void setTotal(BigDecimal total); @Override @JsonIgnore List<FinanceRowItem> getCosts(); @Override BigDecimal getTotal(); @Override void calculateTotal(); @Override void addCost(FinanceRowItem costItem); @Override boolean excludeFromTotalCost(); }
@Test public void checkCostCategoryNotToSetToExcludeFromTotalCosts() { assertTrue(additionalCompanyCostCategory.excludeFromTotalCost()); }
LabourCostCategory implements FinanceRowCostCategory { @Override public List<FinanceRowItem> getCosts() { return costs; } @Override List<FinanceRowItem> getCosts(); void setCosts(List<FinanceRowItem> costItems); @Override BigDecimal getTotal(); @Override void calculateTotal(); Integer getWorkingDaysPerYear(); LabourCost getWorkingDaysPerYearCostItem(); @Override void addCost(FinanceRowItem costItem); @Override boolean excludeFromTotalCost(); static final String WORKING_DAYS_PER_YEAR; static final String WORKING_DAYS_KEY; }
@Test public void getCosts() { assertEquals(costs, labourCostCategory.getCosts()); }
LabourCostCategory implements FinanceRowCostCategory { public Integer getWorkingDaysPerYear() { if (workingDaysPerYearCostItem != null) { return workingDaysPerYearCostItem.getLabourDays(); } else { return 0; } } @Override List<FinanceRowItem> getCosts(); void setCosts(List<FinanceRowItem> costItems); @Override BigDecimal getTotal(); @Override void calculateTotal(); Integer getWorkingDaysPerYear(); LabourCost getWorkingDaysPerYearCostItem(); @Override void addCost(FinanceRowItem costItem); @Override boolean excludeFromTotalCost(); static final String WORKING_DAYS_PER_YEAR; static final String WORKING_DAYS_KEY; }
@Test public void getWorkingDaysPerYear() { Integer result = workingDays.getLabourDays(); assertEquals(result, labourCostCategory.getWorkingDaysPerYear()); } @Test public void getWorkingDaysPerYearWithNullWorkingDays() { Integer result = 0; workingDays.setLabourDays(0); assertEquals(result, labourCostCategory.getWorkingDaysPerYear()); }
LabourCostCategory implements FinanceRowCostCategory { public LabourCost getWorkingDaysPerYearCostItem() { return workingDaysPerYearCostItem; } @Override List<FinanceRowItem> getCosts(); void setCosts(List<FinanceRowItem> costItems); @Override BigDecimal getTotal(); @Override void calculateTotal(); Integer getWorkingDaysPerYear(); LabourCost getWorkingDaysPerYearCostItem(); @Override void addCost(FinanceRowItem costItem); @Override boolean excludeFromTotalCost(); static final String WORKING_DAYS_PER_YEAR; static final String WORKING_DAYS_KEY; }
@Test public void getWorkingDaysPerYearCostItem() { assertEquals(workingDays, labourCostCategory.getWorkingDaysPerYearCostItem()); }
LabourCostCategory implements FinanceRowCostCategory { @Override public void addCost(FinanceRowItem costItem) { if (costItem != null) { LabourCost labourCost = (LabourCost) costItem; if (WORKING_DAYS_PER_YEAR.equals(labourCost.getDescription())) { workingDaysPerYearCostItem = (LabourCost) costItem; } else { costs.add(costItem); } } } @Override List<FinanceRowItem> getCosts(); void setCosts(List<FinanceRowItem> costItems); @Override BigDecimal getTotal(); @Override void calculateTotal(); Integer getWorkingDaysPerYear(); LabourCost getWorkingDaysPerYearCostItem(); @Override void addCost(FinanceRowItem costItem); @Override boolean excludeFromTotalCost(); static final String WORKING_DAYS_PER_YEAR; static final String WORKING_DAYS_KEY; }
@Test public void addCost() { LabourCost testerCost = newLabourCost() .withLabourDays(100) .withGrossEmployeeCost(BigDecimal.valueOf(10000)) .withRole("Tester") .build(); costs.add(testerCost); labourCostCategory.addCost(testerCost); assertEquals(costs, labourCostCategory.getCosts()); }
LabourCostCategory implements FinanceRowCostCategory { @Override public boolean excludeFromTotalCost() { return false; } @Override List<FinanceRowItem> getCosts(); void setCosts(List<FinanceRowItem> costItems); @Override BigDecimal getTotal(); @Override void calculateTotal(); Integer getWorkingDaysPerYear(); LabourCost getWorkingDaysPerYearCostItem(); @Override void addCost(FinanceRowItem costItem); @Override boolean excludeFromTotalCost(); static final String WORKING_DAYS_PER_YEAR; static final String WORKING_DAYS_KEY; }
@Test public void checkCostCategorySetToExcludeFromTotalCosts() { assertFalse(labourCostCategory.excludeFromTotalCost()); }
ExcludedCostCategory extends DefaultCostCategory { @Override public BigDecimal getTotal() { return BigDecimal.ZERO; } @Override boolean excludeFromTotalCost(); @Override BigDecimal getTotal(); }
@Test public void getTotal() { grantClaimCategory.calculateTotal(); assertEquals(BigDecimal.ZERO, grantClaimCategory.getTotal()); }
ExcludedCostCategory extends DefaultCostCategory { @Override public boolean excludeFromTotalCost() { return true; } @Override boolean excludeFromTotalCost(); @Override BigDecimal getTotal(); }
@Test public void checkCostCategorySetToExcludeFromTotalCosts() { assertTrue(grantClaimCategory.excludeFromTotalCost()); }
DefaultCostCategory implements FinanceRowCostCategory { @Override public List<FinanceRowItem> getCosts() { return costs; } @Override List<FinanceRowItem> getCosts(); @Override BigDecimal getTotal(); @Override void calculateTotal(); @Override void addCost(FinanceRowItem costItem); @Override boolean excludeFromTotalCost(); void setCosts(List<FinanceRowItem> costItems); }
@Test public void getCosts() { assertEquals(costs, defaultCostCategory.getCosts()); }
DefaultCostCategory implements FinanceRowCostCategory { @Override public BigDecimal getTotal() { return total; } @Override List<FinanceRowItem> getCosts(); @Override BigDecimal getTotal(); @Override void calculateTotal(); @Override void addCost(FinanceRowItem costItem); @Override boolean excludeFromTotalCost(); void setCosts(List<FinanceRowItem> costItems); }
@Test public void getTotal() { defaultCostCategory.calculateTotal(); assertEquals(new BigDecimal(3000), defaultCostCategory.getTotal()); }
DefaultCostCategory implements FinanceRowCostCategory { @Override public void addCost(FinanceRowItem costItem) { if(costItem!=null) { costs.add(costItem); } } @Override List<FinanceRowItem> getCosts(); @Override BigDecimal getTotal(); @Override void calculateTotal(); @Override void addCost(FinanceRowItem costItem); @Override boolean excludeFromTotalCost(); void setCosts(List<FinanceRowItem> costItems); }
@Test public void addCost() { FinanceRowItem cost3 = newMaterials() .withCost(new BigDecimal(1000)) .withQuantity(1) .build(); costs.add(cost3); defaultCostCategory.addCost(cost3); assertEquals(costs, defaultCostCategory.getCosts()); }
DefaultCostCategory implements FinanceRowCostCategory { @Override public boolean excludeFromTotalCost() { return false; } @Override List<FinanceRowItem> getCosts(); @Override BigDecimal getTotal(); @Override void calculateTotal(); @Override void addCost(FinanceRowItem costItem); @Override boolean excludeFromTotalCost(); void setCosts(List<FinanceRowItem> costItems); }
@Test public void checkCostCategorySetToExcludeFromTotalCosts() { assertFalse(defaultCostCategory.excludeFromTotalCost()); }
OverheadCostCategory implements FinanceRowCostCategory { @Override public List<FinanceRowItem> getCosts() { return costs; } @Override List<FinanceRowItem> getCosts(); @Override BigDecimal getTotal(); @Override void calculateTotal(); @Override void addCost(FinanceRowItem costItem); @Override boolean excludeFromTotalCost(); void setCosts(List<FinanceRowItem> costItems); void setLabourCostTotal(BigDecimal labourCostTotal); static final String ACCEPT_RATE; }
@Test public void getCosts() { assertEquals(costs, overheadCostCategory.getCosts()); }
OverheadCostCategory implements FinanceRowCostCategory { @Override public BigDecimal getTotal() { return total; } @Override List<FinanceRowItem> getCosts(); @Override BigDecimal getTotal(); @Override void calculateTotal(); @Override void addCost(FinanceRowItem costItem); @Override boolean excludeFromTotalCost(); void setCosts(List<FinanceRowItem> costItems); void setLabourCostTotal(BigDecimal labourCostTotal); static final String ACCEPT_RATE; }
@Test public void getTotal() { BigDecimal labourCostTotal = new BigDecimal(1000); overheadCostCategory.setLabourCostTotal(labourCostTotal); overheadCostCategory.calculateTotal(); assertEquals(200, overheadCostCategory.getTotal().intValue()); }
OrganisationPermissionRules { @PermissionRule(value = "READ", description = "The System Registration User can search for Organisations on behalf of non-logged in " + "users during the registration process") public boolean systemRegistrationUserCanSeeOrganisationSearchResults(OrganisationSearchResult organisation, UserResource user) { return isSystemRegistrationUser(user); } @PermissionRule(value = "READ", description = "Internal Users can see all Organisations") boolean internalUsersCanSeeAllOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can see all Organisations") boolean stakeholdersCanSeeAllOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "Competition finance users can see all Organisations") boolean competitionFinanceUsersCanSeeAllOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can see Organisations on their projects") boolean monitoringOfficersCanSeeAllOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "System Registration User can see all Organisations, in order to view particular Organisations during registration and invite") boolean systemRegistrationUserCanSeeAllOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "The System Registration User can see Organisations on behalf of non-logged in users " + "whilst the Organisation is not yet linked to an Application") boolean systemRegistrationUserCanSeeOrganisationsNotYetConnectedToApplications(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "A member of an Organisation can view their own Organisation") boolean memberOfOrganisationCanViewOwnOrganisation(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "Users linked to Applications can view the basic details of the other Organisations on their own Applications") boolean usersCanViewOrganisationsOnTheirOwnApplications(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "User is invited to join the organisation") boolean usersCanViewOrganisationsTheyAreInvitedTo(OrganisationResource organisation, UserResource user); @PermissionRule(value = "CREATE", description = "The System Registration User can create Organisations on behalf of non-logged in Users " + "during the regsitration process") boolean systemRegistrationUserCanCreateOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "UPDATE", description = "The System Registration User can update Organisations that are not yet linked to Applications on behalf of non-logged in Users " + "during the regsitration process") boolean systemRegistrationUserCanUpdateOrganisationsNotYetConnectedToApplicationsOrUsers(OrganisationResource organisation, UserResource user); @PermissionRule(value = "UPDATE", description = "A member of an Organisation can update their own Organisation") boolean memberOfOrganisationCanUpdateOwnOrganisation(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "The System Registration User can search for Organisations on behalf of non-logged in " + "users during the registration process") boolean systemRegistrationUserCanSeeOrganisationSearchResults(OrganisationSearchResult organisation, UserResource user); @PermissionRule(value = "UPDATE", description = "A project finance user can update any Organisation") boolean projectFinanceUserCanUpdateAnyOrganisation(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "Project Partners can see the Partner Organisations within their Projects") boolean projectPartnerUserCanSeePartnerOrganisationsWithinTheirProjects(OrganisationResource organisation, UserResource user); }
@Test public void systemRegistrationUserCanSeeOrganisationSearchResults() { allGlobalRoleUsers.forEach(user -> { if (user.equals(systemRegistrationUser())) { assertTrue(rules.systemRegistrationUserCanSeeOrganisationSearchResults(new OrganisationSearchResult(), user)); } else { assertFalse(rules.systemRegistrationUserCanSeeOrganisationSearchResults(new OrganisationSearchResult(), user)); } }); }
OverheadCostCategory implements FinanceRowCostCategory { @Override public void addCost(FinanceRowItem costItem) { if(costItem!=null) { costs.add(costItem); } } @Override List<FinanceRowItem> getCosts(); @Override BigDecimal getTotal(); @Override void calculateTotal(); @Override void addCost(FinanceRowItem costItem); @Override boolean excludeFromTotalCost(); void setCosts(List<FinanceRowItem> costItems); void setLabourCostTotal(BigDecimal labourCostTotal); static final String ACCEPT_RATE; }
@Test public void addCost() { FinanceRowItem overHead2 = newOverhead().withRate(20).build(); costs.add(overHead2); overheadCostCategory.addCost(overHead2); assertEquals(costs, overheadCostCategory.getCosts()); }
OverheadCostCategory implements FinanceRowCostCategory { @Override public boolean excludeFromTotalCost() { return false; } @Override List<FinanceRowItem> getCosts(); @Override BigDecimal getTotal(); @Override void calculateTotal(); @Override void addCost(FinanceRowItem costItem); @Override boolean excludeFromTotalCost(); void setCosts(List<FinanceRowItem> costItems); void setLabourCostTotal(BigDecimal labourCostTotal); static final String ACCEPT_RATE; }
@Test public void checkCostCategorySetToExcludeFromTotalCosts() { assertFalse(overheadCostCategory.excludeFromTotalCost()); }
CapitalUsage extends AbstractFinanceRowItem { @Override public BigDecimal getTotal() { if (npv == null || residualValue == null || utilisation == null) { return BigDecimal.ZERO; } return npv.subtract(residualValue) .multiply(new BigDecimal(utilisation) .divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_EVEN)); } private CapitalUsage(); CapitalUsage(Long targetId); CapitalUsage(Long id, Integer deprecation, String description, String existing, BigDecimal npv, BigDecimal residualValue, Integer utilisation, Long targetId); @Override Long getId(); Integer getDeprecation(); void setDeprecation(Integer deprecation); String getDescription(); void setDescription(String description); String getExisting(); void setExisting(String existing); BigDecimal getNpv(); void setNpv(BigDecimal npv); BigDecimal getResidualValue(); void setResidualValue(BigDecimal residualValue); Integer getUtilisation(); void setUtilisation(Integer utilisation); @Override BigDecimal getTotal(); @Override String getName(); @Override boolean isEmpty(); @Override FinanceRowType getCostType(); }
@Test public void getTotal() { assertEquals(BigDecimal.valueOf(1250).setScale(2, BigDecimal.ROUND_HALF_EVEN), capitalUsage.getTotal()); } @Test public void totalMustBeZeroWhenDataIsNotAvailableTest() { CapitalUsage emptyCapitalUsage = new CapitalUsage(1L); assertEquals(BigDecimal.ZERO, emptyCapitalUsage.getTotal()); }
CapitalUsage extends AbstractFinanceRowItem { @Override public String getName() { return getCostType().getType(); } private CapitalUsage(); CapitalUsage(Long targetId); CapitalUsage(Long id, Integer deprecation, String description, String existing, BigDecimal npv, BigDecimal residualValue, Integer utilisation, Long targetId); @Override Long getId(); Integer getDeprecation(); void setDeprecation(Integer deprecation); String getDescription(); void setDescription(String description); String getExisting(); void setExisting(String existing); BigDecimal getNpv(); void setNpv(BigDecimal npv); BigDecimal getResidualValue(); void setResidualValue(BigDecimal residualValue); Integer getUtilisation(); void setUtilisation(Integer utilisation); @Override BigDecimal getTotal(); @Override String getName(); @Override boolean isEmpty(); @Override FinanceRowType getCostType(); }
@Test public void getName() { assertEquals("capital_usage", capitalUsage.getName()); }
CapitalUsage extends AbstractFinanceRowItem { @Override public boolean isEmpty() { return false; } private CapitalUsage(); CapitalUsage(Long targetId); CapitalUsage(Long id, Integer deprecation, String description, String existing, BigDecimal npv, BigDecimal residualValue, Integer utilisation, Long targetId); @Override Long getId(); Integer getDeprecation(); void setDeprecation(Integer deprecation); String getDescription(); void setDescription(String description); String getExisting(); void setExisting(String existing); BigDecimal getNpv(); void setNpv(BigDecimal npv); BigDecimal getResidualValue(); void setResidualValue(BigDecimal residualValue); Integer getUtilisation(); void setUtilisation(Integer utilisation); @Override BigDecimal getTotal(); @Override String getName(); @Override boolean isEmpty(); @Override FinanceRowType getCostType(); }
@Test public void isEmpty() { assertFalse(capitalUsage.isEmpty()); }
CapitalUsage extends AbstractFinanceRowItem { @Override public FinanceRowType getCostType() { return FinanceRowType.CAPITAL_USAGE; } private CapitalUsage(); CapitalUsage(Long targetId); CapitalUsage(Long id, Integer deprecation, String description, String existing, BigDecimal npv, BigDecimal residualValue, Integer utilisation, Long targetId); @Override Long getId(); Integer getDeprecation(); void setDeprecation(Integer deprecation); String getDescription(); void setDescription(String description); String getExisting(); void setExisting(String existing); BigDecimal getNpv(); void setNpv(BigDecimal npv); BigDecimal getResidualValue(); void setResidualValue(BigDecimal residualValue); Integer getUtilisation(); void setUtilisation(Integer utilisation); @Override BigDecimal getTotal(); @Override String getName(); @Override boolean isEmpty(); @Override FinanceRowType getCostType(); }
@Test public void getCostType() { assertEquals(CAPITAL_USAGE, capitalUsage.getCostType()); }
ProcurementOverhead extends AbstractFinanceRowItem { @Override public BigDecimal getTotal() { BigDecimal total = BigDecimal.ZERO; if (companyCost != null && projectCost != null) { total = projectCost.multiply(new BigDecimal(companyCost).divide(ONE_HUNDRED)); } return total; } ProcurementOverhead(); ProcurementOverhead(Long targetId); ProcurementOverhead(Long id, String item, BigDecimal projectCost, Integer companyCost, Long targetId); ProcurementOverhead(Long targetId, Long id, Integer companyCost, BigDecimal projectCost, String item, String name); @Override BigDecimal getTotal(); @Override FinanceRowType getCostType(); @Override String getName(); @Override boolean isEmpty(); @Override Long getId(); void setId(Long id); Integer getCompanyCost(); void setCompanyCost(Integer companyCost); BigDecimal getProjectCost(); void setProjectCost(BigDecimal projectCost); String getItem(); void setItem(String item); }
@Test public void totalForOverhead_NullProjectCost() { companyCost = 100; projectCost = null; overhead = new ProcurementOverhead(id, item, projectCost, companyCost, target_id); assertEquals(BigDecimal.ZERO, overhead.getTotal()); } @Test public void totalForOverhead_NullCompanyCost() { companyCost = null; projectCost = BigDecimal.TEN; overhead = new ProcurementOverhead(id, item, projectCost, companyCost, target_id); assertEquals(BigDecimal.ZERO, overhead.getTotal()); } @Test public void totalForOverhead() { companyCost = 500; projectCost = BigDecimal.TEN; overhead = new ProcurementOverhead(id, item, projectCost, companyCost, target_id); assertEquals(BigDecimal.valueOf(50), overhead.getTotal()); }
OrganisationPermissionRules { @PermissionRule(value = "READ", description = "Project Partners can see the Partner Organisations within their Projects") public boolean projectPartnerUserCanSeePartnerOrganisationsWithinTheirProjects(OrganisationResource organisation, UserResource user) { List<ProjectUser> projectRoles = projectUserRepository.findByUserId(user.getId()); return projectRoles.stream().anyMatch(projectUser -> { List<PartnerOrganisation> partnerOrganisations = projectUser.getProject().getPartnerOrganisations(); return partnerOrganisations.stream().anyMatch(org -> org.getOrganisation().getId().equals(organisation.getId())); }); } @PermissionRule(value = "READ", description = "Internal Users can see all Organisations") boolean internalUsersCanSeeAllOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can see all Organisations") boolean stakeholdersCanSeeAllOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "Competition finance users can see all Organisations") boolean competitionFinanceUsersCanSeeAllOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can see Organisations on their projects") boolean monitoringOfficersCanSeeAllOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "System Registration User can see all Organisations, in order to view particular Organisations during registration and invite") boolean systemRegistrationUserCanSeeAllOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "The System Registration User can see Organisations on behalf of non-logged in users " + "whilst the Organisation is not yet linked to an Application") boolean systemRegistrationUserCanSeeOrganisationsNotYetConnectedToApplications(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "A member of an Organisation can view their own Organisation") boolean memberOfOrganisationCanViewOwnOrganisation(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "Users linked to Applications can view the basic details of the other Organisations on their own Applications") boolean usersCanViewOrganisationsOnTheirOwnApplications(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "User is invited to join the organisation") boolean usersCanViewOrganisationsTheyAreInvitedTo(OrganisationResource organisation, UserResource user); @PermissionRule(value = "CREATE", description = "The System Registration User can create Organisations on behalf of non-logged in Users " + "during the regsitration process") boolean systemRegistrationUserCanCreateOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "UPDATE", description = "The System Registration User can update Organisations that are not yet linked to Applications on behalf of non-logged in Users " + "during the regsitration process") boolean systemRegistrationUserCanUpdateOrganisationsNotYetConnectedToApplicationsOrUsers(OrganisationResource organisation, UserResource user); @PermissionRule(value = "UPDATE", description = "A member of an Organisation can update their own Organisation") boolean memberOfOrganisationCanUpdateOwnOrganisation(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "The System Registration User can search for Organisations on behalf of non-logged in " + "users during the registration process") boolean systemRegistrationUserCanSeeOrganisationSearchResults(OrganisationSearchResult organisation, UserResource user); @PermissionRule(value = "UPDATE", description = "A project finance user can update any Organisation") boolean projectFinanceUserCanUpdateAnyOrganisation(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "Project Partners can see the Partner Organisations within their Projects") boolean projectPartnerUserCanSeePartnerOrganisationsWithinTheirProjects(OrganisationResource organisation, UserResource user); }
@Test public void projectPartnerUserCanSeePartnerOrganisationsWithinTheirProjects() { UserResource user = newUserResource().build(); Organisation differentOrganisation = newOrganisation().build(); Organisation organisationBeingChecked = newOrganisation().build(); Organisation anotherDifferentOrganisation = newOrganisation().build(); Project projectWithoutLinkedOrganisation = newProject(). withPartnerOrganisations(newPartnerOrganisation().withOrganisation(differentOrganisation).build(1)). build(); Project projectWithLinkedOrganisation = newProject(). withPartnerOrganisations(newPartnerOrganisation(). withOrganisation(organisationBeingChecked, anotherDifferentOrganisation). build(2)). build(); List<ProjectUser> thisUsersProjectUserEntriesWithoutLinkedOrganisation = newProjectUser(). withProject(projectWithoutLinkedOrganisation). withOrganisation(differentOrganisation). build(1); List<ProjectUser> thisUsersProjectUserEntriesIncludingLinkedOrganisation = newProjectUser(). withProject(projectWithLinkedOrganisation). withOrganisation(organisationBeingChecked, anotherDifferentOrganisation). build(2); List<ProjectUser> allProjectUserEntries = combineLists(thisUsersProjectUserEntriesWithoutLinkedOrganisation, thisUsersProjectUserEntriesIncludingLinkedOrganisation); when(projectUserRepository.findByUserId(user.getId())).thenReturn(allProjectUserEntries); OrganisationResource linkedOrganisationToCheck = newOrganisationResource(). withId(organisationBeingChecked.getId()). build(); assertTrue(rules.projectPartnerUserCanSeePartnerOrganisationsWithinTheirProjects(linkedOrganisationToCheck, user)); verify(projectUserRepository).findByUserId(user.getId()); } @Test public void projectPartnerUserCanSeePartnerOrganisationsWithinTheirProjectsButNoLinkWithOrganisationViaProjects() { UserResource user = newUserResource().build(); Organisation differentOrganisation = newOrganisation().build(); Organisation organisationBeingChecked = newOrganisation().build(); Organisation anotherDifferentOrganisation = newOrganisation().build(); Project projectWithoutLinkedOrganisation = newProject(). withPartnerOrganisations(newPartnerOrganisation().withOrganisation(differentOrganisation).build(1)). build(); Project anotherProjectWithoutLinkedOrganisation = newProject(). withPartnerOrganisations(newPartnerOrganisation(). withOrganisation(anotherDifferentOrganisation). build(2)). build(); List<ProjectUser> thisUsersProjectUserEntriesWithoutLinkedOrganisation = newProjectUser(). withProject(projectWithoutLinkedOrganisation). withOrganisation(differentOrganisation). build(1); List<ProjectUser> thisUsersProjectUserEntriesIncludingLinkedOrganisation = newProjectUser(). withProject(anotherProjectWithoutLinkedOrganisation). withOrganisation(anotherDifferentOrganisation). build(1); List<ProjectUser> allProjectUserEntries = combineLists(thisUsersProjectUserEntriesWithoutLinkedOrganisation, thisUsersProjectUserEntriesIncludingLinkedOrganisation); when(projectUserRepository.findByUserId(user.getId())).thenReturn(allProjectUserEntries); OrganisationResource linkedOrganisationToCheck = newOrganisationResource(). withId(organisationBeingChecked.getId()). build(); assertFalse(rules.projectPartnerUserCanSeePartnerOrganisationsWithinTheirProjects(linkedOrganisationToCheck, user)); verify(projectUserRepository).findByUserId(user.getId()); }
LabourCost extends AbstractFinanceRowItem { public BigDecimal getRate(Integer workingDaysPerYear) { rate = getRatePerDay(workingDaysPerYear); return rate; } private LabourCost(); LabourCost(Long targetId); LabourCost(Long id, String name, String role, BigDecimal grossEmployeeCost, Integer labourDays, String description, Long targetId); @Override Long getId(); @Override String getName(); @Override boolean isEmpty(); String getRole(); BigDecimal getGrossEmployeeCost(); BigDecimal getRate(Integer workingDaysPerYear); BigDecimal getRate(); Integer getLabourDays(); String getDescription(); @Override BigDecimal getTotal(); BigDecimal getTotal(Integer workingDaysPerYear); void setGrossEmployeeCost(BigDecimal grossEmployeeCost); void setName(String name); void setRole(String role); void setLabourDays(Integer labourDays); @Override FinanceRowType getCostType(); void setDescription(String description); BigDecimal totalDiff(Integer workingDaysPerYear, LabourCost otherOverhead); }
@Test public void getRate() { Integer workingDaysPerYear = 232; BigDecimal ratePerDay = labourCost.getRate(workingDaysPerYear); BigDecimal expected = new BigDecimal(215.51724).setScale(5, BigDecimal.ROUND_HALF_EVEN); assertEquals(expected, ratePerDay); } @Test public void rateNullLabourDays() { Integer workingDaysPerYear = null; BigDecimal ratePerDay = labourCost.getRate(workingDaysPerYear); assertNull(ratePerDay); } @Test public void rateWithDivisionByZeroLabourDays() { int workingDaysPerYear = 0; BigDecimal ratePerDay = labourCost.getRate(workingDaysPerYear); assertEquals(BigDecimal.ZERO, ratePerDay); }
LabourCost extends AbstractFinanceRowItem { @Override public BigDecimal getTotal() { return total; } private LabourCost(); LabourCost(Long targetId); LabourCost(Long id, String name, String role, BigDecimal grossEmployeeCost, Integer labourDays, String description, Long targetId); @Override Long getId(); @Override String getName(); @Override boolean isEmpty(); String getRole(); BigDecimal getGrossEmployeeCost(); BigDecimal getRate(Integer workingDaysPerYear); BigDecimal getRate(); Integer getLabourDays(); String getDescription(); @Override BigDecimal getTotal(); BigDecimal getTotal(Integer workingDaysPerYear); void setGrossEmployeeCost(BigDecimal grossEmployeeCost); void setName(String name); void setRole(String role); void setLabourDays(Integer labourDays); @Override FinanceRowType getCostType(); void setDescription(String description); BigDecimal totalDiff(Integer workingDaysPerYear, LabourCost otherOverhead); }
@Test public void getLabourCostTotal() { Integer workingDaysPerYear = 232; BigDecimal totalLabourCost = labourCost.getTotal(workingDaysPerYear); BigDecimal expected = new BigDecimal(36206.89632).setScale(5, BigDecimal.ROUND_HALF_EVEN); BigDecimal totalStoredLabourCost = labourCost.getTotal(); assertEquals(expected, totalLabourCost); assertEquals(expected, totalStoredLabourCost); }
Overhead extends AbstractFinanceRowItem { @Override public BigDecimal getTotal() { return BigDecimal.ZERO; } private Overhead(); Overhead(Long targetId); Overhead(Long id, OverheadRateType rateType, Integer rate, Long targetId); Integer getRate(); @Override BigDecimal getTotal(); @Override Long getId(); @Override FinanceRowType getCostType(); OverheadRateType getRateType(); void setRateType(OverheadRateType rateType); @Override String getName(); @Override boolean isEmpty(); void setRate(Integer rate); final static String FINANCE_OVERHEAD_FILE_REQUIRED; }
@Test public void totalForOverheadShouldAlwaysBeZeroTest() throws Exception { assertEquals(BigDecimal.ZERO, overhead.getTotal()); }
SubContractingCost extends AbstractFinanceRowItem { @Override public BigDecimal getTotal() { return cost; } private SubContractingCost(); SubContractingCost(Long targetId); SubContractingCost(Long id, BigDecimal cost, String country, String name, String role, Long targetId); @Override Long getId(); BigDecimal getCost(); String getCountry(); @Override String getName(); @Override boolean isEmpty(); String getRole(); @Override BigDecimal getTotal(); @Override FinanceRowType getCostType(); void setCost(BigDecimal cost); void setCountry(String country); void setName(String name); void setRole(String role); }
@Test public void calculateTotalsForSubContractingTest() throws Exception { BigDecimal expected = new BigDecimal(10023); assertEquals(expected, subContractingCost.getTotal()); }
TravelCost extends AbstractFinanceRowItem { @Override public BigDecimal getTotal() { if (cost == null || quantity == null) { return BigDecimal.ZERO; } return cost.multiply(new BigDecimal(quantity)); } private TravelCost(); TravelCost(Long targetId); TravelCost(Long id, String item, BigDecimal cost, Integer quantity, Long targetId); @Override Long getId(); BigDecimal getCost(); String getItem(); Integer getQuantity(); @Override BigDecimal getTotal(); @Override FinanceRowType getCostType(); @Override String getName(); @Override boolean isEmpty(); void setItem(String item); void setCost(BigDecimal cost); void setQuantity(Integer quantity); }
@Test public void calculateTotalsForTravelCostTest() throws Exception { BigDecimal expected = new BigDecimal(600).multiply(new BigDecimal(12)); assertEquals(expected, travelCost.getTotal()); } @Test public void calculatedTotalMustBeZeroWhenQuantityOrCostAreNotSetTest() throws Exception { TravelCost travelCostWithoutValues = new TravelCost(1L); assertEquals(BigDecimal.ZERO, travelCostWithoutValues.getTotal()); }
OtherCost extends AbstractFinanceRowItem { @Override public BigDecimal getTotal() { return cost; } private OtherCost(); OtherCost(Long targetId); OtherCost(Long id, String description, BigDecimal cost, Long targetId); @Override Long getId(); BigDecimal getCost(); String getDescription(); @Override BigDecimal getTotal(); @Override FinanceRowType getCostType(); @Override String getName(); @Override boolean isEmpty(); void setCost(BigDecimal cost); void setDescription(String description); }
@Test public void calculateTotalsForOtherCostTest() throws Exception { BigDecimal expected = new BigDecimal(1000); assertEquals(expected, otherCost.getTotal()); }
Materials extends AbstractFinanceRowItem { @Override public BigDecimal getTotal() { BigDecimal total = BigDecimal.ZERO; if (quantity != null && cost != null) { total = cost.multiply(new BigDecimal(quantity)); } return total; } private Materials(); Materials(Long targetId); Materials(Long id, String item, BigDecimal cost, Integer quantity, Long targetId); @Override Long getId(); String getItem(); BigDecimal getCost(); Integer getQuantity(); @Override BigDecimal getTotal(); @Override FinanceRowType getCostType(); void setItem(String item); void setCost(BigDecimal cost); void setQuantity(Integer quantity); @Override String getName(); @Override boolean isEmpty(); }
@Test public void calculateTotalsForMaterialsTest() throws Exception { BigDecimal expected = new BigDecimal(2000).multiply(new BigDecimal(12)); assertEquals(expected, materials.getTotal()); } @Test public void calculatedTotalMustBeZeroWhenQuantityOrCostAreNotSetTest() throws Exception { Materials materialWithoutValues = new Materials(1L); assertEquals(BigDecimal.ZERO, materialWithoutValues.getTotal()); }
ResearchCategoryResource extends CategoryResource { @Override public CategoryType getType() { return RESEARCH_CATEGORY; } @Override CategoryType getType(); }
@Test public void getType() throws Exception { assertEquals(newResearchCategoryResource().build().getType(), RESEARCH_CATEGORY); }
InnovationSectorResource extends CategoryResource { @Override public CategoryType getType() { return CategoryType.INNOVATION_SECTOR; } List<InnovationAreaResource> getChildren(); void setChildren(List<InnovationAreaResource> children); @Override CategoryType getType(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void getType() throws Exception { assertEquals(newInnovationSectorResource().build().getType(), INNOVATION_SECTOR); }
InnovationAreaResource extends CategoryResource { @Override public CategoryType getType() { return INNOVATION_AREA; } @Override CategoryType getType(); Long getSector(); void setSector(Long sector); String getSectorName(); void setSectorName(String sectorName); @JsonIgnore boolean isNone(); @JsonIgnore boolean isNotNone(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void getType() { assertEquals(newInnovationAreaResource().build().getType(), INNOVATION_AREA); }
InnovationAreaResource extends CategoryResource { @JsonIgnore public boolean isNotNone() { return !isNone(); } @Override CategoryType getType(); Long getSector(); void setSector(Long sector); String getSectorName(); void setSectorName(String sectorName); @JsonIgnore boolean isNone(); @JsonIgnore boolean isNotNone(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void isNotNone() { assertTrue(newInnovationAreaResource().withName("Foo").build().isNotNone()); assertFalse(newInnovationAreaResource().withName("None").build().isNotNone()); }
FinanceCheckSummaryResource { public boolean isAllEligibilityAndViabilityInReview() { return partnerStatusResources .stream() .allMatch(partner -> partner.getViability().isInReviewOrNotApplicable() && partner.getEligibility().isInReviewOrNotApplicable()); } FinanceCheckSummaryResource(); FinanceCheckSummaryResource(FinanceCheckOverviewResource overviewResource, Long competitionId, String competitionName, boolean spendProfilesGenerated, List<FinanceCheckPartnerStatusResource> partnerStatusResources, boolean bankDetailsApproved, String spendProfileGeneratedBy, LocalDate spendProfileGeneratedDate, Long applicationId, boolean h2020, FundingType fundingType, boolean hasGrantClaimPercentage); Long getProjectId(); void setProjectId(Long projectId); Long getCompetitionId(); void setCompetitionId(Long competitionId); String getCompetitionName(); void setCompetitionName(String competitionName); List<FinanceCheckPartnerStatusResource> getPartnerStatusResources(); void setPartnerStatusResources(List<FinanceCheckPartnerStatusResource> partnerStatusResources); LocalDate getProjectStartDate(); void setProjectStartDate(LocalDate projectStartDate); int getDurationInMonths(); void setDurationInMonths(int durationInMonths); BigDecimal getTotalProjectCost(); void setTotalProjectCost(BigDecimal totalProjectCost); BigDecimal getGrantAppliedFor(); void setGrantAppliedFor(BigDecimal grantAppliedFor); BigDecimal getOtherPublicSectorFunding(); void setOtherPublicSectorFunding(BigDecimal otherPublicSectorFunding); BigDecimal getTotalPercentageGrant(); void setTotalPercentageGrant(BigDecimal totalPercentageGrant); boolean isSpendProfilesGenerated(); void setSpendProfilesGenerated(boolean spendProfilesGenerated); String getSpendProfileGeneratedBy(); LocalDate getSpendProfileGeneratedDate(); boolean isH2020(); void setH2020(boolean h2020); FundingType getFundingType(); void setFundingType(FundingType fundingType); boolean isHasGrantClaimPercentage(); void setHasGrantClaimPercentage(boolean hasGrantClaimPercentage); @JsonIgnore boolean isFinanceChecksAllApproved(); boolean isAllEligibilityAndViabilityInReview(); void setSpendProfileGeneratedBy(String spendProfileGeneratedBy); void setSpendProfileGeneratedDate(LocalDate spendProfileGeneratedDate); String getProjectName(); void setProjectName(String projectName); BigDecimal getResearchParticipationPercentage(); void setResearchParticipationPercentage(BigDecimal researchParticipationPercentage); BigDecimal getCompetitionMaximumResearchPercentage(); void setCompetitionMaximumResearchPercentage(BigDecimal competitionMaximumResearchPercentage); boolean isBankDetailsApproved(); void setBankDetailsApproved(boolean bankDetailsApproved); Long getApplicationId(); void setApplicationId(Long applicationId); BigDecimal getFundingAppliedFor(); void setFundingAppliedFor(BigDecimal fundingAppliedFor); @JsonIgnore boolean isLoan(); @JsonIgnore boolean isProcurement(); }
@Test public void isAllEligibilityAndViabilityInReview() { FinanceCheckSummaryResource resource = newFinanceCheckSummaryResource() .withPartnerStatusResources(newFinanceCheckPartnerStatusResource() .withEligibility(parameter.eligibilityStates) .withViability(parameter.viabilityStates) .build(parameter.getNumberOfPartners()) ) .build(); assertEquals(parameter.expectedAllEligibilityAndViabilityInReview, resource.isAllEligibilityAndViabilityInReview()); }
CompetitionParticipantResource { @JsonIgnore public long getAssessmentDaysLeft() { return DAYS.between(ZonedDateTime.now(clock), assessorDeadlineDate); } String getCompetitionName(); void setCompetitionName(String competitionName); Long getId(); void setId(Long id); Long getCompetitionId(); void setCompetitionId(Long competitionId); Long getUserId(); void setUserId(Long userId); CompetitionInviteResource getInvite(); void setInvite(CompetitionInviteResource invite); RejectionReasonResource getRejectionReason(); void setRejectionReason(RejectionReasonResource rejectionReason); String getRejectionReasonComment(); void setRejectionReasonComment(String rejectionReasonComment); CompetitionParticipantRoleResource getRole(); void setRole(CompetitionParticipantRoleResource role); ParticipantStatusResource getStatus(); void setStatus(ParticipantStatusResource status); ZonedDateTime getAssessorAcceptsDate(); void setAssessorAcceptsDate(ZonedDateTime assessorAcceptsDate); ZonedDateTime getAssessorDeadlineDate(); void setAssessorDeadlineDate(ZonedDateTime assessorDeadlineDate); long getSubmittedAssessments(); void setSubmittedAssessments(long submittedAssessments); long getTotalAssessments(); void setTotalAssessments(long totalAssessments); long getPendingAssessments(); void setPendingAssessments(long pendingAssessments); CompetitionStatus getCompetitionStatus(); void setCompetitionStatus(CompetitionStatus competitionStatus); @JsonIgnore boolean isAccepted(); @JsonIgnore boolean isPending(); @JsonIgnore boolean isRejected(); @JsonIgnore long getAssessmentDaysLeft(); @JsonIgnore long getAssessmentDaysLeftPercentage(); @JsonIgnore boolean isInAssessment(); @JsonIgnore boolean isAnUpcomingAssessment(); @JsonIgnore boolean isUpcomingOrInAssessment(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void getAssessmentDaysLeft() throws Exception { assertEquals(3, competitionParticipant.getAssessmentDaysLeft()); assertEquals(0, competitionParticipantEndingToday.getAssessmentDaysLeft()); assertEquals(0, competitionParticipantEndingTommorrow.getAssessmentDaysLeft()); assertEquals(-1, competitionParticipantEndedYesterday.getAssessmentDaysLeft()); assertEquals(5, competitionParticipantStartedToday.getAssessmentDaysLeft()); assertEquals(6, competitionParticipantStartingTommorrow.getAssessmentDaysLeft()); }
CompetitionParticipantResource { @JsonIgnore public long getAssessmentDaysLeftPercentage() { return getDaysLeftPercentage(getAssessmentDaysLeft(), DAYS.between(assessorAcceptsDate, assessorDeadlineDate)); } String getCompetitionName(); void setCompetitionName(String competitionName); Long getId(); void setId(Long id); Long getCompetitionId(); void setCompetitionId(Long competitionId); Long getUserId(); void setUserId(Long userId); CompetitionInviteResource getInvite(); void setInvite(CompetitionInviteResource invite); RejectionReasonResource getRejectionReason(); void setRejectionReason(RejectionReasonResource rejectionReason); String getRejectionReasonComment(); void setRejectionReasonComment(String rejectionReasonComment); CompetitionParticipantRoleResource getRole(); void setRole(CompetitionParticipantRoleResource role); ParticipantStatusResource getStatus(); void setStatus(ParticipantStatusResource status); ZonedDateTime getAssessorAcceptsDate(); void setAssessorAcceptsDate(ZonedDateTime assessorAcceptsDate); ZonedDateTime getAssessorDeadlineDate(); void setAssessorDeadlineDate(ZonedDateTime assessorDeadlineDate); long getSubmittedAssessments(); void setSubmittedAssessments(long submittedAssessments); long getTotalAssessments(); void setTotalAssessments(long totalAssessments); long getPendingAssessments(); void setPendingAssessments(long pendingAssessments); CompetitionStatus getCompetitionStatus(); void setCompetitionStatus(CompetitionStatus competitionStatus); @JsonIgnore boolean isAccepted(); @JsonIgnore boolean isPending(); @JsonIgnore boolean isRejected(); @JsonIgnore long getAssessmentDaysLeft(); @JsonIgnore long getAssessmentDaysLeftPercentage(); @JsonIgnore boolean isInAssessment(); @JsonIgnore boolean isAnUpcomingAssessment(); @JsonIgnore boolean isUpcomingOrInAssessment(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void getAssessmentDaysLeftPercentage() throws Exception { assertEquals(50, competitionParticipant.getAssessmentDaysLeftPercentage()); assertEquals(100, competitionParticipantEndingToday.getAssessmentDaysLeftPercentage()); assertEquals(100, competitionParticipantEndingTommorrow.getAssessmentDaysLeftPercentage()); assertEquals(100, competitionParticipantEndedYesterday.getAssessmentDaysLeftPercentage()); assertEquals(16, competitionParticipantStartedToday.getAssessmentDaysLeftPercentage()); assertEquals(0, competitionParticipantStartingTommorrow.getAssessmentDaysLeftPercentage()); }
CompetitionParticipantResource { @JsonIgnore public boolean isInAssessment() { return competitionStatus == IN_ASSESSMENT; } String getCompetitionName(); void setCompetitionName(String competitionName); Long getId(); void setId(Long id); Long getCompetitionId(); void setCompetitionId(Long competitionId); Long getUserId(); void setUserId(Long userId); CompetitionInviteResource getInvite(); void setInvite(CompetitionInviteResource invite); RejectionReasonResource getRejectionReason(); void setRejectionReason(RejectionReasonResource rejectionReason); String getRejectionReasonComment(); void setRejectionReasonComment(String rejectionReasonComment); CompetitionParticipantRoleResource getRole(); void setRole(CompetitionParticipantRoleResource role); ParticipantStatusResource getStatus(); void setStatus(ParticipantStatusResource status); ZonedDateTime getAssessorAcceptsDate(); void setAssessorAcceptsDate(ZonedDateTime assessorAcceptsDate); ZonedDateTime getAssessorDeadlineDate(); void setAssessorDeadlineDate(ZonedDateTime assessorDeadlineDate); long getSubmittedAssessments(); void setSubmittedAssessments(long submittedAssessments); long getTotalAssessments(); void setTotalAssessments(long totalAssessments); long getPendingAssessments(); void setPendingAssessments(long pendingAssessments); CompetitionStatus getCompetitionStatus(); void setCompetitionStatus(CompetitionStatus competitionStatus); @JsonIgnore boolean isAccepted(); @JsonIgnore boolean isPending(); @JsonIgnore boolean isRejected(); @JsonIgnore long getAssessmentDaysLeft(); @JsonIgnore long getAssessmentDaysLeftPercentage(); @JsonIgnore boolean isInAssessment(); @JsonIgnore boolean isAnUpcomingAssessment(); @JsonIgnore boolean isUpcomingOrInAssessment(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void isInAssessment() throws Exception { assertFalse(competitionParticipantCompetitionSetup.isInAssessment()); assertFalse(competitionParticipantReadyToOpen.isInAssessment()); assertFalse(competitionParticipantOpen.isInAssessment()); assertFalse(competitionParticipantAssessmentClosed.isAnUpcomingAssessment()); assertTrue(competitionParticipantInAssessment.isInAssessment()); assertFalse(competitionParticipantAssessmentClosed.isInAssessment()); assertFalse(competitionParticipantAssessorFeedback.isInAssessment()); assertFalse(competitionParticipantProjectSetup.isInAssessment()); }
CompetitionParticipantResource { @JsonIgnore public boolean isAnUpcomingAssessment() { return competitionStatus == READY_TO_OPEN || competitionStatus == OPEN || competitionStatus == CLOSED; } String getCompetitionName(); void setCompetitionName(String competitionName); Long getId(); void setId(Long id); Long getCompetitionId(); void setCompetitionId(Long competitionId); Long getUserId(); void setUserId(Long userId); CompetitionInviteResource getInvite(); void setInvite(CompetitionInviteResource invite); RejectionReasonResource getRejectionReason(); void setRejectionReason(RejectionReasonResource rejectionReason); String getRejectionReasonComment(); void setRejectionReasonComment(String rejectionReasonComment); CompetitionParticipantRoleResource getRole(); void setRole(CompetitionParticipantRoleResource role); ParticipantStatusResource getStatus(); void setStatus(ParticipantStatusResource status); ZonedDateTime getAssessorAcceptsDate(); void setAssessorAcceptsDate(ZonedDateTime assessorAcceptsDate); ZonedDateTime getAssessorDeadlineDate(); void setAssessorDeadlineDate(ZonedDateTime assessorDeadlineDate); long getSubmittedAssessments(); void setSubmittedAssessments(long submittedAssessments); long getTotalAssessments(); void setTotalAssessments(long totalAssessments); long getPendingAssessments(); void setPendingAssessments(long pendingAssessments); CompetitionStatus getCompetitionStatus(); void setCompetitionStatus(CompetitionStatus competitionStatus); @JsonIgnore boolean isAccepted(); @JsonIgnore boolean isPending(); @JsonIgnore boolean isRejected(); @JsonIgnore long getAssessmentDaysLeft(); @JsonIgnore long getAssessmentDaysLeftPercentage(); @JsonIgnore boolean isInAssessment(); @JsonIgnore boolean isAnUpcomingAssessment(); @JsonIgnore boolean isUpcomingOrInAssessment(); @Override boolean equals(Object o); @Override int hashCode(); }
@Test public void isAnUpcomingAssessment() throws Exception { assertFalse(competitionParticipantCompetitionSetup.isAnUpcomingAssessment()); assertTrue(competitionParticipantReadyToOpen.isAnUpcomingAssessment()); assertTrue(competitionParticipantOpen.isAnUpcomingAssessment()); assertFalse(competitionParticipantClosed.isInAssessment()); assertFalse(competitionParticipantInAssessment.isAnUpcomingAssessment()); assertFalse(competitionParticipantAssessmentClosed.isAnUpcomingAssessment()); assertFalse(competitionParticipantAssessorFeedback.isAnUpcomingAssessment()); assertFalse(competitionParticipantProjectSetup.isAnUpcomingAssessment()); }
OrganisationPermissionRules { @PermissionRule(value = "READ", description = "User is invited to join the organisation") public boolean usersCanViewOrganisationsTheyAreInvitedTo(OrganisationResource organisation, UserResource user) { return inviteOrganisationRepository.findFirstByOrganisationIdAndInvitesUserId(organisation.getId(), user.getId()).isPresent(); } @PermissionRule(value = "READ", description = "Internal Users can see all Organisations") boolean internalUsersCanSeeAllOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can see all Organisations") boolean stakeholdersCanSeeAllOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "Competition finance users can see all Organisations") boolean competitionFinanceUsersCanSeeAllOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can see Organisations on their projects") boolean monitoringOfficersCanSeeAllOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "System Registration User can see all Organisations, in order to view particular Organisations during registration and invite") boolean systemRegistrationUserCanSeeAllOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "The System Registration User can see Organisations on behalf of non-logged in users " + "whilst the Organisation is not yet linked to an Application") boolean systemRegistrationUserCanSeeOrganisationsNotYetConnectedToApplications(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "A member of an Organisation can view their own Organisation") boolean memberOfOrganisationCanViewOwnOrganisation(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "Users linked to Applications can view the basic details of the other Organisations on their own Applications") boolean usersCanViewOrganisationsOnTheirOwnApplications(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "User is invited to join the organisation") boolean usersCanViewOrganisationsTheyAreInvitedTo(OrganisationResource organisation, UserResource user); @PermissionRule(value = "CREATE", description = "The System Registration User can create Organisations on behalf of non-logged in Users " + "during the regsitration process") boolean systemRegistrationUserCanCreateOrganisations(OrganisationResource organisation, UserResource user); @PermissionRule(value = "UPDATE", description = "The System Registration User can update Organisations that are not yet linked to Applications on behalf of non-logged in Users " + "during the regsitration process") boolean systemRegistrationUserCanUpdateOrganisationsNotYetConnectedToApplicationsOrUsers(OrganisationResource organisation, UserResource user); @PermissionRule(value = "UPDATE", description = "A member of an Organisation can update their own Organisation") boolean memberOfOrganisationCanUpdateOwnOrganisation(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "The System Registration User can search for Organisations on behalf of non-logged in " + "users during the registration process") boolean systemRegistrationUserCanSeeOrganisationSearchResults(OrganisationSearchResult organisation, UserResource user); @PermissionRule(value = "UPDATE", description = "A project finance user can update any Organisation") boolean projectFinanceUserCanUpdateAnyOrganisation(OrganisationResource organisation, UserResource user); @PermissionRule(value = "READ", description = "Project Partners can see the Partner Organisations within their Projects") boolean projectPartnerUserCanSeePartnerOrganisationsWithinTheirProjects(OrganisationResource organisation, UserResource user); }
@Test public void usersCanViewOrganisationsTheyAreInvitedTo() { UserResource invitedUser = newUserResource().build(); UserResource notInvitedUser = newUserResource().build(); OrganisationResource organisation = newOrganisationResource().build(); when(inviteOrganisationRepository.findFirstByOrganisationIdAndInvitesUserId(organisation.getId(), invitedUser.getId())) .thenReturn(Optional.of(newInviteOrganisation().build())); when(inviteOrganisationRepository.findFirstByOrganisationIdAndInvitesUserId(organisation.getId(), notInvitedUser.getId())) .thenReturn(Optional.empty()); assertTrue(rules.usersCanViewOrganisationsTheyAreInvitedTo(organisation, invitedUser)); assertFalse(rules.usersCanViewOrganisationsTheyAreInvitedTo(organisation, notInvitedUser)); }
AssessorProfileDeclarationModelPopulator extends AssessorProfileDeclarationBasePopulator { public AssessorProfileDeclarationViewModel populateModel(UserResource user, ProfileResource profile, Optional<Long> competitionId, boolean compAdminUser) { CompetitionResource competition = competitionId.map(id -> competitionRestService.getCompetitionById(id).getSuccess()) .orElse(null); AssessorProfileDetailsViewModel assessorProfileDetailsViewModel = assessorProfileDetailsModelPopulator.populateModel(user, profile); Map<AffiliationType, List<AffiliationResource>> affiliations = getAffiliationsMap(affiliationRestService.getUserAffiliations(user.getId()).getSuccess().getAffiliationResourceList()); Optional<AffiliationResource> principalEmployer = getPrincipalEmployer(affiliations); return new AssessorProfileDeclarationViewModel( competition, assessorProfileDetailsViewModel, affiliations.size() > 0, principalEmployer.map(AffiliationResource::getOrganisation).orElse(null), principalEmployer.map(AffiliationResource::getPosition).orElse(null), getProfessionalAffiliations(affiliations), getAppointments(affiliations), getFinancialInterests(affiliations), getFamilyAffiliations(affiliations), getFamilyFinancialInterests(affiliations), compAdminUser ); } AssessorProfileDeclarationModelPopulator(AssessorProfileDetailsModelPopulator assessorProfileDetailsModelPopulator, AffiliationRestService affiliationRestService, CompetitionRestService competitionRestService); AssessorProfileDeclarationViewModel populateModel(UserResource user, ProfileResource profile, Optional<Long> competitionId, boolean compAdminUser); }
@Test public void populateModel() throws Exception { CompetitionResource competition = newCompetitionResource() .withId(1L) .build(); UserResource user = newUserResource() .withId(2L) .withFirstName("Test") .withLastName("Tester") .withEmail("[email protected]") .withPhoneNumber("012345") .build(); AddressResource expectedAddress = newAddressResource() .withAddressLine1("1 Testing Lane") .withTown("Testville") .withCounty("South Testshire") .withPostcode("TES TEST") .build(); List<InnovationAreaResource> expectedInnovationAreas = newInnovationAreaResource() .withSector(1L, 2L, 1L) .withSectorName("sector 1", "sector 2", "sector 1") .withName("innovation area 1", "innovation area 2", "innovation area 3") .build(3); ProfileResource profile = newProfileResource() .withSkillsAreas("A Skill") .withBusinessType(ACADEMIC) .withInnovationAreas(expectedInnovationAreas) .withAddress(expectedAddress) .build(); AssessorProfileResource expectedProfile = newAssessorProfileResource() .withUser(user) .withProfile(profile) .build(); AssessorProfileDetailsViewModel expectedDetailsViewModel = new AssessorProfileDetailsViewModel(user, profile); setupAffiliations(); when(assessorRestService.getAssessorProfile(user.getId())).thenReturn(restSuccess(expectedProfile)); when(competitionRestService.getCompetitionById(competition.getId())).thenReturn(restSuccess(competition)); when(assessorProfileDetailsModelPopulator.populateModel(user, profile)).thenReturn(expectedDetailsViewModel); AssessorProfileDeclarationViewModel model = populator.populateModel(user, profile, Optional.of(competition.getId()), false); AssessorProfileDetailsViewModel assessorDetails = model.getAssessorProfileDetailsViewModel(); assertEquals("Test Tester", assessorDetails.getName()); assertEquals("012345", assessorDetails.getPhoneNumber()); assertEquals(ACADEMIC.getDisplayName(), assessorDetails.getBusinessType().getDisplayName()); assertEquals("[email protected]", assessorDetails.getEmail()); assertEquals(expectedAddress, assessorDetails.getAddress()); assertEquals(expectedAppointments, model.getAppointments()); assertEquals(expectedFamilyAffiliations, model.getFamilyAffiliations()); assertEquals(expectedFamilyFinancialInterests, model.getFamilyFinancialInterests()); assertEquals(expectedFinancialInterests, model.getFinancialInterests()); assertEquals(expectedPrincipalEmployer, model.getPrincipalEmployer()); assertEquals(expectedProfessionalAffiliations, model.getProfessionalAffiliations()); assertEquals(expectedRole, model.getRole()); }
AssessorProfileSkillsModelPopulator { public AssessorProfileSkillsViewModel populateModel(UserResource user, ProfileResource profile, Optional<Long> competitionId, boolean compAdminUser) { CompetitionResource competition = competitionId.map(id -> competitionRestService.getCompetitionById(id).getSuccess()) .orElse(null); AssessorProfileDetailsViewModel assessorProfileDetailsViewModel = getAssessorProfileDetails(user, profile); return new AssessorProfileSkillsViewModel( competition, assessorProfileDetailsViewModel, getInnovationAreasSectorMap(profile.getInnovationAreas()), profile.getSkillsAreas(), compAdminUser ); } AssessorProfileSkillsModelPopulator(AssessorProfileDetailsModelPopulator assessorProfileDetailsModelPopulator, CompetitionRestService competitionRestService); AssessorProfileSkillsViewModel populateModel(UserResource user, ProfileResource profile, Optional<Long> competitionId, boolean compAdminUser); }
@Test public void populateModel() { CompetitionResource competition = newCompetitionResource() .withId(1L) .build(); UserResource user = newUserResource() .withId(2L) .withFirstName("Test") .withLastName("Tester") .withEmail("[email protected]") .withPhoneNumber("012345") .build(); AddressResource expectedAddress = newAddressResource() .withAddressLine1("1 Testing Lane") .withTown("Testville") .withCounty("South Testshire") .withPostcode("TES TEST") .build(); List<InnovationAreaResource> expectedInnovationAreas = newInnovationAreaResource() .withSector(1L, 2L, 1L) .withSectorName("sector 1", "sector 2", "sector 1") .withName("innovation area 1", "innovation area 2", "innovation area 3") .build(3); ProfileResource profile = newProfileResource() .withSkillsAreas("A Skill") .withBusinessType(ACADEMIC) .withInnovationAreas(expectedInnovationAreas) .withAddress(expectedAddress) .build(); AssessorProfileResource expectedProfile = newAssessorProfileResource() .withUser(user) .withProfile(profile) .build(); AssessorProfileDetailsViewModel expectedDetailsViewModel = new AssessorProfileDetailsViewModel(user, profile); when(assessorRestService.getAssessorProfile(user.getId())).thenReturn(restSuccess(expectedProfile)); when(competitionRestService.getCompetitionById(competition.getId())).thenReturn(restSuccess(competition)); when(assessorProfileDetailsModelPopulator.populateModel(user, profile)).thenReturn(expectedDetailsViewModel); AssessorProfileSkillsViewModel model = populator.populateModel(user, profile, Optional.of(competition.getId()), false); AssessorProfileDetailsViewModel assessorDetails = model.getAssessorProfileDetailsViewModel(); assertEquals("Test Tester", assessorDetails.getName()); assertEquals("012345", assessorDetails.getPhoneNumber()); assertEquals("A Skill", model.getSkillAreas()); assertEquals(ACADEMIC.getDisplayName(), assessorDetails.getBusinessType().getDisplayName()); assertEquals("[email protected]", assessorDetails.getEmail()); assertEquals(2, model.getInnovationAreas().size()); assertEquals(expectedAddress, assessorDetails.getAddress()); }
CompetitionController { @GetMapping("overview") public String competitionOverview(final Model model, @PathVariable("competitionId") final long competitionId, UserResource loggedInUser) { final PublicContentItemResource publicContentItem = publicContentItemRestService.getItemByCompetitionId(competitionId).getSuccess(); model.addAttribute("model", overviewPopulator.populateViewModel(publicContentItem, loggedInUser != null)); return "competition/overview"; } @GetMapping("overview") String competitionOverview(final Model model, @PathVariable("competitionId") final long competitionId, UserResource loggedInUser); @GetMapping("download/{contentGroupId}") ResponseEntity<ByteArrayResource> getFileDetails(@PathVariable("competitionId") final long competitionId, @PathVariable("contentGroupId") final long contentGroupId); @GetMapping("info/terms-and-conditions") String termsAndConditions(@PathVariable("competitionId") final long competitionId, Model model); @GetMapping("info/terms-and-conditions/full") @ResponseBody ResponseEntity<ByteArrayResource> additionalTerms(@PathVariable("competitionId") final long competitionId); }
@Test public void competitionOverview() throws Exception { final long competitionId = 20L; final PublicContentItemResource publicContentItem = newPublicContentItemResource().build(); final CompetitionOverviewViewModel viewModel = new CompetitionOverviewViewModel(); when(publicContentItemRestService.getItemByCompetitionId(competitionId)).thenReturn(restSuccess(publicContentItem)); when(overviewPopulator.populateViewModel(publicContentItem, true)).thenReturn(viewModel); mockMvc.perform(get("/competition/{id}/overview", competitionId)) .andExpect(status().isOk()) .andExpect(model().attribute("model", viewModel)) .andExpect(view().name("competition/overview")); }
CompetitionController { @GetMapping("info/terms-and-conditions") public String termsAndConditions(@PathVariable("competitionId") final long competitionId, Model model) { CompetitionResource competition = competitionRestService.getCompetitionById(competitionId).getSuccess(); GrantTermsAndConditionsResource termsAndConditions = competition.getTermsAndConditions(); model.addAttribute("model", new CompetitionTermsViewModel(competitionId)); return "competition/info/" + termsAndConditions.getTemplate(); } @GetMapping("overview") String competitionOverview(final Model model, @PathVariable("competitionId") final long competitionId, UserResource loggedInUser); @GetMapping("download/{contentGroupId}") ResponseEntity<ByteArrayResource> getFileDetails(@PathVariable("competitionId") final long competitionId, @PathVariable("contentGroupId") final long contentGroupId); @GetMapping("info/terms-and-conditions") String termsAndConditions(@PathVariable("competitionId") final long competitionId, Model model); @GetMapping("info/terms-and-conditions/full") @ResponseBody ResponseEntity<ByteArrayResource> additionalTerms(@PathVariable("competitionId") final long competitionId); }
@Test public void termsAndConditions() throws Exception { GrantTermsAndConditionsResource termsAndConditions = new GrantTermsAndConditionsResource("T&C", "special-terms-and-conditions", 3); final CompetitionResource competitionResource = newCompetitionResource() .withCompetitionTypeName("Competition name") .withTermsAndConditions(termsAndConditions) .build(); when(competitionRestService.getCompetitionById(competitionResource.getId())).thenReturn(restSuccess(competitionResource)); mockMvc.perform(get("/competition/{id}/info/terms-and-conditions", competitionResource.getId())) .andExpect(status().isOk()) .andExpect(model().attribute("model", new CompetitionTermsViewModel(competitionResource.getId()))) .andExpect(view().name("competition/info/special-terms-and-conditions")); verify(competitionRestService, only()).getCompetitionById(competitionResource.getId()); }
CompetitionSearchController { @NotSecured("Not currently secured") @GetMapping public String publicContentSearch(Model model, @RequestParam(value = KEYWORDS_KEY, required = false) Optional<String> keywords, @RequestParam(value = INNOVATION_AREA_ID_KEY, required = false) Optional<Long> innovationAreaId, @RequestParam(value = PAGE_NUMBER_KEY, required = false) Optional<Integer> pageNumber) { model.addAttribute("model", itemSearchPopulator.createItemSearchViewModel(innovationAreaId, keywords, pageNumber)); return TEMPLATE_FOLDER + "search"; } @NotSecured("Not currently secured") @GetMapping String publicContentSearch(Model model, @RequestParam(value = KEYWORDS_KEY, required = false) Optional<String> keywords, @RequestParam(value = INNOVATION_AREA_ID_KEY, required = false) Optional<Long> innovationAreaId, @RequestParam(value = PAGE_NUMBER_KEY, required = false) Optional<Integer> pageNumber); }
@Test public void publicContentSearch() throws Exception { CompetitionSearchViewModel competitionSearchViewModel = new CompetitionSearchViewModel(); when(competitionSearchPopulatorMock.createItemSearchViewModel(Optional.empty(), Optional.empty(), Optional.empty())).thenReturn(competitionSearchViewModel); mockMvc.perform(get("/competition/search")) .andExpect(status().isOk()) .andExpect(view().name("competition/search")); verify(competitionSearchPopulatorMock, times(1)).createItemSearchViewModel(Optional.empty(), Optional.empty(), Optional.empty()); }
ScopeViewModelPopulator extends AbstractPublicContentGroupViewModelPopulator<ScopeViewModel> { @Override public PublicContentSectionType getType() { return PublicContentSectionType.SCOPE; } @Override PublicContentSectionType getType(); }
@Test public void getType() { assertEquals(PublicContentSectionType.SCOPE, populator.getType()); }
SummaryViewModelPopulator extends AbstractPublicContentGroupViewModelPopulator<SummaryViewModel> { @Override protected void populateSection(SummaryViewModel model, PublicContentItemResource publicContentItemResource, PublicContentSectionResource section, Boolean nonIFS) { PublicContentResource publicContentResource = publicContentItemResource.getPublicContentResource(); model.setDescription(publicContentResource.getSummary()); model.setFundingType(publicContentItemResource.getFundingType().getDisplayName()); model.setProjectSize(publicContentResource.getProjectSize()); super.populateSection(model, publicContentItemResource, section, nonIFS); } @Override PublicContentSectionType getType(); }
@Test public void populateSection() { populator.populateSection(viewModel, publicContentItemResource, publicContentSectionResource, Boolean.FALSE); assertEquals("Summary", viewModel.getDescription()); assertEquals(FundingType.GRANT.getDisplayName(), viewModel.getFundingType()); assertEquals("5M", viewModel.getProjectSize()); assertEquals(1, viewModel.getContentGroups().size()); assertEquals(contentGroups.get(0).getId(), viewModel.getContentGroups().get(0).getId()); assertTrue(viewModel.getFileEntries().containsKey(contentGroups.get(0).getId())); }
SummaryViewModelPopulator extends AbstractPublicContentGroupViewModelPopulator<SummaryViewModel> { @Override public PublicContentSectionType getType() { return PublicContentSectionType.SUMMARY; } @Override PublicContentSectionType getType(); }
@Test public void getType() { assertEquals(PublicContentSectionType.SUMMARY, populator.getType()); }
EligibilityViewModelPopulator extends AbstractPublicContentGroupViewModelPopulator<EligibilityViewModel> { @Override public PublicContentSectionType getType() { return PublicContentSectionType.ELIGIBILITY; } @Override PublicContentSectionType getType(); }
@Test public void getType() { assertEquals(PublicContentSectionType.ELIGIBILITY, populator.getType()); }
DatesViewModelPopulator extends AbstractPublicContentSectionViewModelPopulator<DatesViewModel> { @Override protected void populateSection(DatesViewModel model, PublicContentItemResource publicContentItemResource, PublicContentSectionResource section, Boolean nonIFS) { List<DateViewModel> publicContentDates = mapContentEventsToDatesViewModel(publicContentItemResource.getPublicContentResource().getContentEvents()); publicContentDates.addAll(getMilestonesAsDatesViewModel(publicContentItemResource.getPublicContentResource().getCompetitionId())); model.setPublicContentDates(publicContentDates); } @Override PublicContentSectionType getType(); }
@Test public void populateSectionWithMilestonesFound() { when(milestoneRestService.getAllPublicMilestonesByCompetitionId(publicContentItemResource.getPublicContentResource().getCompetitionId())) .thenReturn(restSuccess(newMilestoneResource() .withDate(ZonedDateTime.now(), ZonedDateTime.now(), ZonedDateTime.now()) .withType(MilestoneType.OPEN_DATE, MilestoneType.NOTIFICATIONS, MilestoneType.SUBMISSION_DATE) .build(3))); publicContentItemResource.getPublicContentResource().setContentEvents(emptyList()); populator.populateSection(viewModel, publicContentItemResource, publicContentSectionResource, Boolean.FALSE); assertEquals(3, viewModel.getPublicContentDates().size()); } @Test public void populateSectionWithMilestonesNotFound() { when(milestoneRestService.getAllPublicMilestonesByCompetitionId(publicContentItemResource.getPublicContentResource().getCompetitionId())) .thenReturn(restSuccess(emptyList())); publicContentItemResource.getPublicContentResource().setContentEvents(emptyList()); populator.populateSection(viewModel, publicContentItemResource, publicContentSectionResource, Boolean.FALSE); assertEquals(0, viewModel.getPublicContentDates().size()); } @Test public void populateSectionWithNoPublicContentDates() { when(milestoneRestService.getAllPublicMilestonesByCompetitionId(publicContentItemResource.getPublicContentResource().getCompetitionId())) .thenReturn(restSuccess(emptyList())); publicContentItemResource.getPublicContentResource().setContentEvents(emptyList()); populator.populateSection(viewModel, publicContentItemResource, publicContentSectionResource, Boolean.FALSE); assertEquals(0, viewModel.getPublicContentDates().size()); } @Test public void populateSectionWithPublicContentDatesAndMilestones() { when(milestoneRestService.getAllPublicMilestonesByCompetitionId(publicContentItemResource.getPublicContentResource().getCompetitionId())) .thenReturn(restSuccess(newMilestoneResource() .withDate(ZonedDateTime.now(), ZonedDateTime.now().plusDays(3)) .withType(MilestoneType.OPEN_DATE, MilestoneType.SUBMISSION_DATE) .build(2))); publicContentItemResource.getPublicContentResource().setContentEvents(newContentEventResource().build(2)); populator.populateSection(viewModel, publicContentItemResource, publicContentSectionResource, Boolean.FALSE); assertEquals(2, viewModel.getPublicContentDates().size()); } @Test public void populateSectionWithPublicContentDatesAndMilestonesNonIFS() { when(milestoneRestService.getAllPublicMilestonesByCompetitionId(publicContentItemResource.getPublicContentResource().getCompetitionId())) .thenReturn(restSuccess(newMilestoneResource() .withDate(ZonedDateTime.now().plusDays(1), ZonedDateTime.now().plusDays(2), ZonedDateTime.now().plusDays(3), ZonedDateTime.now().plusDays(4)) .withType(MilestoneType.OPEN_DATE, MilestoneType.REGISTRATION_DATE, MilestoneType.NOTIFICATIONS, MilestoneType.SUBMISSION_DATE) .build(4))); publicContentItemResource.getPublicContentResource().setContentEvents(newContentEventResource().build(2)); populator.populateSection(viewModel, publicContentItemResource, publicContentSectionResource, Boolean.TRUE); assertEquals(4, viewModel.getPublicContentDates().size()); }
OrganisationController { @GetMapping("/find-by-id/{organisationId}") public RestResult<OrganisationResource> findById(@PathVariable("organisationId") final Long organisationId) { return organisationService.findById(organisationId).toGetResponse(); } @GetMapping("/find-by-application-id/{applicationId}") RestResult<Set<OrganisationResource>> findByApplicationId(@PathVariable("applicationId") final Long applicationId); @GetMapping("/find-by-id/{organisationId}") RestResult<OrganisationResource> findById(@PathVariable("organisationId") final Long organisationId); @GetMapping("/by-user-and-application-id/{userId}/{applicationId}") RestResult<OrganisationResource> getByUserAndApplicationId(@PathVariable("userId") final long userId, @PathVariable("applicationId") final long applicationId); @GetMapping("/by-user-and-project-id/{userId}/{projectId}") RestResult<OrganisationResource> getByUserAndProjectId(@PathVariable("userId") final long userId, @PathVariable("projectId") final long projectId); @GetMapping("/all-by-user-id/{userId}") RestResult<List<OrganisationResource>> getAllByUserId(@PathVariable("userId") final long userId); @GetMapping() RestResult<List<OrganisationResource>> getOrganisations(@RequestParam final long userId, @RequestParam final boolean international); @PostMapping("/create-or-match") RestResult<OrganisationResource> createOrMatch(@RequestBody OrganisationResource organisation); @PutMapping("/update") RestResult<OrganisationResource> saveResource(@RequestBody OrganisationResource organisationResource); @PostMapping("/update-name-and-registration/{organisationId}") RestResult<OrganisationResource> updateNameAndRegistration(@PathVariable("organisationId") Long organisationId, @RequestParam(value = "name") String name, @RequestParam(value = "registration") String registration); }
@Test public void findByIdShouldReturnOrganisation() throws Exception { when(organisationServiceMock.findById(1L)).thenReturn(serviceSuccess(newOrganisationResource().withId(1L).withName("uniqueOrganisationName").build())); mockMvc.perform(get("/organisation/find-by-id/1")) .andExpect(status().isOk()) .andExpect(jsonPath("$.name", is("uniqueOrganisationName"))); }
DatesViewModelPopulator extends AbstractPublicContentSectionViewModelPopulator<DatesViewModel> { @Override public PublicContentSectionType getType() { return PublicContentSectionType.DATES; } @Override PublicContentSectionType getType(); }
@Test public void getType() { assertEquals(PublicContentSectionType.DATES, populator.getType()); }
HowToApplyViewModelPopulator extends AbstractPublicContentGroupViewModelPopulator<HowToApplyViewModel> { @Override public PublicContentSectionType getType() { return PublicContentSectionType.HOW_TO_APPLY; } @Override PublicContentSectionType getType(); }
@Test public void getType() { assertEquals(PublicContentSectionType.HOW_TO_APPLY, populator.getType()); }
SupportingInformationViewModelPopulator extends AbstractPublicContentGroupViewModelPopulator<SupportingInformationViewModel> { @Override public PublicContentSectionType getType() { return PublicContentSectionType.SUPPORTING_INFORMATION; } @Override PublicContentSectionType getType(); }
@Test public void getType() { assertEquals(PublicContentSectionType.SUPPORTING_INFORMATION, populator.getType()); }
CompetitionSearchPopulator { public CompetitionSearchViewModel createItemSearchViewModel(Optional<Long> innovationAreaId, Optional<String> keywords, Optional<Integer> pageNumber) { CompetitionSearchViewModel viewModel = new CompetitionSearchViewModel(); viewModel.setInnovationAreas(categoryRestService.getInnovationAreas().getSuccess()); PublicContentItemPageResource pageResource = publicContentItemRestService.getByFilterValues( innovationAreaId, keywords, pageNumber, CompetitionSearchViewModel.PAGE_SIZE).getSuccess(); innovationAreaId.ifPresent(viewModel::setSelectedInnovationAreaId); keywords.ifPresent(viewModel::setSearchKeywords); if (pageNumber.isPresent()) { viewModel.setPageNumber(pageNumber.get()); } else { viewModel.setPageNumber(0); } viewModel.setPublicContentItems(pageResource.getContent().stream() .map(this::createPublicContentItemViewModel).collect(Collectors.toList())); viewModel.setTotalResults(pageResource.getTotalElements()); viewModel.setNextPageLink(createPageLink(innovationAreaId, keywords, pageNumber, 1)); viewModel.setPreviousPageLink(createPageLink(innovationAreaId, keywords, pageNumber, -1)); return viewModel; } CompetitionSearchViewModel createItemSearchViewModel(Optional<Long> innovationAreaId, Optional<String> keywords, Optional<Integer> pageNumber); }
@Test public void createItemSearchViewModel() throws Exception { Optional<Long> expectedInnovationAreaId = Optional.of(10L); Optional<String> expectedKeywords = Optional.of("test%20abc"); Optional<Integer> expectedPageNumber = Optional.of(1); RestResult<PublicContentItemPageResource> restResult = restSuccess(publicContentItemPageResourceList); when(publicContentItemRestService.getByFilterValues(expectedInnovationAreaId, expectedKeywords, expectedPageNumber, CompetitionSearchViewModel.PAGE_SIZE)).thenReturn(restResult); CompetitionSearchViewModel viewModel = competitionSearchPopulator.createItemSearchViewModel(expectedInnovationAreaId, expectedKeywords, expectedPageNumber); verify(publicContentItemRestService, times(1)).getByFilterValues(expectedInnovationAreaId,expectedKeywords, expectedPageNumber,CompetitionSearchViewModel.PAGE_SIZE); verify(categoryRestService, times(1)).getInnovationAreas(); assertEquals(publicContentItemPageResourceList.getTotalElements(), (long) viewModel.getTotalResults()); assertEquals(1, (long) viewModel.getPageNumber()); } @Test public void createItemSearchViewModel_noSearchParamsShouldResultInDefaultSearch() throws Exception { Optional<Long> expectedInnovationAreaId = Optional.empty(); Optional<String> expectedKeywords = Optional.empty(); Optional<Integer> expectedPageNumber = Optional.empty(); RestResult<PublicContentItemPageResource> restResult = restSuccess(publicContentItemPageResourceList); when(publicContentItemRestService.getByFilterValues(expectedInnovationAreaId, expectedKeywords, expectedPageNumber, CompetitionSearchViewModel.PAGE_SIZE)).thenReturn(restResult); when(categoryRestService.getInnovationAreas()).thenReturn(restSuccess(innovationAreaResources)); CompetitionSearchViewModel viewModel = competitionSearchPopulator.createItemSearchViewModel(expectedInnovationAreaId, expectedKeywords, expectedPageNumber); assertEquals(publicContentItemPageResourceList.getTotalElements(), (long)viewModel.getTotalResults()); assertEquals(false, viewModel.hasPreviousPage()); assertEquals(false, viewModel.hasNextPage()); } @Test public void createItemSearchViewModel_firstPageShouldProvidePageModelParams() throws Exception { Optional<Long> expectedInnovationAreaId = Optional.of(10L); Optional<String> expectedKeywords = Optional.of("test"); Optional<Integer> expectedPageNumber = Optional.of(0); publicContentItemPageResourceList.setTotalElements(15L); RestResult<PublicContentItemPageResource> restResult = restSuccess(publicContentItemPageResourceList); when(publicContentItemRestService.getByFilterValues(expectedInnovationAreaId, expectedKeywords, expectedPageNumber, CompetitionSearchViewModel.PAGE_SIZE)).thenReturn(restResult); when(categoryRestService.getInnovationAreas()).thenReturn(restSuccess(innovationAreaResources)); CompetitionSearchViewModel viewModel = competitionSearchPopulator.createItemSearchViewModel(expectedInnovationAreaId, expectedKeywords, expectedPageNumber); assertEquals(publicContentItemPageResourceList.getTotalElements(), (long)viewModel.getTotalResults()); assertEquals(0L, (long)viewModel.getPageNumber()); assertEquals(15L, (long)viewModel.getTotalResults()); assertEquals(false, viewModel.hasPreviousPage()); assertEquals(true, viewModel.hasNextPage()); assertEquals(11, viewModel.getNextPageStart()); assertEquals(15, viewModel.getNextPageEnd()); assertEquals("innovationAreaId=10&keywords=test&page=1", viewModel.getNextPageLink()); } @Test public void createItemSearchViewModel_middlePageShouldProvidePageModelParams() throws Exception { Optional<Long> expectedInnovationAreaId = Optional.of(10L); Optional<String> expectedKeywords = Optional.of("test"); Optional<Integer> expectedPageNumber = Optional.of(1); publicContentItemPageResourceList.setTotalElements(21L); RestResult<PublicContentItemPageResource> restResult = restSuccess(publicContentItemPageResourceList); when(publicContentItemRestService.getByFilterValues(expectedInnovationAreaId, expectedKeywords, expectedPageNumber, CompetitionSearchViewModel.PAGE_SIZE)).thenReturn(restResult); when(categoryRestService.getInnovationAreas()).thenReturn(restSuccess(innovationAreaResources)); CompetitionSearchViewModel viewModel = competitionSearchPopulator.createItemSearchViewModel(expectedInnovationAreaId, expectedKeywords, expectedPageNumber); assertEquals(publicContentItemPageResourceList.getTotalElements(), (long)viewModel.getTotalResults()); assertEquals(1L, (long)viewModel.getPageNumber()); assertEquals(21L, (long)viewModel.getTotalResults()); assertEquals(true, viewModel.hasPreviousPage()); assertEquals(1, viewModel.getPreviousPageStart()); assertEquals(10, viewModel.getPreviousPageEnd()); assertEquals("innovationAreaId=10&keywords=test&page=0", viewModel.getPreviousPageLink()); assertEquals(true, viewModel.hasNextPage()); assertEquals(21, viewModel.getNextPageStart()); assertEquals(21, viewModel.getNextPageEnd()); assertEquals("innovationAreaId=10&keywords=test&page=2", viewModel.getNextPageLink()); } @Test public void createItemSearchViewModel_endPageShouldProvidePageModelParams() throws Exception { Optional<Long> expectedInnovationAreaId = Optional.of(10L); Optional<String> expectedKeywords = Optional.of("test"); Optional<Integer> expectedPageNumber = Optional.of(2); publicContentItemPageResourceList.setTotalElements(21L); RestResult<PublicContentItemPageResource> restResult = restSuccess(publicContentItemPageResourceList); when(publicContentItemRestService.getByFilterValues(expectedInnovationAreaId, expectedKeywords, expectedPageNumber, CompetitionSearchViewModel.PAGE_SIZE)).thenReturn(restResult); when(categoryRestService.getInnovationAreas()).thenReturn(restSuccess(innovationAreaResources)); CompetitionSearchViewModel viewModel = competitionSearchPopulator.createItemSearchViewModel(expectedInnovationAreaId, expectedKeywords, expectedPageNumber); assertEquals(publicContentItemPageResourceList.getTotalElements(), (long)viewModel.getTotalResults()); assertEquals(2L, (long)viewModel.getPageNumber()); assertEquals(21L, (long)viewModel.getTotalResults()); assertEquals(true, viewModel.hasPreviousPage()); assertEquals(11, viewModel.getPreviousPageStart()); assertEquals(20, viewModel.getPreviousPageEnd()); assertEquals("innovationAreaId=10&keywords=test&page=1", viewModel.getPreviousPageLink()); assertEquals(false, viewModel.hasNextPage()); } @Test public void createItemSearchViewModel_pageNumberShouldBeAddedToSearchParamInLinks() throws Exception { Optional<Long> expectedInnovationAreaId = Optional.of(10L); Optional<String> expectedKeywords = Optional.of("test"); Optional<Integer> expectedPageNumber = Optional.empty(); publicContentItemPageResourceList.setTotalElements(21L); RestResult<PublicContentItemPageResource> restResult = restSuccess(publicContentItemPageResourceList); when(publicContentItemRestService.getByFilterValues(expectedInnovationAreaId, expectedKeywords, expectedPageNumber, CompetitionSearchViewModel.PAGE_SIZE)).thenReturn(restResult); when(categoryRestService.getInnovationAreas()).thenReturn(restSuccess(innovationAreaResources)); CompetitionSearchViewModel viewModel = competitionSearchPopulator.createItemSearchViewModel(expectedInnovationAreaId, expectedKeywords, expectedPageNumber); assertEquals("innovationAreaId=10&keywords=test&page=1", viewModel.getNextPageLink()); assertEquals("innovationAreaId=10&keywords=test&page=-1", viewModel.getPreviousPageLink()); } @Test public void createItemSearchViewModel_searchParamsShouldBePartiallyReflectedInLinks() throws Exception { Optional<Long> expectedInnovationAreaId = Optional.of(10L); Optional<String> expectedKeywords = Optional.empty(); Optional<Integer> expectedPageNumber = Optional.of(2); publicContentItemPageResourceList.setTotalElements(21L); RestResult<PublicContentItemPageResource> restResult = restSuccess(publicContentItemPageResourceList); when(publicContentItemRestService.getByFilterValues(expectedInnovationAreaId, expectedKeywords, expectedPageNumber, CompetitionSearchViewModel.PAGE_SIZE)).thenReturn(restResult); when(categoryRestService.getInnovationAreas()).thenReturn(restSuccess(innovationAreaResources)); CompetitionSearchViewModel viewModel = competitionSearchPopulator.createItemSearchViewModel(expectedInnovationAreaId, expectedKeywords, expectedPageNumber); assertEquals("innovationAreaId=10&page=3", viewModel.getNextPageLink()); assertEquals("innovationAreaId=10&page=1", viewModel.getPreviousPageLink()); } @Test public void createItemSearchViewModel_statusTextEnumShouldBeConsultedForStatusText() throws Exception { Optional<Long> expectedInnovationAreaId = Optional.of(10L); Optional<String> expectedKeywords = Optional.empty(); Optional<Integer> expectedPageNumber = Optional.of(2); publicContentItemPageResourceList.setTotalElements(21L); RestResult<PublicContentItemPageResource> restResult = restSuccess(publicContentItemPageResourceList); when(publicContentItemRestService.getByFilterValues(expectedInnovationAreaId, expectedKeywords, expectedPageNumber, CompetitionSearchViewModel.PAGE_SIZE)).thenReturn(restResult); when(categoryRestService.getInnovationAreas()).thenReturn(restSuccess(innovationAreaResources)); CompetitionSearchViewModel viewModel = competitionSearchPopulator.createItemSearchViewModel(expectedInnovationAreaId, expectedKeywords, expectedPageNumber); verify(publicContentStatusDeterminer, times(2)).getApplicablePublicContentStatusText(any()); }
OrganisationController { @PostMapping("/create-or-match") public RestResult<OrganisationResource> createOrMatch(@RequestBody OrganisationResource organisation) { return organisationCreationService.createOrMatch(organisation).toPostCreateResponse(); } @GetMapping("/find-by-application-id/{applicationId}") RestResult<Set<OrganisationResource>> findByApplicationId(@PathVariable("applicationId") final Long applicationId); @GetMapping("/find-by-id/{organisationId}") RestResult<OrganisationResource> findById(@PathVariable("organisationId") final Long organisationId); @GetMapping("/by-user-and-application-id/{userId}/{applicationId}") RestResult<OrganisationResource> getByUserAndApplicationId(@PathVariable("userId") final long userId, @PathVariable("applicationId") final long applicationId); @GetMapping("/by-user-and-project-id/{userId}/{projectId}") RestResult<OrganisationResource> getByUserAndProjectId(@PathVariable("userId") final long userId, @PathVariable("projectId") final long projectId); @GetMapping("/all-by-user-id/{userId}") RestResult<List<OrganisationResource>> getAllByUserId(@PathVariable("userId") final long userId); @GetMapping() RestResult<List<OrganisationResource>> getOrganisations(@RequestParam final long userId, @RequestParam final boolean international); @PostMapping("/create-or-match") RestResult<OrganisationResource> createOrMatch(@RequestBody OrganisationResource organisation); @PutMapping("/update") RestResult<OrganisationResource> saveResource(@RequestBody OrganisationResource organisationResource); @PostMapping("/update-name-and-registration/{organisationId}") RestResult<OrganisationResource> updateNameAndRegistration(@PathVariable("organisationId") Long organisationId, @RequestParam(value = "name") String name, @RequestParam(value = "registration") String registration); }
@Test public void createOrMatch_callsOrganisationServiceAndReturnsResultWithNoHash() throws Exception { OrganisationResource organisationResource = newOrganisationResource().build(); Gson gson = new Gson(); String json = gson.toJson(organisationResource, OrganisationResource.class); when(organisationInitialCreationServiceMock.createOrMatch(organisationResource)).thenReturn(serviceSuccess(newOrganisationResource().withId(1L).withName("uniqueOrganisationName").build())); mockMvc.perform(post("/organisation/create-or-match") .contentType(MediaType.APPLICATION_JSON). content(json)) .andExpect(status().isCreated()) .andExpect(jsonPath("$.name", is("uniqueOrganisationName"))); verify(organisationInitialCreationServiceMock, only()).createOrMatch(organisationResource); }
CompetitionOverviewPopulator { public CompetitionOverviewViewModel populateViewModel(PublicContentItemResource publicContentItemResource, boolean userIsLoggedIn) { CompetitionOverviewViewModel viewModel = new CompetitionOverviewViewModel(); viewModel.setCompetitionOpenDate(publicContentItemResource.getCompetitionOpenDate()); viewModel.setCompetitionCloseDate(publicContentItemResource.getCompetitionCloseDate()); viewModel.setRegistrationCloseDate(publicContentItemResource.getRegistrationCloseDate()); viewModel.setCompetitionTitle(publicContentItemResource.getCompetitionTitle()); viewModel.setNonIfsUrl(publicContentItemResource.getNonIfsUrl()); viewModel.setNonIfs(publicContentItemResource.getNonIfs()); viewModel.setUserIsLoggedIn(userIsLoggedIn); viewModel.setCompetitionSetupComplete(publicContentItemResource.getSetupComplete()); viewModel.setH2020(publicContentItemResource.isH2020()); if(null != publicContentItemResource.getPublicContentResource()) { viewModel.setShortDescription(publicContentItemResource.getPublicContentResource().getShortDescription()); viewModel.setCompetitionId(publicContentItemResource.getPublicContentResource().getCompetitionId()); } viewModel.setAllSections(getSectionPopulators(publicContentItemResource)); return viewModel; } @Autowired void setSectionPopulator(Collection<AbstractPublicContentSectionViewModelPopulator> populators); CompetitionOverviewViewModel populateViewModel(PublicContentItemResource publicContentItemResource, boolean userIsLoggedIn); }
@Test public void populateViewModelTest_Default() throws Exception { PublicContentResource publicContentResource = newPublicContentResource() .withShortDescription("Short description") .withCompetitionId(23523L) .build(); CompetitionOverviewViewModel viewModel = populator.populateViewModel(setupPublicContent(publicContentResource), true); assertEquals(publicContentResource.getShortDescription(), viewModel.getShortDescription()); assertEquals(publicContentResource.getCompetitionId(), viewModel.getCompetitionId()); assertEquals(openDate, viewModel.getCompetitionOpenDate()); assertEquals(closeDate, viewModel.getCompetitionCloseDate()); assertEquals(closeDate.minusDays(7), viewModel.getRegistrationCloseDate()); assertEquals(competitionTitle, viewModel.getCompetitionTitle()); assertEquals(nonIfsUrl, viewModel.getNonIfsUrl()); assertEquals(true, viewModel.isUserIsLoggedIn()); assertEquals(true, viewModel.isCompetitionSetupComplete()); assertEquals(true, viewModel.isH2020()); } @Test public void populateViewModelTest_EmptyPublicContentResource() throws Exception { PublicContentResource publicContentResource = newPublicContentResource().build(); CompetitionOverviewViewModel viewModel = populator.populateViewModel(setupPublicContent(publicContentResource), true); assertEquals(null, viewModel.getShortDescription()); assertEquals(null, viewModel.getCompetitionId()); assertEquals(openDate, viewModel.getCompetitionOpenDate()); assertEquals(closeDate, viewModel.getCompetitionCloseDate()); assertEquals(competitionTitle, viewModel.getCompetitionTitle()); assertEquals(true, viewModel.isUserIsLoggedIn()); assertEquals(true, viewModel.isCompetitionSetupComplete()); } @Test public void populateViewModelTest_NullPublicContentResource() throws Exception { CompetitionOverviewViewModel viewModel = populator.populateViewModel(setupPublicContent(null), true); assertEquals(null, viewModel.getShortDescription()); assertEquals(null, viewModel.getCompetitionId()); assertEquals(openDate, viewModel.getCompetitionOpenDate()); assertEquals(closeDate, viewModel.getCompetitionCloseDate()); assertEquals(competitionTitle, viewModel.getCompetitionTitle()); assertEquals(true, viewModel.isUserIsLoggedIn()); assertEquals(true, viewModel.isCompetitionSetupComplete()); } @Test public void populateViewModelTest_setupNotComplete() throws Exception { final PublicContentItemResource publicContentItemResource = setupPublicContent(newPublicContentResource() .withCompetitionId(1L) .withShortDescription("Short description") .build()); publicContentItemResource.setSetupComplete(false); final CompetitionOverviewViewModel viewModel = populator.populateViewModel(publicContentItemResource, true); assertEquals(openDate, viewModel.getCompetitionOpenDate()); assertEquals(closeDate, viewModel.getCompetitionCloseDate()); assertEquals(competitionTitle, viewModel.getCompetitionTitle()); assertFalse(viewModel.isCompetitionSetupComplete()); assertFalse(viewModel.getNonIfs()); assertTrue(viewModel.isShowNotOpenYetMessage()); assertEquals(1L, viewModel.getCompetitionId().longValue()); assertEquals("Short description", viewModel.getShortDescription()); } @Test public void populateViewModelTest_setupNotCompleteCompetitionNotOpen() throws Exception { final ZonedDateTime openDateFuture = LocalDateTime.of(LocalDateTime.now().getYear() + 1, 1, 1, 0, 0).atZone(ZoneId.systemDefault()); final ZonedDateTime closeDateFuture = LocalDateTime.of(LocalDateTime.now().getYear() + 1, 1, 1, 0, 0).atZone(ZoneId.systemDefault()); final PublicContentItemResource publicContentItemResource = newPublicContentItemResource() .withCompetitionOpenDate(openDateFuture) .withCompetitionCloseDate(closeDateFuture) .withCompetitionTitle(competitionTitle) .withPublicContentResource(newPublicContentResource() .withCompetitionId(1L) .withShortDescription("Short description") .build()) .withNonIfs(false) .withSetupComplete(false) .build(); final CompetitionOverviewViewModel viewModel = populator.populateViewModel(publicContentItemResource, true); assertEquals(openDateFuture, viewModel.getCompetitionOpenDate()); assertEquals(closeDateFuture, viewModel.getCompetitionCloseDate()); assertEquals(competitionTitle, viewModel.getCompetitionTitle()); assertFalse(viewModel.isCompetitionSetupComplete()); assertFalse(viewModel.getNonIfs()); assertTrue(viewModel.isShowNotOpenYetMessage()); assertEquals(1L, viewModel.getCompetitionId().longValue()); assertEquals("Short description", viewModel.getShortDescription()); } @Test public void populateViewModelTest_nonIfs() throws Exception { final PublicContentItemResource publicContentItemResource = setupPublicContent(newPublicContentResource() .withCompetitionId(1L) .withShortDescription("Short description") .build()); publicContentItemResource.setNonIfs(true); ZonedDateTime newCloseDate = closeDate.plusDays(5); publicContentItemResource.setCompetitionCloseDate(newCloseDate); final CompetitionOverviewViewModel viewModel = populator.populateViewModel(publicContentItemResource, true); assertEquals(openDate, viewModel.getCompetitionOpenDate()); assertEquals(newCloseDate, viewModel.getCompetitionCloseDate()); assertEquals(competitionTitle, viewModel.getCompetitionTitle()); assertTrue(viewModel.getRegistrationCloseDate().isBefore(ZonedDateTime.now())); assertTrue(viewModel.isCompetitionSetupComplete()); assertTrue(viewModel.getNonIfs()); assertFalse(viewModel.isShowNotOpenYetMessage()); assertFalse(viewModel.isShowClosedMessage()); assertTrue(viewModel.isShowRegistrationClosedMessage()); assertEquals(1L, viewModel.getCompetitionId().longValue()); assertEquals("Short description", viewModel.getShortDescription()); }
OrganisationController { @GetMapping("/by-user-and-application-id/{userId}/{applicationId}") public RestResult<OrganisationResource> getByUserAndApplicationId(@PathVariable("userId") final long userId, @PathVariable("applicationId") final long applicationId) { return organisationService.getByUserAndApplicationId(userId, applicationId).toGetResponse(); } @GetMapping("/find-by-application-id/{applicationId}") RestResult<Set<OrganisationResource>> findByApplicationId(@PathVariable("applicationId") final Long applicationId); @GetMapping("/find-by-id/{organisationId}") RestResult<OrganisationResource> findById(@PathVariable("organisationId") final Long organisationId); @GetMapping("/by-user-and-application-id/{userId}/{applicationId}") RestResult<OrganisationResource> getByUserAndApplicationId(@PathVariable("userId") final long userId, @PathVariable("applicationId") final long applicationId); @GetMapping("/by-user-and-project-id/{userId}/{projectId}") RestResult<OrganisationResource> getByUserAndProjectId(@PathVariable("userId") final long userId, @PathVariable("projectId") final long projectId); @GetMapping("/all-by-user-id/{userId}") RestResult<List<OrganisationResource>> getAllByUserId(@PathVariable("userId") final long userId); @GetMapping() RestResult<List<OrganisationResource>> getOrganisations(@RequestParam final long userId, @RequestParam final boolean international); @PostMapping("/create-or-match") RestResult<OrganisationResource> createOrMatch(@RequestBody OrganisationResource organisation); @PutMapping("/update") RestResult<OrganisationResource> saveResource(@RequestBody OrganisationResource organisationResource); @PostMapping("/update-name-and-registration/{organisationId}") RestResult<OrganisationResource> updateNameAndRegistration(@PathVariable("organisationId") Long organisationId, @RequestParam(value = "name") String name, @RequestParam(value = "registration") String registration); }
@Test public void getByUserAndApplicationId() throws Exception { when(organisationServiceMock.getByUserAndApplicationId(1L, 2L)).thenReturn(serviceSuccess(newOrganisationResource().withId(1L).withName("uniqueOrganisationName").build())); mockMvc.perform(get("/organisation/by-user-and-application-id/1/2")) .andExpect(status().isOk()) .andExpect(jsonPath("$.name", is("uniqueOrganisationName"))); }
PublicContentItemViewModelMapper { public PublicContentItemViewModel mapToViewModel(PublicContentItemResource publicContentItemResource) { PublicContentItemViewModel publicContentItemViewModel = new PublicContentItemViewModel(); publicContentItemViewModel.setCompetitionTitle(publicContentItemResource.getCompetitionTitle()); publicContentItemViewModel.setCompetitionCloseDate(publicContentItemResource.getCompetitionCloseDate()); publicContentItemViewModel.setCompetitionOpenDate(publicContentItemResource.getCompetitionOpenDate()); publicContentItemViewModel.setRegistrationCloseDate(publicContentItemResource.getRegistrationCloseDate()); PublicContentResource publicContentResource = publicContentItemResource.getPublicContentResource(); publicContentItemViewModel.setEligibilitySummary(publicContentResource.getEligibilitySummary()); publicContentItemViewModel.setShortDescription(publicContentResource.getShortDescription()); publicContentItemViewModel.setCompetitionId(publicContentResource.getCompetitionId()); return publicContentItemViewModel; } PublicContentItemViewModel mapToViewModel(PublicContentItemResource publicContentItemResource); }
@Test public void mapToViewModel_expectedResourceVariablesAreMappedToViewModel() throws Exception { String eligibilitySummary = "eligibility summary"; String shortDescription = "short description"; Long competitionId = 123L; ZonedDateTime openDate = ZonedDateTime.now().minusDays(3L); ZonedDateTime closedDate = ZonedDateTime.now().plusDays(3L); String competitionTitle = "competition title"; PublicContentResource publicContentResource = newPublicContentResource() .withEligibilitySummary(eligibilitySummary) .withShortDescription(shortDescription) .withCompetitionId(competitionId).build(); PublicContentItemResource publicContentItemResource = newPublicContentItemResource() .withCompetitionOpenDate(openDate) .withCompetitionCloseDate(closedDate) .withCompetitionTitle(competitionTitle) .withPublicContentResource(publicContentResource).build(); PublicContentItemViewModelMapper contentItemViewModelMapper = new PublicContentItemViewModelMapper(); PublicContentItemViewModel result = contentItemViewModelMapper.mapToViewModel(publicContentItemResource); assertEquals(closedDate, result.getCompetitionCloseDate()); assertEquals(openDate, result.getCompetitionOpenDate()); assertEquals(competitionTitle, result.getCompetitionTitle()); assertEquals(eligibilitySummary, result.getEligibilitySummary()); assertEquals(shortDescription, result.getShortDescription()); assertEquals(competitionId, result.getCompetitionId()); }
AcceptGrantsInviteController { @GetMapping("/{hash}") public String inviteEntryPage( @PathVariable final long projectId, @PathVariable final String hash, HttpServletResponse response, Model model, UserResource loggedInUser) { RestResult<String> result = find(inviteByHash(projectId, hash)).andOnSuccess((invite) -> { ValidationMessages errors = validateUserCanAcceptInvite(loggedInUser, invite); if (errors.hasErrors()) { return populateModelWithErrorsAndReturnErrorView(errors, model); } cookieUtil.saveToCookie(response, INVITE_HASH, hash); model.addAttribute("model", new GrantsInviteViewModel(invite.getApplicationId(), projectId, invite.getProjectName(), invite.getGrantsInviteRole(), invite.userExists(), loggedInUser != null)); return restSuccess("project/grants-invite/accept-invite"); }); if (result.isFailure()) { return ACCEPT_INVITE_FAILURE; } else { return result.getSuccess(); } } @GetMapping("/{hash}") String inviteEntryPage( @PathVariable final long projectId, @PathVariable final String hash, HttpServletResponse response, Model model, UserResource loggedInUser); @GetMapping("accept-authenticated") String acceptInviteUserDoesExistConfirm(HttpServletRequest request, @PathVariable long projectId, UserResource loggedInUser, Model model); static RestResult<String> populateModelWithErrorsAndReturnErrorView(ValidationMessages errors, Model model); static ValidationMessages validateUserCanAcceptInvite(UserResource loggedInUser, SentGrantsInviteResource invite); static final String INVITE_HASH; static final String ACCEPT_INVITE_FAILURE; }
@Test public void inviteEntryPage() throws Exception { String hash = "hash"; long projectId = 1L; SentGrantsInviteResource invite = newSentGrantsInviteResource() .withStatus(SENT) .withEmail("[email protected]") .build(); when(grantsInviteRestService.getInviteByHash(projectId, hash)).thenReturn(restSuccess(invite)); logoutCurrentUser(); MvcResult result = mockMvc.perform(get("/project/{id}/grants/invite/{hash}", projectId, hash)) .andExpect(status().isOk()) .andExpect(view().name("project/grants-invite/accept-invite")) .andReturn(); GrantsInviteViewModel viewmodel = (GrantsInviteViewModel) result.getModelAndView().getModel().get("model"); assertFalse(viewmodel.isUserExists()); assertEquals(invite.getProjectName(), viewmodel.getProjectName()); }
SetupSectionsPermissionRules { @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") public boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user) { return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessProjectDetailsSection); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void projectDetailsSectionAccess() { assertScenariosForSections(SetupSectionAccessibilityHelper::canAccessProjectDetailsSection, () -> rules.partnerCanAccessProjectDetailsSection(ProjectCompositeId.id(activeProject.getId()), user)); verify(projectService).getById(activeProject.getId()); } @Test public void projectDetailsSectionAccessUnavailableForWithdrawnProject() { assertLeadPartnerWithdrawnProjectAccess(() -> rules.partnerCanAccessProjectDetailsSection(ProjectCompositeId.id(withdrawnProject.getId()), user)); verify(projectService).getById(withdrawnProject.getId()); }
SetupSectionsPermissionRules { @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") public boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user) { return !isMonitoringOfficerOnProject(projectCompositeId.id(), user.getId()) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::leadCanAccessProjectManagerPage); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void projectManagerPageAccess() { assertLeadPartnerSuccessfulAccess(SetupSectionAccessibilityHelper::leadCanAccessProjectManagerPage, () -> rules.leadCanAccessProjectManagerPage(ProjectCompositeId.id(activeProject.getId()), user)); verify(projectService, times(2)).getById(activeProject.getId()); } @Test public void projectManagerPageAccessUnavailableForWithdrawnProject() { assertLeadPartnerWithdrawnProjectAccess(() -> rules.leadCanAccessProjectManagerPage(ProjectCompositeId.id(withdrawnProject.getId()), user)); verify(projectService, times(2)).getById(withdrawnProject.getId()); }
SetupSectionsPermissionRules { @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") public boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user) { return !isMonitoringOfficerOnProject(projectCompositeId.id(), user.getId()) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::leadCanAccessProjectAddressPage); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void projectAddressPageAccess() { assertLeadPartnerSuccessfulAccess(SetupSectionAccessibilityHelper::leadCanAccessProjectAddressPage, () -> rules.leadCanAccessProjectAddressPage(ProjectCompositeId.id(activeProject.getId()), user)); verify(projectService, times(2)).getById(activeProject.getId()); } @Test public void projectAddressPageAccessUnavailableForWithdrawnProject() { assertLeadPartnerWithdrawnProjectAccess(() -> rules.leadCanAccessProjectAddressPage(ProjectCompositeId.id(withdrawnProject.getId()), user)); verify(projectService, times(2)).getById(withdrawnProject.getId()); }
SetupSectionsPermissionRules { @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") public boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user) { return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessFinanceContactPage); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void financeContactPageAccess() { assertNonLeadPartnerSuccessfulAccess(SetupSectionAccessibilityHelper::canAccessFinanceContactPage, () -> rules.partnerCanAccessFinanceContactPage(ProjectCompositeId.id(activeProject.getId()), user)); verify(projectService).getById(activeProject.getId()); } @Test public void financeContactPageAccessUnavailableForWithdrawnProject() { assertNonLeadPartnerWithdrawnProjectAccess(() -> rules.partnerCanAccessFinanceContactPage(ProjectCompositeId.id(withdrawnProject.getId()), user)); verify(projectService).getById(withdrawnProject.getId()); }
SetupSectionsPermissionRules { @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") public boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user) { boolean partnerProjectLocationRequired = isPartnerProjectLocationRequired(projectCompositeId); return doSectionCheck(projectCompositeId.id(), user, (setupSectionAccessibilityHelper, organisation) -> setupSectionAccessibilityHelper.canAccessPartnerProjectLocationPage(organisation, partnerProjectLocationRequired)); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void partnerProjectLocationPageAccess() { setUpPartnerProjectLocationRequiredMocking(); assertNonLeadPartnerSuccessfulAccess((setupSectionAccessibilityHelper, organisation) -> setupSectionAccessibilityHelper.canAccessPartnerProjectLocationPage(organisation, true), () -> rules.partnerCanAccessProjectLocationPage(ProjectCompositeId.id(activeProject.getId()), user)); verify(projectService, times(2)).getById(activeProject.getId()); } @Test public void projectLocationSectionAccessUnavailableForWithdrawnProject() { setUpPartnerProjectLocationRequiredMocking(); assertNonLeadPartnerWithdrawnProjectAccess(() -> rules.partnerCanAccessProjectLocationPage(ProjectCompositeId.id(withdrawnProject.getId()), user)); verify(projectService, times(2)).getById(withdrawnProject.getId()); }
SetupSectionsPermissionRules { @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") public boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user) { boolean partnerProjectLocationRequired = isPartnerProjectLocationRequired(projectCompositeId); return doSectionCheck(projectCompositeId.id(), user, (setupSectionAccessibilityHelper, organisation) -> setupSectionAccessibilityHelper.canAccessMonitoringOfficerSection(organisation, partnerProjectLocationRequired)); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void monitoringOfficerSectionAccess() { setUpPartnerProjectLocationRequiredMocking(); assertNonLeadPartnerSuccessfulAccess((setupSectionAccessibilityHelper, organisation) -> setupSectionAccessibilityHelper.canAccessMonitoringOfficerSection(organisation, true), () -> rules.partnerCanAccessMonitoringOfficerSection(ProjectCompositeId.id(activeProject.getId()), user)); verify(projectService, times(2)).getById(activeProject.getId()); } @Test public void monitoringOfficerSectionAccessUnavailableForWithdrawnProject() { setUpPartnerProjectLocationRequiredMocking(); assertNonLeadPartnerWithdrawnProjectAccess(() -> rules.partnerCanAccessMonitoringOfficerSection(ProjectCompositeId.id(withdrawnProject.getId()), user)); verify(projectService, times(2)).getById(withdrawnProject.getId()); }
SetupSectionsPermissionRules { @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") public boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user) { return !isMonitoringOfficerOnProject(projectCompositeId.id(), user.getId()) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessBankDetailsSection); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void bankDetailsSectionAccess() { assertNonLeadPartnerSuccessfulAccess(SetupSectionAccessibilityHelper::canAccessBankDetailsSection, () -> rules.partnerCanAccessBankDetailsSection(ProjectCompositeId.id(activeProject.getId()), user)); verify(projectService, times(2)).getById(activeProject.getId()); } @Test public void bankDetailsSectionAccessMonitoringOfficer() { activeProject.setMonitoringOfficerUser(monitoringOfficer.getId()); when(projectService.getById(activeProject.getId())).thenReturn(activeProject); assertMonitoringOfficerUnSuccessfulAccess(SetupSectionAccessibilityHelper::canAccessBankDetailsSection, () -> rules.partnerCanAccessBankDetailsSection(ProjectCompositeId.id(activeProject.getId()), monitoringOfficer)); verify(projectService).getById(activeProject.getId()); } @Test public void bankDetailsSectionAccessUnavailableForWithdrawnProject() { assertNonLeadPartnerWithdrawnProjectAccess(() -> rules.partnerCanAccessBankDetailsSection(ProjectCompositeId.id(withdrawnProject.getId()), user)); verify(projectService, times(2)).getById(withdrawnProject.getId()); }
OrganisationController { @GetMapping("/by-user-and-project-id/{userId}/{projectId}") public RestResult<OrganisationResource> getByUserAndProjectId(@PathVariable("userId") final long userId, @PathVariable("projectId") final long projectId) { return organisationService.getByUserAndProjectId(userId, projectId).toGetResponse(); } @GetMapping("/find-by-application-id/{applicationId}") RestResult<Set<OrganisationResource>> findByApplicationId(@PathVariable("applicationId") final Long applicationId); @GetMapping("/find-by-id/{organisationId}") RestResult<OrganisationResource> findById(@PathVariable("organisationId") final Long organisationId); @GetMapping("/by-user-and-application-id/{userId}/{applicationId}") RestResult<OrganisationResource> getByUserAndApplicationId(@PathVariable("userId") final long userId, @PathVariable("applicationId") final long applicationId); @GetMapping("/by-user-and-project-id/{userId}/{projectId}") RestResult<OrganisationResource> getByUserAndProjectId(@PathVariable("userId") final long userId, @PathVariable("projectId") final long projectId); @GetMapping("/all-by-user-id/{userId}") RestResult<List<OrganisationResource>> getAllByUserId(@PathVariable("userId") final long userId); @GetMapping() RestResult<List<OrganisationResource>> getOrganisations(@RequestParam final long userId, @RequestParam final boolean international); @PostMapping("/create-or-match") RestResult<OrganisationResource> createOrMatch(@RequestBody OrganisationResource organisation); @PutMapping("/update") RestResult<OrganisationResource> saveResource(@RequestBody OrganisationResource organisationResource); @PostMapping("/update-name-and-registration/{organisationId}") RestResult<OrganisationResource> updateNameAndRegistration(@PathVariable("organisationId") Long organisationId, @RequestParam(value = "name") String name, @RequestParam(value = "registration") String registration); }
@Test public void getByUserAndProjectId() throws Exception { when(organisationServiceMock.getByUserAndProjectId(1L, 2L)).thenReturn(serviceSuccess(newOrganisationResource().withId(1L).withName("uniqueOrganisationName").build())); mockMvc.perform(get("/organisation/by-user-and-project-id/1/2")) .andExpect(status().isOk()) .andExpect(jsonPath("$.name", is("uniqueOrganisationName"))); }
SetupSectionsPermissionRules { @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") public boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user) { return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessSpendProfileSection); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void spendProfileSectionAccess() { assertNonLeadPartnerSuccessfulAccess(SetupSectionAccessibilityHelper::canAccessSpendProfileSection, () -> rules.partnerCanAccessSpendProfileSection(ProjectCompositeId.id(activeProject.getId()), user)); verify(projectService).getById(activeProject.getId()); } @Test public void spendProfileSectionAccessMonitoringOfficer() { assertMonitoringOfficerSuccessfulAccess(SetupSectionAccessibilityHelper::canAccessSpendProfileSection, () -> rules.partnerCanAccessSpendProfileSection(ProjectCompositeId.id(activeProject.getId()), monitoringOfficer)); verify(projectService).getById(activeProject.getId()); } @Test public void spendProfileSectionAccessUnavailableForWithdrawnProject() { assertNonLeadPartnerWithdrawnProjectAccess(() -> rules.partnerCanAccessSpendProfileSection(ProjectCompositeId.id(withdrawnProject.getId()), user)); verify(projectService).getById(withdrawnProject.getId()); }
SetupSectionsPermissionRules { @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") public boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user) { return isProjectManager(projectCompositeId.id(), user) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessSpendProfileSection); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void projectManagerTotalSpendProfileSectionAccess() { assertLeadPartnerSuccessfulAccess(SetupSectionAccessibilityHelper::canAccessSpendProfileSection, () -> rules.projectManagerCanAccessSpendProfileSection(ProjectCompositeId.id(activeProject.getId()), user)); verify(projectService).getById(activeProject.getId()); } @Test public void partnerTotalSpendProfileSectionNoAccess() { assertNonLeadPartnerAndNotMOUnsuccessfulAccess(SetupSectionAccessibilityHelper::canAccessSpendProfileSection, () -> rules.projectManagerCanAccessSpendProfileSection(ProjectCompositeId.id(activeProject.getId()), user)); }
SetupSectionsPermissionRules { @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") public boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) { return doSectionCheck(projectOrganisationCompositeId.getProjectId(), user, (setupSectionAccessibilityHelper, organisation) -> setupSectionAccessibilityHelper.canEditSpendProfileSection(organisation, projectOrganisationCompositeId.getOrganisationId())); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void editSpendProfileSectionAccess() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(activeProject.getId(), 22L); assertNonLeadPartnerSuccessfulAccess((setupSectionAccessibilityHelper, organisation) -> setupSectionAccessibilityHelper.canEditSpendProfileSection(organisation, projectOrganisationCompositeId.getOrganisationId()), () -> rules.partnerCanEditSpendProfileSection(projectOrganisationCompositeId, user)); verify(projectService).getById(activeProject.getId()); } @Test public void editSpendProfileSectionAccessUnavailableForWithdrawnProject() { ProjectOrganisationCompositeId projectOrganisationCompositeId = new ProjectOrganisationCompositeId(withdrawnProject.getId(), 22L); assertNonLeadPartnerWithdrawnProjectAccess(() -> rules.partnerCanEditSpendProfileSection(projectOrganisationCompositeId, user)); verify(projectService).getById(withdrawnProject.getId()); }
SetupSectionsPermissionRules { @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") public boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user) { return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessDocumentsSection); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void documentsSectionAccessLead() { assertLeadPartnerSuccessfulAccess(SetupSectionAccessibilityHelper::canAccessDocumentsSection, () -> rules.canAccessDocumentsSection(ProjectCompositeId.id(activeProject.getId()), user)); verify(projectService).getById(activeProject.getId()); } @Test public void documentsSectionAccessMonitoringOfficer() { assertMonitoringOfficerSuccessfulAccess(SetupSectionAccessibilityHelper::canAccessDocumentsSection, () -> rules.canAccessDocumentsSection(ProjectCompositeId.id(activeProject.getId()), monitoringOfficer)); verify(projectService).getById(activeProject.getId()); } @Test public void documentsSectionAccessNonLead() { assertNonLeadPartnerSuccessfulAccess(SetupSectionAccessibilityHelper::canAccessDocumentsSection, () -> rules.canAccessDocumentsSection(ProjectCompositeId.id(activeProject.getId()), user)); verify(projectService).getById(activeProject.getId()); }
SetupSectionsPermissionRules { @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") public boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user) { return isProjectManager(projectCompositeId.id(), user); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void projectManagerCanEditDocumentsSection() { when(projectService.isProjectManager(user.getId(), activeProject.getId())).thenReturn(true); assertTrue(rules.projectManagerCanEditDocumentsSection(ProjectCompositeId.id(activeProject.getId()), user)); }
OrganisationServiceImpl extends BaseTransactionalService implements OrganisationService { @Override @Transactional public ServiceResult<OrganisationResource> update(final OrganisationResource organisationResource) { return serviceSuccess(organisationMapper.mapToResource(createNewOrganisation(organisationResource))); } @Override ServiceResult<Set<OrganisationResource>> findByApplicationId(final long applicationId); @Override ServiceResult<OrganisationResource> findById(final long organisationId); @Override ServiceResult<OrganisationResource> getByUserAndApplicationId(long userId, long applicationId); @Override ServiceResult<OrganisationResource> getByUserAndProjectId(long userId, long projectId); @Override ServiceResult<List<OrganisationResource>> getAllByUserId(long userId); @Override ServiceResult<List<OrganisationResource>> getOrganisations(long userId, boolean international); @Override @Transactional ServiceResult<OrganisationResource> create(final OrganisationResource organisationToCreate); @Override @Transactional ServiceResult<OrganisationResource> update(final OrganisationResource organisationResource); @Override @Transactional ServiceResult<OrganisationResource> updateOrganisationNameAndRegistration(final long organisationId, final String organisationName, final String registrationNumber); @Override @Transactional ServiceResult<OrganisationResource> addAddress(final long organisationId, final OrganisationAddressType organisationAddressType, AddressResource addressResource); @Override ServiceResult<List<OrganisationSearchResult>> searchAcademic(final String organisationName, int maxItems); @Override ServiceResult<OrganisationSearchResult> getSearchOrganisation(final long searchOrganisationId); }
@Test public void update() throws Exception { }
SetupSectionsPermissionRules { @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") public boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user) { return isProjectInViewableState(projectCompositeId.id()); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void projectTeamStatusAccessUnavailableForWithdrawnProject() { assertLeadPartnerWithdrawnProjectAccess(() -> rules.partnerCanAccessProjectTeamStatus(ProjectCompositeId.id(withdrawnProject.getId()), user)); verify(projectService).getById(withdrawnProject.getId()); }
CompaniesHouseApiServiceImpl implements CompaniesHouseApiService { @Override public ServiceResult<List<OrganisationSearchResult>> searchOrganisations(String encodedSearchText) { return decodeString(encodedSearchText).andOnSuccess(decodedSearchText -> { JsonNode companiesResources = restGet(COMPANIES_HOUSE_SEARCH_PATH, JsonNode.class, companySearchUrlVariables(decodedSearchText)); JsonNode companyItems = companiesResources.path("items"); List<OrganisationSearchResult> results = new ArrayList<>(); companyItems.forEach(i -> results.add(companySearchMapper(i))); return serviceSuccess(results); }); } @Override ServiceResult<List<OrganisationSearchResult>> searchOrganisations(String encodedSearchText); @Override ServiceResult<OrganisationSearchResult> getOrganisationById(String id); }
@Test public void searchOrganisations() { Map<String, Object> companyResultMap = companyResultMap(); JsonNode resultNode = new ObjectMapper().valueToTree(asMap("items", asList(companyResultMap))); ResponseEntity<JsonNode> response = new ResponseEntity<JsonNode>(resultNode, HttpStatus.OK); when(adapter.restGetEntity(searchUrlPath, JsonNode.class, searchVariables)).thenReturn(response); ServiceResult<List<OrganisationSearchResult>> result = service.searchOrganisations(defaultSearchString); verify(adapter).restGetEntity(searchUrlPath, JsonNode.class, searchVariables); assertTrue(result.isSuccess()); assertEquals(1, result.getSuccess().size()); assertEquals("company name", result.getSuccess().get(0).getName()); assertEquals("1234", result.getSuccess().get(0).getOrganisationSearchId()); assertEquals("line1", result.getSuccess().get(0).getOrganisationAddress().getAddressLine1()); assertEquals("line2", result.getSuccess().get(0).getOrganisationAddress().getAddressLine2()); assertEquals("line3", result.getSuccess().get(0).getOrganisationAddress().getAddressLine3()); assertEquals("loc", result.getSuccess().get(0).getOrganisationAddress().getTown()); assertEquals("reg", result.getSuccess().get(0).getOrganisationAddress().getCounty()); assertEquals("ba1", result.getSuccess().get(0).getOrganisationAddress().getPostcode()); } @Test public void searchOrganisationsNullAddressLine() { Map<String, Object> companyResultMap = companyResultMap(); ((Map<String,Object>)companyResultMap.get("address")).put("address_line_1", null); JsonNode resultNode = new ObjectMapper().valueToTree(asMap("items", asList(companyResultMap))); ResponseEntity<JsonNode> response = new ResponseEntity<JsonNode>(resultNode, HttpStatus.OK); when(adapter.restGetEntity(searchUrlPath, JsonNode.class, searchVariables)).thenReturn(response); ServiceResult<List<OrganisationSearchResult>> result = service.searchOrganisations("searchtext"); verify(adapter).restGetEntity(searchUrlPath, JsonNode.class, searchVariables); assertTrue(result.isSuccess()); assertEquals(1, result.getSuccess().size()); assertEquals("company name", result.getSuccess().get(0).getName()); assertEquals("1234", result.getSuccess().get(0).getOrganisationSearchId()); assertNull(result.getSuccess().get(0).getOrganisationAddress().getAddressLine1()); assertEquals("line2", result.getSuccess().get(0).getOrganisationAddress().getAddressLine2()); assertEquals("line3", result.getSuccess().get(0).getOrganisationAddress().getAddressLine3()); assertEquals("loc", result.getSuccess().get(0).getOrganisationAddress().getTown()); assertEquals("reg", result.getSuccess().get(0).getOrganisationAddress().getCounty()); assertEquals("ba1", result.getSuccess().get(0).getOrganisationAddress().getPostcode()); } @Test public void searchOrganisationsNullAddress() { Map<String, Object> companyResultMap = companyResultMap(); companyResultMap.put("address", null); JsonNode resultNode = new ObjectMapper().valueToTree(asMap("items", asList(companyResultMap))); ResponseEntity<JsonNode> response = new ResponseEntity<JsonNode>(resultNode, HttpStatus.OK); when(adapter.restGetEntity(searchUrlPath, JsonNode.class, searchVariables)).thenReturn(response); ServiceResult<List<OrganisationSearchResult>> result = service.searchOrganisations(defaultSearchString); verify(adapter).restGetEntity(searchUrlPath, JsonNode.class, searchVariables); assertTrue(result.isSuccess()); assertEquals(1, result.getSuccess().size()); assertEquals("company name", result.getSuccess().get(0).getName()); assertEquals("1234", result.getSuccess().get(0).getOrganisationSearchId()); assertNull(result.getSuccess().get(0).getOrganisationAddress().getAddressLine1()); assertNull(result.getSuccess().get(0).getOrganisationAddress().getAddressLine2()); assertNull(result.getSuccess().get(0).getOrganisationAddress().getAddressLine3()); assertNull(result.getSuccess().get(0).getOrganisationAddress().getTown()); assertNull(result.getSuccess().get(0).getOrganisationAddress().getCounty()); assertNull(result.getSuccess().get(0).getOrganisationAddress().getPostcode()); }
SetupSectionsPermissionRules { @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") public boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user) { return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessGrantOfferLetterSection); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void grantOfferLetterSectionAccess() { assertNonLeadPartnerSuccessfulAccess(SetupSectionAccessibilityHelper::canAccessGrantOfferLetterSection, () -> rules.partnerCanAccessGrantOfferLetterSection(ProjectCompositeId.id(activeProject.getId()), user)); verify(projectService).getById(activeProject.getId()); } @Test public void grantOfferLetterSectionAccessMonitoringOfficer() { assertMonitoringOfficerSuccessfulAccess(SetupSectionAccessibilityHelper::canAccessGrantOfferLetterSection, () -> rules.partnerCanAccessGrantOfferLetterSection(ProjectCompositeId.id(activeProject.getId()), monitoringOfficer)); verify(projectService).getById(activeProject.getId()); }
SetupSectionsPermissionRules { @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") public boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user) { return doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessGrantOfferLetterSection) && projectService.isUserLeadPartner(projectCompositeId.id(), user.getId()); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void signedGrantOfferLetterSuccessfulAccessByLead() { assertLeadPartnerSuccessfulAccess(SetupSectionAccessibilityHelper::canAccessGrantOfferLetterSection, () -> rules.leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId.id(activeProject.getId()), user)); verify(projectService).getById(activeProject.getId()); } @Test public void signedGrantOfferLetterUnSuccessfulAccessByNonLead() { assertNonLeadPartnerUnsuccessfulAccess(SetupSectionAccessibilityHelper::canAccessGrantOfferLetterSection, () -> rules.leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId.id(activeProject.getId()), user)); }
SetupSectionsPermissionRules { @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") public boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user) { List<ProjectUserResource> projectLeadPartners = projectService.getLeadPartners(projectCompositeId.id()); Optional<ProjectUserResource> returnedProjectUser = simpleFindFirst(projectLeadPartners, projectUserResource -> projectUserResource.getUser().equals(user.getId())); return returnedProjectUser.isPresent(); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void markSpendProfileIncompleteAccess() { ProjectUserResource leadPartnerProjectUserResource = newProjectUserResource().withUser(user.getId()).build(); when(projectService.getLeadPartners(activeProject.getId())).thenReturn(singletonList(leadPartnerProjectUserResource)); assertTrue(rules.userCanMarkSpendProfileIncomplete(ProjectCompositeId.id(activeProject.getId()), user)); verify(projectService).getLeadPartners(activeProject.getId()); }
SetupSectionsPermissionRules { @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") public boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user) { OrganisationResource organisation = organisationRestService.getByUserAndProjectId(user.getId(), projectOrganisationCompositeId.getProjectId()).getSuccess(); return !organisation.getId().equals(projectOrganisationCompositeId.getOrganisationId()); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void userCannotMarkOwnOrganisationAsIncomplete() { long userId = 1L; long organisationId = 2L; long projectId = 3L; UserResource userResource = newUserResource().withId(userId).build(); OrganisationResource organisationResource = newOrganisationResource().withId(organisationId).build(); when(organisationRestService.getByUserAndProjectId(userId, projectId)).thenReturn(restSuccess(organisationResource)); assertFalse(rules.userCannotMarkOwnSpendProfileIncomplete(new ProjectOrganisationCompositeId(projectId, organisationId), userResource)); verify(organisationRestService).getByUserAndProjectId(userId, projectId); } @Test public void userCanMarkOtherOrganisationAsIncomplete() { long userId = 1L; long organisationId = 2L; long otherOrganisationId = 3L; long projectId = 4L; UserResource userResource = newUserResource().withId(userId).build(); OrganisationResource organisationResource = newOrganisationResource().withId(otherOrganisationId).build(); when(organisationRestService.getByUserAndProjectId(userId, projectId)).thenReturn(restSuccess(organisationResource)); assertTrue(rules.userCannotMarkOwnSpendProfileIncomplete(new ProjectOrganisationCompositeId(projectId, organisationId), userResource)); verify(organisationRestService).getByUserAndProjectId(userId, projectId); }
SetupSectionsPermissionRules { @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") public boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user) { return !isMonitoringOfficerOnProject(projectCompositeId.id(), user.getId()) && doSectionCheck(projectCompositeId.id(), user, SetupSectionAccessibilityHelper::canAccessFinanceChecksSection); } @PermissionRule(value = "ACCESS_PROJECT_TEAM_STATUS", description = "A partner can access the Project Team Status page when the project is in a correct state to do so") boolean partnerCanAccessProjectTeamStatus(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_DETAILS_SECTION", description = "A partner can access the Project Details section when their Companies House data is complete or not required") boolean partnerCanAccessProjectDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_TEAM_SECTION", description = "A partner can access the Project Team section when their Companies House data is complete or not required") boolean partnerCanAccessProjectTeamSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CONTACT_PAGE", description = "A partner can access the Finance Contact " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean partnerCanAccessFinanceContactPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PARTNER_PROJECT_LOCATION_PAGE", description = "A partner can access the partner project location " + "page when their Companies House data is complete or not required, and the Monitoring Officer has not yet been assigned") boolean partnerCanAccessProjectLocationPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_MANAGER_PAGE", description = "A lead can access the Project Manager " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectManagerPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_PROJECT_ADDRESS_PAGE", description = "A lead can access the Project Address " + "page when their Companies House data is complete or not required, and the Grant Offer Letter has not yet been generated") boolean leadCanAccessProjectAddressPage(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_MONITORING_OFFICER_SECTION", description = "A partner can access the Monitoring Officer " + "section when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessMonitoringOfficerSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_BANK_DETAILS_SECTION", description = "A partner can access the Bank Details " + "section when their Companies House details are complete or not required, and they have a Finance Contact " + "available for their Organisation") boolean partnerCanAccessBankDetailsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_FINANCE_CHECKS_SECTION_EXTERNAL", description = "A partner can access the finance details " + " when their Companies House details are complete or not required, and the Project Details have been submitted") boolean partnerCanAccessFinanceChecksSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SPEND_PROFILE_SECTION", description = "A partner can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_TOTAL_SPEND_PROFILE_SECTION", description = "Only the project manager can access the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean projectManagerCanAccessSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "SUBMIT_SPEND_PROFILE_SECTION", description = "A partner can attempt to submit the Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or queried") boolean partnerCanSubmitSpendProfileSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_SPEND_PROFILE_SECTION", description = "A partner can edit their own Spend Profile " + "section when their Companies House details are complete or not required, the Project Details have been submitted, " + "and the Organisation's Bank Details have been approved or not required") boolean partnerCanEditSpendProfileSection(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); @PermissionRule(value = "ACCESS_DOCUMENTS_SECTION", description = "A lead can access Documents section. A partner can access Documents " + "section if their Companies House information is unnecessary or complete") boolean canAccessDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "EDIT_DOCUMENTS_SECTION", description = "A project manager can edit Documents section") boolean projectManagerCanEditDocumentsSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_GRANT_OFFER_LETTER_SECTION", description = "A lead partner can access the Grant Offer Letter " + "section when all other sections are complete and a Grant Offer Letter has been generated by the internal team") boolean partnerCanAccessGrantOfferLetterSection(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "ACCESS_SIGNED_GRANT_OFFER_LETTER", description = "A lead partner can view and download signed grant offer letter document") boolean leadPartnerAccessToSignedGrantOfferLetter(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "MARK_SPEND_PROFILE_INCOMPLETE", description = "All lead partners can mark partners spend profiles as incomplete") boolean userCanMarkSpendProfileIncomplete(ProjectCompositeId projectCompositeId, UserResource user); @PermissionRule(value = "IS_NOT_FROM_OWN_ORGANISATION", description = "A lead partner cannot mark their own spend profiles as incomplete") boolean userCannotMarkOwnSpendProfileIncomplete(ProjectOrganisationCompositeId projectOrganisationCompositeId, UserResource user); }
@Test public void partnerAccess() { long organisationId = 234L; UserResource user = newUserResource().withRolesGlobal(singletonList(PARTNER)).build(); BaseIntegrationTest.setLoggedInUser(user); OrganisationResource o = newOrganisationResource().withId(organisationId).build(); ProjectPartnerStatusResource partnerStatus = newProjectPartnerStatusResource().withProjectDetailsStatus(ProjectActivityStates.COMPLETE).withOrganisationId(organisationId).withOrganisationType(OrganisationTypeEnum.valueOf(BUSINESS.toString())).build(); List<ProjectUserResource> pu = newProjectUserResource().withProject(activeProject.getId()).withOrganisation(o.getId()).withUser(user.getId()).build(1); pu.get(0).setRoleName(PARTNER.getName()); ProjectTeamStatusResource teamStatus = newProjectTeamStatusResource().withPartnerStatuses(singletonList(partnerStatus)).build(); when(projectService.getById(activeProject.getId())).thenReturn(activeProject); when(projectService.getOrganisationIdFromUser(activeProject.getId(), user)).thenReturn(organisationId); when(statusService.getProjectTeamStatus(activeProject.getId(), Optional.of(user.getId()))).thenReturn(teamStatus); when(accessor.canAccessFinanceChecksSection(any())).thenReturn(ACCESSIBLE); assertTrue(rules.partnerCanAccessFinanceChecksSection(ProjectCompositeId.id(activeProject.getId()), user)); verify(accessor).canAccessFinanceChecksSection(any()); } @Test public void partnerNoAccess() { long organisationId = 234L; UserResource user = newUserResource().withRolesGlobal(singletonList(PARTNER)).build(); BaseIntegrationTest.setLoggedInUser(user); OrganisationResource o = newOrganisationResource().withId(organisationId).build(); ProjectPartnerStatusResource partnerStatus = newProjectPartnerStatusResource().withProjectDetailsStatus(ProjectActivityStates.COMPLETE).withOrganisationId(organisationId).withOrganisationType(OrganisationTypeEnum.valueOf(BUSINESS.toString())).build(); List<ProjectUserResource> pu = newProjectUserResource().withProject(activeProject.getId()).withOrganisation(o.getId()).withUser(user.getId()).build(1); pu.get(0).setRoleName(PARTNER.getName()); when(projectService.getById(activeProject.getId())).thenReturn(activeProject); ProjectTeamStatusResource teamStatus = newProjectTeamStatusResource().withPartnerStatuses(singletonList(partnerStatus)).build(); when(projectService.getProjectUsersForProject(activeProject.getId())).thenReturn(pu); when(statusService.getProjectTeamStatus(activeProject.getId(), Optional.of(user.getId()))).thenReturn(teamStatus); when(accessor.canAccessFinanceChecksSection(any())).thenReturn(NOT_ACCESSIBLE); when(projectService.getOrganisationIdFromUser(activeProject.getId(), user)).thenReturn(organisationId); assertFalse(rules.partnerCanAccessFinanceChecksSection(ProjectCompositeId.id(activeProject.getId()), user)); } @Test public void financeContactAccess() { long organisationId = 234L; UserResource user = newUserResource().withRolesGlobal(singletonList(FINANCE_CONTACT)).build(); BaseIntegrationTest.setLoggedInUser(user); OrganisationResource o = newOrganisationResource().withId(organisationId).build(); ProjectPartnerStatusResource partnerStatus = newProjectPartnerStatusResource().withProjectDetailsStatus(ProjectActivityStates.COMPLETE).withOrganisationId(organisationId).withOrganisationType(OrganisationTypeEnum.valueOf(BUSINESS.toString())).build(); List<ProjectUserResource> pu = newProjectUserResource().withProject(activeProject.getId()).withOrganisation(o.getId()).withUser(user.getId()).build(2); pu.get(0).setRoleName(PARTNER.getName()); pu.get(1).setRoleName(FINANCE_CONTACT.getName()); ProjectTeamStatusResource teamStatus = newProjectTeamStatusResource().withPartnerStatuses(singletonList(partnerStatus)).build(); when(projectService.getById(activeProject.getId())).thenReturn(activeProject); when(projectService.getOrganisationIdFromUser(activeProject.getId(), user)).thenReturn(organisationId); when(statusService.getProjectTeamStatus(activeProject.getId(), Optional.of(user.getId()))).thenReturn(teamStatus); when(accessor.canAccessFinanceChecksSection(any())).thenReturn(ACCESSIBLE); assertTrue(rules.partnerCanAccessFinanceChecksSection(ProjectCompositeId.id(activeProject.getId()), user)); verify(projectService, times(2)).getById(activeProject.getId()); verify(projectService).getOrganisationIdFromUser(activeProject.getId(), user); verify(statusService).getProjectTeamStatus(activeProject.getId(), Optional.of(user.getId())); }
SetupSectionAccessibilityHelper { public SectionAccess canEditSpendProfileSection(OrganisationResource userOrganisation, Long organisationIdFromUrl) { if (setupProgressChecker.isOfflineOrWithdrawn()) { return NOT_ACCESSIBLE; } if (canAccessSpendProfileSection(userOrganisation) == NOT_ACCESSIBLE) { return NOT_ACCESSIBLE; } else if (isFromOwnOrganisation(userOrganisation, organisationIdFromUrl)) { return ACCESSIBLE; } else { return fail("Unable to edit Spend Profile section as user does not belong to this organisation"); } } SetupSectionAccessibilityHelper(ProjectTeamStatusResource projectTeamStatus); SectionAccess canAccessCompaniesHouseSection(OrganisationResource organisation); SectionAccess canAccessProjectDetailsSection(OrganisationResource organisation); SectionAccess canAccessProjectTeamSection(OrganisationResource organisation); SectionAccess canAccessFinanceContactPage(OrganisationResource organisation); SectionAccess canAccessPartnerProjectLocationPage(OrganisationResource organisation, boolean partnerProjectLocationRequired); boolean isMonitoringOfficerAssigned(); SectionAccess leadCanAccessProjectManagerPage(OrganisationResource organisation); SectionAccess leadCanAccessProjectAddressPage(OrganisationResource organisation); boolean isGrantOfferLetterGenerated(); SectionAccess canAccessMonitoringOfficerSection(OrganisationResource organisation, boolean partnerProjectLocationRequired); SectionAccess canAccessBankDetailsSection(OrganisationResource organisation); SectionAccess canAccessFinanceChecksSection(OrganisationResource organisation); SectionAccess canAccessSpendProfileSection(OrganisationResource organisation); SectionAccess canEditSpendProfileSection(OrganisationResource userOrganisation, Long organisationIdFromUrl); SectionAccess canAccessDocumentsSection(OrganisationResource organisation); SectionAccess canAccessGrantOfferLetterSection(OrganisationResource organisation); SectionAccess canAccessProjectSetupCompleteSection(); boolean isSpendProfileGenerated(); boolean isFinanceContactSubmitted(OrganisationResource organisationResource); boolean isPartnerProjectLocationSubmitted(OrganisationResource organisationResource); }
@Test public void canEditSpendProfileSectionWhenCompaniesHouseDetailsNotComplete() { whenCompaniesHouseDetailsNotComplete((helper, organisation) -> helper.canEditSpendProfileSection(organisation, organisation.getId())); } @Test public void canEditSpendProfileSectionWhenProjectDetailsNotSubmitted() { whenProjectDetailsNotSubmitted((helper, organisation) -> helper.canEditSpendProfileSection(organisation, organisation.getId())); } @Test public void canEditSpendProfileSectionWhenBankDetailsNotApproved() { whenBankDetailsNotApproved((helper, organisation) -> helper.canEditSpendProfileSection(organisation, organisation.getId())); } @Test public void canEditSpendProfileSectionWhenSpendProfileNotGenerated() { whenSpendProfileNotGenerated((helper, organisation) -> helper.canEditSpendProfileSection(organisation, organisation.getId())); } @Test public void canEditSpendProfileSectionWhenUserNotFromCurrentOrganisation() { whenSpendProfileGeneratedAndNotAccessible((helper, organisation) -> helper.canEditSpendProfileSection(organisation, 22L)); } @Test public void canEditSpendProfileSectionWhenUserFromCurrentOrganisation() { whenSpendProfileGeneratedAndAccessible((helper, organisation) -> helper.canEditSpendProfileSection(organisation, organisation.getId())); }
SetupSectionAccessibilityHelper { public SectionAccess canAccessBankDetailsSection(OrganisationResource organisation) { if (organisation.isInternational()) { return NOT_ACCESSIBLE; } if (setupProgressChecker.isOfflineOrWithdrawn()) { return NOT_ACCESSIBLE; } if (!isCompaniesHouseSectionIsUnnecessaryOrComplete(organisation, "Unable to access Bank Details section until Companies House information is complete")) { return NOT_ACCESSIBLE; } if(!setupProgressChecker.isOrganisationRequiringFunding(organisation)){ return NOT_ACCESSIBLE; } if (!setupProgressChecker.isFinanceContactSubmitted(organisation)) { return fail("Unable to access Bank Details section until this Partner Organisation has submitted " + "its Finance Contact"); } return ACCESSIBLE; } SetupSectionAccessibilityHelper(ProjectTeamStatusResource projectTeamStatus); SectionAccess canAccessCompaniesHouseSection(OrganisationResource organisation); SectionAccess canAccessProjectDetailsSection(OrganisationResource organisation); SectionAccess canAccessProjectTeamSection(OrganisationResource organisation); SectionAccess canAccessFinanceContactPage(OrganisationResource organisation); SectionAccess canAccessPartnerProjectLocationPage(OrganisationResource organisation, boolean partnerProjectLocationRequired); boolean isMonitoringOfficerAssigned(); SectionAccess leadCanAccessProjectManagerPage(OrganisationResource organisation); SectionAccess leadCanAccessProjectAddressPage(OrganisationResource organisation); boolean isGrantOfferLetterGenerated(); SectionAccess canAccessMonitoringOfficerSection(OrganisationResource organisation, boolean partnerProjectLocationRequired); SectionAccess canAccessBankDetailsSection(OrganisationResource organisation); SectionAccess canAccessFinanceChecksSection(OrganisationResource organisation); SectionAccess canAccessSpendProfileSection(OrganisationResource organisation); SectionAccess canEditSpendProfileSection(OrganisationResource userOrganisation, Long organisationIdFromUrl); SectionAccess canAccessDocumentsSection(OrganisationResource organisation); SectionAccess canAccessGrantOfferLetterSection(OrganisationResource organisation); SectionAccess canAccessProjectSetupCompleteSection(); boolean isSpendProfileGenerated(); boolean isFinanceContactSubmitted(OrganisationResource organisationResource); boolean isPartnerProjectLocationSubmitted(OrganisationResource organisationResource); }
@Test public void canAccessBankDetailsSection() { when(setupProgressChecker.isOfflineOrWithdrawn()).thenReturn(false); when(setupProgressChecker.isCompaniesHouseDetailsComplete(organisation)).thenReturn(true); when(setupProgressChecker.isOrganisationRequiringFunding(organisation)).thenReturn(true); when(setupProgressChecker.isFinanceContactSubmitted(organisation)).thenReturn(true); SectionAccess access = helper.canAccessBankDetailsSection(organisation); assertEquals(SectionAccess.ACCESSIBLE, access); }
SetupStatusViewModelPopulator extends AsyncAdaptor { public SetupStatusViewModel populateViewModel(long projectId, UserResource loggedInUser) { ProjectResource project = projectService.getById(projectId); boolean monitoringOfficer = monitoringOfficerService.isMonitoringOfficerOnProject(projectId, loggedInUser.getId()).getSuccess(); CompetitionResource competition = competitionRestService.getCompetitionById(project.getCompetition()).getSuccess(); RestResult<OrganisationResource> organisationResult = projectRestService.getOrganisationByProjectAndUser(project.getId(), loggedInUser.getId()); ProjectTeamStatusResource teamStatus = statusService.getProjectTeamStatus(project.getId(), Optional.of(loggedInUser.getId())); CompletableFuture<ProjectTeamStatusResource> teamStatusRequest = async(() -> statusService.getProjectTeamStatus(project.getId(), Optional.empty())); CompletableFuture<OrganisationResource> organisationRequest = async(() -> monitoringOfficer ? projectService.getLeadOrganisation(project.getId()) : projectRestService.getOrganisationByProjectAndUser(project.getId(), loggedInUser.getId()).getSuccess()); List<SetupStatusStageViewModel> stages = competition.getProjectSetupStages().stream() .filter(stage -> (ProjectSetupStage.BANK_DETAILS != stage) || showBankDetails(organisationResult, teamStatus)) .map(stage -> toStageViewModel(stage, project, competition, loggedInUser, monitoringOfficer, teamStatusRequest, organisationRequest)) .collect(toList()); boolean isInvestorPartnership = FundingType.INVESTOR_PARTNERSHIPS == competition.getFundingType(); RestResult<CompetitionPostAwardServiceResource> competitionPostAwardServiceResource = competitionSetupPostAwardServiceRestService.getPostAwardService(project.getCompetition()); boolean isProjectManager = projectService.isProjectManager(loggedInUser.getId(), projectId); boolean isProjectFinanceContact = projectService.isProjectFinanceContact(loggedInUser.getId(), projectId); return new SetupStatusViewModel( project, monitoringOfficer, stages, competition.isLoan(), showApplicationSummaryLink(project, loggedInUser, monitoringOfficer), isInvestorPartnership, isProjectManager, isProjectFinanceContact, competitionPostAwardServiceResource.getSuccess().getPostAwardService(), navigationUtils.getLiveProjectsLandingPageUrl()); } SetupStatusViewModel populateViewModel(long projectId, UserResource loggedInUser); boolean checkLeadPartnerProjectDetailsProcessCompleted(ProjectTeamStatusResource teamStatus); }
@Test public void viewProjectSetupStatusWithGOLApproved() { ProjectTeamStatusResource teamStatus = newProjectTeamStatusResource(). withProjectLeadStatus(newProjectPartnerStatusResource(). withProjectDetailsStatus(COMPLETE). withProjectTeamStatus(COMPLETE). withBankDetailsStatus(COMPLETE). withFinanceChecksStatus(COMPLETE). withSpendProfileStatus(COMPLETE). withGrantOfferStatus(COMPLETE). withProjectSetupCompleteStatus(NOT_REQUIRED). withOrganisationId(organisationResource.getId()). withIsLeadPartner(true). build()). withPartnerStatuses(newProjectPartnerStatusResource(). withFinanceChecksStatus(COMPLETE). withBankDetailsStatus(COMPLETE). withSpendProfileStatus(COMPLETE). withProjectDetailsStatus(COMPLETE). build(1)) .withProjectState(LIVE). build(); setupLookupProjectDetailsExpectations(monitoringOfficerFoundResult, bankDetailsFoundResult, teamStatus); SetupStatusViewModel viewModel = populator.populateViewModel(project.getId(), loggedInUser); assertStandardViewModelValuesCorrect(viewModel, monitoringOfficerExpected); assertStageStatus(viewModel, PROJECT_DETAILS, TICK); assertStageStatus(viewModel, ProjectSetupStage.MONITORING_OFFICER, TICK); assertStageStatus(viewModel, BANK_DETAILS, TICK); assertStageStatus(viewModel, FINANCE_CHECKS, TICK); assertStageStatus(viewModel, SPEND_PROFILE, TICK); assertStageStatus(viewModel, GRANT_OFFER_LETTER, TICK); }
ProjectManagerController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_MANAGER_PAGE')") @PostMapping(value = "/{projectId}/team/project-manager") public String updateProjectManager(@PathVariable("projectId") final long projectId, Model model, @Valid @ModelAttribute("form") ProjectManagerForm projectManagerForm, @SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler, UserResource loggedInUser) { Supplier<String> failureView = () -> doViewProjectManager(model, projectId, loggedInUser); return validationHandler.failNowOrSucceedWith(failureView, () -> { ServiceResult<Void> updateResult = projectDetailsService.updateProjectManager(projectId, projectManagerForm.getProjectManager()); return validationHandler.addAnyErrors(updateResult, toField("projectManager")). failNowOrSucceedWith(failureView, () -> redirectToProjectTeamPage(projectId)); }); } ProjectManagerController( ProjectService projectService, ProjectDetailsService projectDetailsService ); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_MANAGER_PAGE')") @GetMapping("/{projectId}/team/project-manager") String viewProjectTeam(@PathVariable("projectId") final long projectId, Model model, @ModelAttribute(name = "form", binding = false) ProjectManagerForm projectManagerForm, UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_MANAGER_PAGE')") @PostMapping(value = "/{projectId}/team/project-manager") String updateProjectManager(@PathVariable("projectId") final long projectId, Model model, @Valid @ModelAttribute("form") ProjectManagerForm projectManagerForm, @SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler, UserResource loggedInUser); }
@Test public void updateProjectManager() throws Exception { long projectId = 123L; long projectManagerUserId = 456L; when(projectDetailsService.updateProjectManager(projectId, projectManagerUserId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{id}/team/project-manager", projectId) .param("projectManager", String.valueOf(projectManagerUserId))) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/project/" + projectId + "/team")); verify(projectDetailsService).updateProjectManager(projectId, projectManagerUserId); }
FinanceContactController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CONTACT_PAGE')") @PostMapping(value = "/{projectId}/team/finance-contact/organisation/{organisationId}") public String updateFinanceContact(@PathVariable("projectId") final long projectId, @PathVariable("organisationId") final long organisationId, Model model, @Valid @ModelAttribute("form") FinanceContactForm financeContactForm, @SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler, UserResource loggedInUser) { Supplier<String> failureView = () -> doViewFinanceContact(model, projectId, organisationId, loggedInUser, financeContactForm); return validationHandler.failNowOrSucceedWith(failureView, () -> { ServiceResult<Void> updateResult = projectDetailsService.updateFinanceContact(new ProjectOrganisationCompositeId(projectId, organisationId), financeContactForm.getFinanceContact()); return validationHandler.addAnyErrors(updateResult, toField("financeContact")). failNowOrSucceedWith(failureView, () -> redirectToProjectTeamPage(projectId)); }); } FinanceContactController( ProjectService projectService, ProjectDetailsService projectDetailsService ); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CONTACT_PAGE')") @GetMapping("/{projectId}/team/finance-contact/organisation/{organisationId}") String viewFinanceContact(@PathVariable("projectId") final long projectId, @PathVariable("organisationId") final long organisationId, Model model, @ModelAttribute(name = "form", binding = false) FinanceContactForm financeContactForm, UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_FINANCE_CONTACT_PAGE')") @PostMapping(value = "/{projectId}/team/finance-contact/organisation/{organisationId}") String updateFinanceContact(@PathVariable("projectId") final long projectId, @PathVariable("organisationId") final long organisationId, Model model, @Valid @ModelAttribute("form") FinanceContactForm financeContactForm, @SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler, UserResource loggedInUser); }
@Test public void updateFinanceContact() throws Exception { long projectId = 123L; long financeContactUserId = 456L; long organisationId = 789L; ProjectOrganisationCompositeId composite = new ProjectOrganisationCompositeId(projectId, organisationId); when(projectDetailsService.updateFinanceContact(composite, financeContactUserId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/project/{projectId}/team/finance-contact/organisation/{organisationId}", projectId, organisationId) .param("financeContact", String.valueOf(financeContactUserId))) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/project/" + projectId + "/team")); verify(projectDetailsService).updateFinanceContact(composite, financeContactUserId); }
FileFunctions { public static final Path pathElementsToPath(List<String> pathElements) { return pathElementsToFile(pathElements).toPath(); } private FileFunctions(); static final String pathElementsToPathString(List<String> pathElements); static final List<String> pathStringToPathElements(final String pathString); static final String pathElementsToAbsolutePathString(List<String> pathElements, String absolutePathPrefix); static final List<String> pathElementsToAbsolutePathElements(List<String> pathElements, String absolutePathPrefix); static final File pathElementsToFile(List<String> pathElements); static final Path pathElementsToPath(List<String> pathElements); }
@Test public void testPathElementsToPath() { assertEquals("path" + separator + "to" + separator + "file", FileFunctions.pathElementsToPath(asList("path", "to", "file")).toString()); } @Test public void testPathElementsToPathWithLeadingSeparator() { assertEquals(separator + "path" + separator + "to" + separator + "file", FileFunctions.pathElementsToPath(asList(separator + "path", "to", "file")).toString()); } @Test public void testPathElementsToPathWithEmptyStringList() { assertEquals("", FileFunctions.pathElementsToPath(asList()).toString()); } @Test public void testPathElementsToPathWithNullStringList() { assertEquals("", FileFunctions.pathElementsToPath(null).toString()); } @Test public void testPathElementsToPathWithNullStringElements() { assertEquals("path" + separator + "null" + separator + "file", FileFunctions.pathElementsToPath(asList("path", null, "file")).toString()); }
ProjectTeamController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @GetMapping("/{projectId}/team") public String viewProjectTeam(@ModelAttribute(value = "form", binding = false) ProjectTeamForm form, BindingResult bindingResult, @PathVariable("projectId") final long projectId, Model model, UserResource loggedInUser) { model.addAttribute("model", projectTeamPopulator.populate(projectId, loggedInUser)); return "projectteam/project-team"; } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @GetMapping("/{projectId}/team") String viewProjectTeam(@ModelAttribute(value = "form", binding = false) ProjectTeamForm form, BindingResult bindingResult, @PathVariable("projectId") final long projectId, Model model, UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "remove-team-member") String removeUser(@PathVariable("projectId") final long projectId, @RequestParam("remove-team-member") final long userId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "remove-invite") String removeInvite(@PathVariable("projectId") final long projectId, @RequestParam("remove-invite") final long inviteId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "resend-invite") String resendInvite(@PathVariable("projectId") final long projectId, @RequestParam("resend-invite") final long inviteId, HttpServletResponse response); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "add-team-member") String openAddTeamMemberForm(@ModelAttribute(value = "form") ProjectTeamForm form, BindingResult bindingResult, @PathVariable("projectId") final long projectId, @RequestParam("add-team-member") final long organisationId, Model model, UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "close-add-team-member-form") String closeAddTeamMemberForm(@PathVariable("projectId") final long projectId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "invite-to-project") String inviteToProject(@Valid @ModelAttribute("form") ProjectTeamForm form, BindingResult bindingResult, ValidationHandler validationHandler, @PathVariable("projectId") final long projectId, @RequestParam("invite-to-project") final long organisationId, Model model, UserResource loggedInUser); }
@Test public void viewProjectTeam() throws Exception { UserResource loggedInUser = newUserResource().build(); setLoggedInUser(loggedInUser); long projectId = 999L; ProjectTeamViewModel expected = mock(ProjectTeamViewModel.class); when(populator.populate(projectId, loggedInUser)).thenReturn(expected); MvcResult result = mockMvc.perform(get("/project/{id}/team", projectId)) .andExpect(status().isOk()) .andExpect(view().name("projectteam/project-team")) .andExpect(model().attributeDoesNotExist("internalUserView")) .andReturn(); ProjectTeamViewModel actual = (ProjectTeamViewModel) result.getModelAndView().getModel().get("model"); assertEquals(expected, actual); }
ProjectTeamController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "add-team-member") public String openAddTeamMemberForm(@ModelAttribute(value = "form") ProjectTeamForm form, BindingResult bindingResult, @PathVariable("projectId") final long projectId, @RequestParam("add-team-member") final long organisationId, Model model, UserResource loggedInUser) { model.addAttribute("model", projectTeamPopulator.populate(projectId, loggedInUser) .openAddTeamMemberForm(organisationId)); return "projectteam/project-team"; } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @GetMapping("/{projectId}/team") String viewProjectTeam(@ModelAttribute(value = "form", binding = false) ProjectTeamForm form, BindingResult bindingResult, @PathVariable("projectId") final long projectId, Model model, UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "remove-team-member") String removeUser(@PathVariable("projectId") final long projectId, @RequestParam("remove-team-member") final long userId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "remove-invite") String removeInvite(@PathVariable("projectId") final long projectId, @RequestParam("remove-invite") final long inviteId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "resend-invite") String resendInvite(@PathVariable("projectId") final long projectId, @RequestParam("resend-invite") final long inviteId, HttpServletResponse response); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "add-team-member") String openAddTeamMemberForm(@ModelAttribute(value = "form") ProjectTeamForm form, BindingResult bindingResult, @PathVariable("projectId") final long projectId, @RequestParam("add-team-member") final long organisationId, Model model, UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "close-add-team-member-form") String closeAddTeamMemberForm(@PathVariable("projectId") final long projectId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "invite-to-project") String inviteToProject(@Valid @ModelAttribute("form") ProjectTeamForm form, BindingResult bindingResult, ValidationHandler validationHandler, @PathVariable("projectId") final long projectId, @RequestParam("invite-to-project") final long organisationId, Model model, UserResource loggedInUser); }
@Test public void openAddTeamMemberForm() throws Exception { UserResource loggedInUser = newUserResource().build(); setLoggedInUser(loggedInUser); long projectId = 999L; long organisationId = 3L; ProjectTeamViewModel expected = mock(ProjectTeamViewModel.class); when(populator.populate(projectId, loggedInUser)).thenReturn(expected); when(expected.openAddTeamMemberForm(organisationId)).thenReturn(expected); MvcResult result = mockMvc.perform(post("/project/{id}/team", projectId) .param("add-team-member", String.valueOf(organisationId))) .andExpect(status().isOk()) .andExpect(view().name("projectteam/project-team")) .andExpect(model().attributeDoesNotExist("internalUserView")) .andReturn(); ProjectTeamViewModel actual = (ProjectTeamViewModel) result.getModelAndView().getModel().get("model"); assertEquals(expected, actual); verify(expected).openAddTeamMemberForm(organisationId); }
ProjectTeamController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "close-add-team-member-form") public String closeAddTeamMemberForm(@PathVariable("projectId") final long projectId) { return format("redirect:/project/%d/team", projectId); } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @GetMapping("/{projectId}/team") String viewProjectTeam(@ModelAttribute(value = "form", binding = false) ProjectTeamForm form, BindingResult bindingResult, @PathVariable("projectId") final long projectId, Model model, UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "remove-team-member") String removeUser(@PathVariable("projectId") final long projectId, @RequestParam("remove-team-member") final long userId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "remove-invite") String removeInvite(@PathVariable("projectId") final long projectId, @RequestParam("remove-invite") final long inviteId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "resend-invite") String resendInvite(@PathVariable("projectId") final long projectId, @RequestParam("resend-invite") final long inviteId, HttpServletResponse response); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "add-team-member") String openAddTeamMemberForm(@ModelAttribute(value = "form") ProjectTeamForm form, BindingResult bindingResult, @PathVariable("projectId") final long projectId, @RequestParam("add-team-member") final long organisationId, Model model, UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "close-add-team-member-form") String closeAddTeamMemberForm(@PathVariable("projectId") final long projectId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "invite-to-project") String inviteToProject(@Valid @ModelAttribute("form") ProjectTeamForm form, BindingResult bindingResult, ValidationHandler validationHandler, @PathVariable("projectId") final long projectId, @RequestParam("invite-to-project") final long organisationId, Model model, UserResource loggedInUser); }
@Test public void closeAddTeamMemberForm() throws Exception { long projectId = 999L; mockMvc.perform(post("/project/{id}/team", projectId) .param("close-add-team-member-form", "")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(String.format("/project/%d/team", projectId))) .andReturn(); }
ProjectTeamController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "invite-to-project") public String inviteToProject(@Valid @ModelAttribute("form") ProjectTeamForm form, BindingResult bindingResult, ValidationHandler validationHandler, @PathVariable("projectId") final long projectId, @RequestParam("invite-to-project") final long organisationId, Model model, UserResource loggedInUser) { Supplier<String> failureView = () -> { model.addAttribute("model", projectTeamPopulator.populate(projectId, loggedInUser) .openAddTeamMemberForm(organisationId)); return "projectteam/project-team"; }; Supplier<String> successView = () -> format("redirect:/project/%d/team", projectId); return projectInviteHelper.sendInvite(form.getName(), form.getEmail(), loggedInUser, validationHandler, failureView, successView, projectId, organisationId); } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @GetMapping("/{projectId}/team") String viewProjectTeam(@ModelAttribute(value = "form", binding = false) ProjectTeamForm form, BindingResult bindingResult, @PathVariable("projectId") final long projectId, Model model, UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "remove-team-member") String removeUser(@PathVariable("projectId") final long projectId, @RequestParam("remove-team-member") final long userId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "remove-invite") String removeInvite(@PathVariable("projectId") final long projectId, @RequestParam("remove-invite") final long inviteId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "resend-invite") String resendInvite(@PathVariable("projectId") final long projectId, @RequestParam("resend-invite") final long inviteId, HttpServletResponse response); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "add-team-member") String openAddTeamMemberForm(@ModelAttribute(value = "form") ProjectTeamForm form, BindingResult bindingResult, @PathVariable("projectId") final long projectId, @RequestParam("add-team-member") final long organisationId, Model model, UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "close-add-team-member-form") String closeAddTeamMemberForm(@PathVariable("projectId") final long projectId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "invite-to-project") String inviteToProject(@Valid @ModelAttribute("form") ProjectTeamForm form, BindingResult bindingResult, ValidationHandler validationHandler, @PathVariable("projectId") final long projectId, @RequestParam("invite-to-project") final long organisationId, Model model, UserResource loggedInUser); }
@Test public void inviteToProject() throws Exception { UserResource loggedInUser = newUserResource().build(); setLoggedInUser(loggedInUser); long projectId = 999L; ProjectTeamViewModel expected = mock(ProjectTeamViewModel.class); String email = "[email protected]"; String userName = "Some One"; ProjectResource projectResource = newProjectResource() .withId(projectId) .withApplication(5L) .build(); OrganisationResource leadOrganisation = newOrganisationResource().build(); OrganisationResource organisationResource = newOrganisationResource().build(); ProjectUserInviteResource projectUserInviteResource = new ProjectUserInviteResource(userName, email, projectId); projectUserInviteResource.setOrganisation(organisationResource.getId()); projectUserInviteResource.setApplicationId(projectResource.getApplication()); projectUserInviteResource.setLeadOrganisationId(leadOrganisation.getId()); projectUserInviteResource.setOrganisationName(organisationResource.getName()); when(expected.openAddTeamMemberForm(organisationResource.getId())).thenReturn(expected); when(populator.populate(projectId, loggedInUser)).thenReturn(expected); when(projectService.getById(projectId)).thenReturn(projectResource); when(projectService.getLeadOrganisation(projectId)).thenReturn(leadOrganisation); when(organisationRestService.getOrganisationById(organisationResource.getId())).thenReturn(restSuccess(organisationResource)); when(projectInviteRestService.getInvitesByProject(projectId)).thenReturn(restSuccess(asList(projectUserInviteResource))); when(projectTeamRestService.inviteProjectMember(projectId, projectUserInviteResource)).thenReturn(restSuccess()); MvcResult result = mockMvc.perform(post("/project/{id}/team", projectId) .param("invite-to-project", String.valueOf(organisationResource.getId())) .param("name", userName) .param("email", email)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl(String.format("/project/%d/team", projectId))) .andReturn(); verify(projectTeamRestService).inviteProjectMember(projectId, projectUserInviteResource); }
ProjectTeamController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "resend-invite") public String resendInvite(@PathVariable("projectId") final long projectId, @RequestParam("resend-invite") final long inviteId, HttpServletResponse response) { projectInviteHelper.resendInvite(inviteId, projectId, (project, projectInviteResource) -> projectTeamRestService.inviteProjectMember(project, projectInviteResource).toServiceResult()); cookieFlashMessageFilter.setFlashMessage(response, "emailSent"); return "redirect:/project/" + projectId + "/team"; } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @GetMapping("/{projectId}/team") String viewProjectTeam(@ModelAttribute(value = "form", binding = false) ProjectTeamForm form, BindingResult bindingResult, @PathVariable("projectId") final long projectId, Model model, UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "remove-team-member") String removeUser(@PathVariable("projectId") final long projectId, @RequestParam("remove-team-member") final long userId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "remove-invite") String removeInvite(@PathVariable("projectId") final long projectId, @RequestParam("remove-invite") final long inviteId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "resend-invite") String resendInvite(@PathVariable("projectId") final long projectId, @RequestParam("resend-invite") final long inviteId, HttpServletResponse response); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "add-team-member") String openAddTeamMemberForm(@ModelAttribute(value = "form") ProjectTeamForm form, BindingResult bindingResult, @PathVariable("projectId") final long projectId, @RequestParam("add-team-member") final long organisationId, Model model, UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "close-add-team-member-form") String closeAddTeamMemberForm(@PathVariable("projectId") final long projectId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "invite-to-project") String inviteToProject(@Valid @ModelAttribute("form") ProjectTeamForm form, BindingResult bindingResult, ValidationHandler validationHandler, @PathVariable("projectId") final long projectId, @RequestParam("invite-to-project") final long organisationId, Model model, UserResource loggedInUser); }
@Test public void resendInvite() throws Exception { long projectId = 4L; long organisationId = 21L; long inviteId = 3L; String invitedUserName = "test"; String invitedUserEmail = "[email protected]"; OrganisationResource leadOrganisation = newOrganisationResource().withName("Lead Organisation").build(); List<ProjectUserInviteResource> existingInvites = newProjectUserInviteResource().withId(inviteId) .withProject(projectId).withName("exist test", invitedUserName) .withEmail("[email protected]", invitedUserEmail) .withOrganisation(organisationId) .withStatus(SENT) .withLeadOrganisation(leadOrganisation.getId()).build(1); when(projectInviteRestService.getInvitesByProject(projectId)).thenReturn(restSuccess(existingInvites)); when(projectTeamRestService.inviteProjectMember(projectId, existingInvites.get(0))).thenReturn(restSuccess()); mockMvc.perform(post("/project/{id}/team", projectId) .param("resend-invite", "3")) .andExpect(status().is3xxRedirection()); verify(projectTeamRestService).inviteProjectMember(projectId, existingInvites.get(0)); verify(cookieFlashMessageFilter).setFlashMessage(any(), eq("emailSent")); }
ProjectTeamController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "remove-team-member") public String removeUser(@PathVariable("projectId") final long projectId, @RequestParam("remove-team-member") final long userId) { projectTeamRestService.removeUser(projectId, userId).getSuccess(); return "redirect:/project/" + projectId + "/team"; } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @GetMapping("/{projectId}/team") String viewProjectTeam(@ModelAttribute(value = "form", binding = false) ProjectTeamForm form, BindingResult bindingResult, @PathVariable("projectId") final long projectId, Model model, UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "remove-team-member") String removeUser(@PathVariable("projectId") final long projectId, @RequestParam("remove-team-member") final long userId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "remove-invite") String removeInvite(@PathVariable("projectId") final long projectId, @RequestParam("remove-invite") final long inviteId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "resend-invite") String resendInvite(@PathVariable("projectId") final long projectId, @RequestParam("resend-invite") final long inviteId, HttpServletResponse response); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "add-team-member") String openAddTeamMemberForm(@ModelAttribute(value = "form") ProjectTeamForm form, BindingResult bindingResult, @PathVariable("projectId") final long projectId, @RequestParam("add-team-member") final long organisationId, Model model, UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "close-add-team-member-form") String closeAddTeamMemberForm(@PathVariable("projectId") final long projectId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "invite-to-project") String inviteToProject(@Valid @ModelAttribute("form") ProjectTeamForm form, BindingResult bindingResult, ValidationHandler validationHandler, @PathVariable("projectId") final long projectId, @RequestParam("invite-to-project") final long organisationId, Model model, UserResource loggedInUser); }
@Test public void removeUser() throws Exception { UserResource loggedInUser = newUserResource().build(); setLoggedInUser(loggedInUser); long userId = 444L; long projectId = 555L; when(projectTeamRestService.removeUser(projectId, userId)).thenReturn(restSuccess()); mockMvc.perform(post("/project/" + projectId + "/team") .param("remove-team-member", String.valueOf(userId))) .andExpect(status().is3xxRedirection()); verify(projectTeamRestService).removeUser(projectId, userId); }
ProjectTeamController { @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "remove-invite") public String removeInvite(@PathVariable("projectId") final long projectId, @RequestParam("remove-invite") final long inviteId) { projectTeamRestService.removeInvite(projectId, inviteId).getSuccess(); return "redirect:/project/" + projectId + "/team"; } @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @GetMapping("/{projectId}/team") String viewProjectTeam(@ModelAttribute(value = "form", binding = false) ProjectTeamForm form, BindingResult bindingResult, @PathVariable("projectId") final long projectId, Model model, UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "remove-team-member") String removeUser(@PathVariable("projectId") final long projectId, @RequestParam("remove-team-member") final long userId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "remove-invite") String removeInvite(@PathVariable("projectId") final long projectId, @RequestParam("remove-invite") final long inviteId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "resend-invite") String resendInvite(@PathVariable("projectId") final long projectId, @RequestParam("resend-invite") final long inviteId, HttpServletResponse response); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "add-team-member") String openAddTeamMemberForm(@ModelAttribute(value = "form") ProjectTeamForm form, BindingResult bindingResult, @PathVariable("projectId") final long projectId, @RequestParam("add-team-member") final long organisationId, Model model, UserResource loggedInUser); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "close-add-team-member-form") String closeAddTeamMemberForm(@PathVariable("projectId") final long projectId); @PreAuthorize("hasPermission(#projectId, 'org.innovateuk.ifs.project.resource.ProjectCompositeId', 'ACCESS_PROJECT_TEAM_SECTION')") @PostMapping(value = "/{projectId}/team", params = "invite-to-project") String inviteToProject(@Valid @ModelAttribute("form") ProjectTeamForm form, BindingResult bindingResult, ValidationHandler validationHandler, @PathVariable("projectId") final long projectId, @RequestParam("invite-to-project") final long organisationId, Model model, UserResource loggedInUser); }
@Test public void removeInvite() throws Exception { long inviteId = 777L; long projectId = 888L; when(projectTeamRestService.removeInvite(projectId, inviteId)).thenReturn(restSuccess()); mockMvc.perform(post("/project/" + projectId + "/team") .param("remove-invite", String.valueOf(inviteId))) .andExpect(status().is3xxRedirection()); verify(projectTeamRestService).removeInvite(projectId, inviteId); }
ProjectTeamViewModelPopulator { public ProjectTeamViewModel populate(long projectId, UserResource loggedInUser) { ProjectResource project = projectService.getById(projectId); boolean isMonitoringOfficer = monitoringOfficerRestService.isMonitoringOfficerOnProject(projectId, loggedInUser.getId()).getSuccess(); List<ProjectUserResource> projectUsers = projectService.getDisplayProjectUsersForProject(project.getId()); List<OrganisationResource> projectOrganisations = projectService.getPartnerOrganisationsForProject(projectId); OrganisationResource leadOrganisation = projectService.getLeadOrganisation(projectId); OrganisationResource loggedInUserOrg; if(isMonitoringOfficer) { loggedInUserOrg = null; } else { loggedInUserOrg = projectRestService.getOrganisationByProjectAndUser(projectId, loggedInUser.getId()).getSuccess(); } List<ProjectUserInviteResource> invitedUsers = projectInviteRestService.getInvitesByProject(projectId).getSuccess(); boolean isLead = leadOrganisation.equals(loggedInUserOrg); List<ProjectTeamOrganisationViewModel> partnerOrgModels = projectOrganisations.stream() .map(org -> mapToProjectOrganisationViewModel(projectId, projectUsers, invitedUsers, org, loggedInUser, org.equals(leadOrganisation), org.equals(loggedInUserOrg))) .sorted() .collect(toList()); ProjectTeamOrganisationViewModel loggedInUserOrgModel = getLoggedInUserOrgModel(partnerOrgModels, loggedInUserOrg, isMonitoringOfficer); ProjectTeamStatusResource teamStatus = statusService.getProjectTeamStatus(projectId, Optional.empty()); SetupSectionAccessibilityHelper statusAccessor = new SetupSectionAccessibilityHelper(teamStatus); boolean isReadOnly = statusAccessor.isGrantOfferLetterGenerated() || project.getProjectState().isComplete() || isMonitoringOfficer; return new ProjectTeamViewModel( project, partnerOrgModels, loggedInUserOrgModel, getProjectManager(project.getId()).orElse(null), isLead, loggedInUser.getId(), statusAccessor.isGrantOfferLetterGenerated(), false, isReadOnly, false, false); } ProjectTeamViewModel populate(long projectId, UserResource loggedInUser); }
@Test public void populate() { UserResource loggedInUser = newUserResource().withId(123L).build(); CompetitionResource competition = newCompetitionResource() .withName("Imaginative competition name") .build(); ProjectResource project = newProjectResource() .withCompetition(competition.getId()) .withName("Imaginative project name") .withMonitoringOfficerUser(789L) .withProjectState(SETUP) .build(); OrganisationResource leadOrg = newOrganisationResource() .withName("Imaginative organisation name") .build(); OrganisationResource partnerOne = newOrganisationResource().build(); OrganisationResource partnerTwo = newOrganisationResource().build(); List<ProjectUserResource> projectUsers = newProjectUserResource() .withUser(123L, 456L, 123L, 456L) .withOrganisation(partnerOne.getId(), partnerTwo.getId(), partnerOne.getId(), partnerTwo.getId()) .withRole(11L, 10L, 10L, 9L) .build(4); List<OrganisationResource> projectOrgs = asList(partnerOne, partnerTwo); ProjectTeamStatusResource teamStatus = newProjectTeamStatusResource(). withProjectLeadStatus(newProjectPartnerStatusResource() .withIsLeadPartner(true) .withMonitoringOfficerStatus(ProjectActivityStates.NOT_STARTED) .withSpendProfileStatus(ProjectActivityStates.PENDING) .withGrantOfferStatus(ProjectActivityStates.NOT_REQUIRED) .build()) .build(); List<ProjectUserInviteResource> invites = newProjectUserInviteResource() .withName("Mr Invite") .withOrganisation(partnerOne.getId()) .withStatus(InviteStatus.SENT) .withSentOn(ZonedDateTime.now().minusHours(2).minusDays(10)) .build(1); when(monitoringOfficerRestService.isMonitoringOfficerOnProject(project.getId(), loggedInUser.getId())).thenReturn(restSuccess(false)); when(projectRestService.getOrganisationByProjectAndUser(project.getId(), loggedInUser.getId())).thenReturn(restSuccess(partnerOne)); when(projectService.getById(project.getId())).thenReturn(project); when(projectService.getProjectUsersForProject(project.getId())).thenReturn(projectUsers); when(projectService.getPartnerOrganisationsForProject(project.getId())).thenReturn(projectOrgs); when(projectService.getLeadOrganisation(project.getId())).thenReturn(leadOrg); when(statusService.getProjectTeamStatus(project.getId(), Optional.empty())).thenReturn(teamStatus); when(projectInviteRestService.getInvitesByProject(project.getId())).thenReturn(restSuccess(invites)); ProjectTeamViewModel model = service.populate(project.getId(), loggedInUser); assertEquals(project.getCompetitionName(), model.getCompetitionName()); assertEquals(project.getCompetition(), model.getCompetitionId()); assertEquals(project.getName(), model.getProjectName()); assertEquals((long) project.getId(), model.getProjectId()); assertFalse(model.isUserLeadPartner()); assertEquals((long) loggedInUser.getId(), model.getLoggedInUserId()); assertFalse(model.isInternalUserView()); assertFalse(model.isReadOnly()); assertEquals(2, model.getPartners().size()); ProjectTeamOrganisationViewModel partnerOneViewModel = model.getPartners().stream().filter(view -> view.getId() == partnerOne.getId()).findAny().get(); assertEquals(1, partnerOneViewModel.getUsers().size()); AbstractProjectTeamRowViewModel partnerOneInvitee = partnerOneViewModel.getUsers().get(0); assertEquals((long) invites.get(0).getId(), partnerOneInvitee.getId()); assertEquals("Mr Invite (pending for 10 days)", partnerOneInvitee.getName()); assertFalse(partnerOneViewModel.isOpenAddTeamMemberForm()); model.openAddTeamMemberForm(partnerOne.getId()); assertTrue(partnerOneViewModel.isOpenAddTeamMemberForm()); assertFalse(model.isReadOnly()); }
ProjectDetailsStartDateViewModel implements BasicProjectDetailsViewModel { public boolean isKtpCompetition() { return ktpCompetition; } ProjectDetailsStartDateViewModel(ProjectResource project, CompetitionResource competitionResource); Long getApplicationId(); Long getProjectId(); String getProjectName(); LocalDate getTargetStartDate(); long getProjectDurationInMonths(); long getCompetitionId(); List<Long> getProjectUsers(); boolean isKtpCompetition(); boolean isProcurementCompetition(); }
@Test public void testKtpCompetition() { ProjectResource projectResource = ProjectResourceBuilder.newProjectResource() .withDuration(15L).build(); CompetitionResource competitionResource = CompetitionResourceBuilder.newCompetitionResource() .withFundingType(FundingType.KTP).build(); ProjectDetailsStartDateViewModel viewModel = new ProjectDetailsStartDateViewModel(projectResource, competitionResource); assertTrue(viewModel.isKtpCompetition()); }
ProjectDetailsViewModel { public String getLocationForPartnerOrganisation(Long organisationId) { return partnerOrganisations.stream() .filter(partnerOrganisation -> partnerOrganisation.getOrganisation().equals(organisationId)) .findFirst() .map(partnerOrg -> { Optional<OrganisationResource> organisationResource = organisations.stream().filter(org -> organisationId.equals(org.getId())).findFirst(); if (organisationResource.isPresent() && organisationResource.get().isInternational()) { return partnerOrg.getInternationalLocation(); } else { return partnerOrg.getPostcode(); } }) .orElse(null); } ProjectDetailsViewModel(ProjectResource project, UserResource currentUser, List<Long> usersPartnerOrganisations, List<OrganisationResource> organisations, List<PartnerOrganisationResource> partnerOrganisations, OrganisationResource leadOrganisation, boolean userIsLeadPartner, boolean spendProfileGenerated, boolean grantOfferLetterGenerated, boolean readOnlyView, CompetitionResource competitionResource); ProjectResource getProject(); UserResource getCurrentUser(); List<OrganisationResource> getOrganisations(); String getLocationForPartnerOrganisation(Long organisationId); OrganisationResource getLeadOrganisation(); void setLeadOrganisation(OrganisationResource leadOrganisation); boolean isUserLeadPartner(); boolean isUserPartnerInOrganisation(Long organisationId); boolean isReadOnly(); boolean isSpendProfileGenerated(); boolean isGrantOfferLetterGenerated(); boolean isCollaborativeProject(); boolean isProjectLive(); boolean isKtpCompetition(); boolean isProcurementCompetition(); }
@Test public void shouldShowPostcodeForLocationGivenNotInternational() { List<OrganisationResource> organisations = Collections.emptyList(); PartnerOrganisationResource partnerOrg = new PartnerOrganisationResource(); partnerOrg.setOrganisation(ORG_ID); partnerOrg.setPostcode(POSTCODE); List<PartnerOrganisationResource> partnerOrganisations = Collections.singletonList(partnerOrg); ProjectDetailsViewModel model = new ProjectDetailsViewModel(project, currentUser, usersPartnerOrganisations, organisations, partnerOrganisations, leadOrganisation, userIsLeadPartner, spendProfileGenerated, grantOfferLetterGenerated, readOnlyView, competitionResource); String result = model.getLocationForPartnerOrganisation(ORG_ID); assertEquals(POSTCODE, result); } @Test public void shouldShowInternationalLocationGivenInternational() { OrganisationResource organisationResource = new OrganisationResource(); organisationResource.setInternational(true); organisationResource.setId(ORG_ID); List<OrganisationResource> organisations = Collections.singletonList(organisationResource); PartnerOrganisationResource partnerOrg = new PartnerOrganisationResource(); partnerOrg.setOrganisation(ORG_ID); partnerOrg.setInternationalLocation(LOCATION); List<PartnerOrganisationResource> partnerOrganisations = Collections.singletonList(partnerOrg); ProjectDetailsViewModel model = new ProjectDetailsViewModel(project, currentUser, usersPartnerOrganisations, organisations, partnerOrganisations, leadOrganisation, userIsLeadPartner, spendProfileGenerated, grantOfferLetterGenerated, readOnlyView, competitionResource); String result = model.getLocationForPartnerOrganisation(ORG_ID); assertEquals(LOCATION, result); }
CompaniesHouseApiServiceImpl implements CompaniesHouseApiService { @Override public ServiceResult<OrganisationSearchResult> getOrganisationById(String id) { LOG.debug("getOrganisationById " + id); return ofNullable(restGet("company/" + id, JsonNode.class)). map(jsonNode -> serviceSuccess(companyProfileMapper(jsonNode))). orElse(serviceFailure(COMPANIES_HOUSE_NO_RESPONSE)); } @Override ServiceResult<List<OrganisationSearchResult>> searchOrganisations(String encodedSearchText); @Override ServiceResult<OrganisationSearchResult> getOrganisationById(String id); }
@Test public void searchCompany() { Map<String, Object> companyMap = companyMap(); JsonNode resultNode = new ObjectMapper().valueToTree(companyMap); ResponseEntity<JsonNode> response = new ResponseEntity<JsonNode>(resultNode, HttpStatus.OK); when(adapter.restGetEntity("baseurl/company/123", JsonNode.class)).thenReturn(response); ServiceResult<OrganisationSearchResult> result = service.getOrganisationById("123"); verify(adapter).restGetEntity("baseurl/company/123", JsonNode.class); assertTrue(result.isSuccess()); assertEquals("company name", result.getSuccess().getName()); assertEquals("1234", result.getSuccess().getOrganisationSearchId()); assertEquals("line1", result.getSuccess().getOrganisationAddress().getAddressLine1()); assertEquals("line2", result.getSuccess().getOrganisationAddress().getAddressLine2()); assertEquals("line3", result.getSuccess().getOrganisationAddress().getAddressLine3()); assertEquals("loc", result.getSuccess().getOrganisationAddress().getTown()); assertEquals("reg", result.getSuccess().getOrganisationAddress().getCounty()); assertEquals("ba1", result.getSuccess().getOrganisationAddress().getPostcode()); } @Test public void searchCompanyNulAddress() { Map<String, Object> companyMap = companyMap(); companyMap.put("registered_office_address", null); JsonNode resultNode = new ObjectMapper().valueToTree(companyMap); ResponseEntity<JsonNode> response = new ResponseEntity<JsonNode>(resultNode, HttpStatus.OK); when(adapter.restGetEntity("baseurl/company/123", JsonNode.class)).thenReturn(response); ServiceResult<OrganisationSearchResult> result = service.getOrganisationById("123"); verify(adapter).restGetEntity("baseurl/company/123", JsonNode.class); assertTrue(result.isSuccess()); assertEquals("company name", result.getSuccess().getName()); assertEquals("1234", result.getSuccess().getOrganisationSearchId()); assertNull(result.getSuccess().getOrganisationAddress().getAddressLine1()); assertNull(result.getSuccess().getOrganisationAddress().getAddressLine2()); assertNull(result.getSuccess().getOrganisationAddress().getAddressLine3()); assertNull(result.getSuccess().getOrganisationAddress().getTown()); assertNull(result.getSuccess().getOrganisationAddress().getCounty()); assertNull(result.getSuccess().getOrganisationAddress().getPostcode()); }
ProjectDetailsViewModel { public boolean isKtpCompetition() { return ktpCompetition; } ProjectDetailsViewModel(ProjectResource project, UserResource currentUser, List<Long> usersPartnerOrganisations, List<OrganisationResource> organisations, List<PartnerOrganisationResource> partnerOrganisations, OrganisationResource leadOrganisation, boolean userIsLeadPartner, boolean spendProfileGenerated, boolean grantOfferLetterGenerated, boolean readOnlyView, CompetitionResource competitionResource); ProjectResource getProject(); UserResource getCurrentUser(); List<OrganisationResource> getOrganisations(); String getLocationForPartnerOrganisation(Long organisationId); OrganisationResource getLeadOrganisation(); void setLeadOrganisation(OrganisationResource leadOrganisation); boolean isUserLeadPartner(); boolean isUserPartnerInOrganisation(Long organisationId); boolean isReadOnly(); boolean isSpendProfileGenerated(); boolean isGrantOfferLetterGenerated(); boolean isCollaborativeProject(); boolean isProjectLive(); boolean isKtpCompetition(); boolean isProcurementCompetition(); }
@Test public void testKtpCompetition() { competitionResource = CompetitionResourceBuilder.newCompetitionResource().withFundingType(FundingType.KTP).build(); ProjectDetailsViewModel viewModel = new ProjectDetailsViewModel(project, currentUser, usersPartnerOrganisations, null, null, leadOrganisation, userIsLeadPartner, spendProfileGenerated, grantOfferLetterGenerated, readOnlyView, competitionResource); assertTrue(viewModel.isKtpCompetition()); }