src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
BasePatternVoter extends AbstractBoolVoter { public void init() { if(autoTrueValue){ if(!isInverse()){ setTrueValue(pattern.length()); } else{ setTrueValue(-pattern.length()); } } } void init(); @Override void setTrueValue(int positiveVoteValue); String getPattern(); void setPattern(String pattern); boolean isInverse(); void setInverse(boolean inverse); @Override String toString(); }
@Test public void testInitWithoutPattern(){ BasePatternVoter voter = new BasePatternVoter() { @Override protected boolean boolVote(Object value) { return false; }}; voter.init(); }
ResponseContentTypeVoter extends AbstractBoolVoter { public void addAllowed(String contentType) { allowed.add(contentType); } List<String> getAllowed(); void setAllowed(List<String> allowed); void addAllowed(String contentType); List<String> getRejected(); void setRejected(List<String> rejected); void addRejected(String contentType); }
@Test public void testVotesTrueIfContentTypeIsAllowed() { voter.addAllowed("text/html"); voter.addAllowed("application/x-javascript"); voter.addAllowed("text/plain"); expect(response.getContentType()).andReturn("application/x-javascript"); doTest(true); } @Test public void testVotesFalseIfContentTypeIsNotInAllowedList() { voter.addAllowed("text/html"); voter.addAllowed("application/x-javascript"); voter.addAllowed("text/plain"); expect(response.getContentType()).andReturn("whatever"); doTest(false); } @Test public void testVotesFalseIfResponseDoesNotHaveAContentTypeSetYetEvenIfNoRejectedAreConfigured() { voter.addAllowed("text/html"); voter.addAllowed("application/x-javascript"); voter.addAllowed("text/plain"); expect(response.getContentType()).andReturn(null); doTest(false); } @Test public void testIgnoresCharsetInContentType2() { voter.addAllowed("text/html"); voter.addAllowed("application/x-javascript"); voter.addAllowed("text/plain"); expect(response.getContentType()).andReturn("image/jpeg;charset=UTF-8"); doTest(false); }
ResponseContentTypeVoter extends AbstractBoolVoter { public void addRejected(String contentType) { rejected.add(contentType); } List<String> getAllowed(); void setAllowed(List<String> allowed); void addAllowed(String contentType); List<String> getRejected(); void setRejected(List<String> rejected); void addRejected(String contentType); }
@Test public void testVotesFalseIfContentTypeIsExplicitelyRejected() { voter.addRejected("image/gif"); voter.addRejected("image/jpeg"); voter.addRejected("application/octet-stream"); expect(response.getContentType()).andReturn("image/gif"); doTest(false); } @Test public void testVotesTrueIfContentTypeIsNotRejected() { voter.addRejected("image/gif"); voter.addRejected("image/jpeg"); voter.addRejected("application/octet-stream"); expect(response.getContentType()).andReturn("text/plain"); doTest(true); } @Test public void testVotesFalseIfResponseDoesNotHaveAContentTypeSetYetEvenIfNoAllowedAreConfigured() { voter.addRejected("text/html"); voter.addRejected("application/x-javascript"); voter.addRejected("text/plain"); expect(response.getContentType()).andReturn(null); doTest(false); }
URIPatternVoter extends BasePatternVoter { @Override public void setPattern(String pattern) { super.setPattern(pattern); this.pattern = new SimpleUrlPattern(pattern); } @Override void setPattern(String pattern); }
@Test public void testVotesTrueOnMatchingWildcardPattern() { URIPatternVoter voter = new URIPatternVoter(); voter.setPattern("/foo/bar*"); assertEquals(1, voter.vote("/foo/bar/zed")); } @Test public void testVotesFalseOnNonMatchingWildcardPattern() { URIPatternVoter voter = new URIPatternVoter(); voter.setPattern("/foo/bar*"); assertEquals(0, voter.vote("/abc/xyz")); }
FreemarkerHelper { public void render(String templatePath, Object root, Writer out) throws TemplateException, IOException { render(templatePath, null, null, root, out); } FreemarkerHelper(); FreemarkerHelper(final FreemarkerConfig freemarkerConfig); static FreemarkerHelper getInstance(); void resetObjectWrapper(); void render(String templatePath, Object root, Writer out); void render(String templatePath, Locale locale, String i18nBasename, Object root, Writer out); void render(Reader template, Object root, Writer out); }
@Test public void testContextPathIsNotAddedWithNotWebContext() throws IOException, TemplateException { tplLoader.putTemplate("pouet", ":${contextPath}:"); final Context context = createStrictMock(Context.class); expect(context.getLocale()).andReturn(Locale.US); replay(context); MgnlContext.setInstance(context); final StringWriter out = new StringWriter(); try { fmHelper.render("pouet", new HashMap(), out); fail("should have failed"); } catch (InvalidReferenceException e) { assertEquals("Expression contextPath is undefined on line 1, column 4 in pouet.", e.getMessage()); } verify(context); }
FreemarkerHelper { public static FreemarkerHelper getInstance() { return Components.getSingleton(FreemarkerHelper.class); } FreemarkerHelper(); FreemarkerHelper(final FreemarkerConfig freemarkerConfig); static FreemarkerHelper getInstance(); void resetObjectWrapper(); void render(String templatePath, Object root, Writer out); void render(String templatePath, Locale locale, String i18nBasename, Object root, Writer out); void render(Reader template, Object root, Writer out); }
@Test public void testUuidLinksAreTransformedToRelativeLinksInWebContext() throws IOException, TemplateException, RepositoryException { final MockContent page = new MockContent("baz"); final MockHierarchyManager hm = prepareHM(page); final AggregationState agg = new AggregationState(); agg.setMainContent(page); final WebContext context = createStrictMock(WebContext.class); final MockSession session = new MockSession("website"); MgnlContext.setInstance(context); expect(context.getContextPath()).andReturn("/"); expect(context.getLocale()).andReturn(Locale.CANADA); expect(context.getAggregationState()).andReturn(agg); expect(MgnlContext.getJCRSession("website")).andReturn(session).times(2); LinkTransformerManager.getInstance().setMakeBrowserLinksRelative(true); replay(context); agg.setOriginalURI("/foo/bar/boo.html"); doTestUuidLinksAreTransformed(context, "== Some text... blah blah... <a href=\"baz.html\">Bleh</a> ! =="); verify(context); } @Test public void testUuidLinksAreTransformedToAbsoluteLinksInWebContextWithoutAggregationState() throws IOException, TemplateException, RepositoryException { final MockContent page = new MockContent("baz"); final MockHierarchyManager hm = prepareHM(page); final MockSession session = new MockSession("website"); LinkTransformerManager.getInstance().setAddContextPathToBrowserLinks(true); final WebContext context = createStrictMock(WebContext.class); MgnlContext.setInstance(context); expect(context.getLocale()).andReturn(Locale.CANADA); expect(context.getAggregationState()).andReturn(null); expect(MgnlContext.getJCRSession("website")).andReturn(session).anyTimes(); expect(context.getContextPath()).andReturn("/some-context"); replay(context); doTestUuidLinksAreTransformed(context, "== Some text... blah blah... <a href=\"/some-context/foo/bar/baz.html\">Bleh</a> ! =="); verify(context); }
MagnoliaObjectWrapper extends DefaultObjectWrapper { @Override public TemplateModel wrap(Object obj) throws TemplateModelException { if (obj == null) { return super.wrap(null); } if ((obj instanceof Class) && ((Class) obj).isEnum()) { final String enumClassName = ((Class) obj).getName(); return getEnumModels().get(enumClassName); } Class<?> clazz = obj.getClass(); ModelFactory modelFactory = getModelFactory(clazz, freemarkerConfig.getModelFactories()); if (modelFactory == null) { modelFactory = getModelFactory(clazz, DEFAULT_MODEL_FACTORIES); } if (modelFactory != null) { return handleUnknownType(obj); } return super.wrap(obj); } MagnoliaObjectWrapper(FreemarkerConfig freemarkerConfig); @Override Object unwrap(TemplateModel model, Class hint); @Override TemplateModel wrap(Object obj); }
@Test public void testModelFactoryHasPrecedence() throws TemplateModelException { FreemarkerConfig freemarkerConfig = new FreemarkerConfig(); freemarkerConfig.getModelFactories().add(new CustomMapModelFactory()); MagnoliaObjectWrapper objectWrapper = new MagnoliaObjectWrapper(freemarkerConfig); TemplateModel templateModel = objectWrapper.wrap(new CustomMap()); assertTrue(templateModel instanceof CustomMapModel); } @Test public void testWrapsContentMapWithContentMapModel() throws TemplateModelException { FreemarkerConfig freemarkerConfig = new FreemarkerConfig(); MagnoliaObjectWrapper objectWrapper = new MagnoliaObjectWrapper(freemarkerConfig); TemplateModel templateModel = objectWrapper.wrap(new ContentMap(new MockNode())); assertTrue(templateModel instanceof ContentMapModel); } @Test public void testWrapsContextWithMapModel() throws TemplateModelException { FreemarkerConfig freemarkerConfig = new FreemarkerConfig(); MagnoliaObjectWrapper objectWrapper = new MagnoliaObjectWrapper(freemarkerConfig); TemplateModel templateModel = objectWrapper.wrap(new MockContext()); assertTrue(templateModel instanceof MapModel); } @Test public void testWrapsBeanAsBeanModel() throws TemplateModelException { FreemarkerConfig freemarkerConfig = new FreemarkerConfig(); MagnoliaObjectWrapper objectWrapper = new MagnoliaObjectWrapper(freemarkerConfig); TemplateModel templateModel = objectWrapper.wrap(new SimpleBean()); assertTrue(templateModel instanceof BeanModel); } @Test public void testWrapsMapAsSimpleHash() throws TemplateModelException { FreemarkerConfig freemarkerConfig = new FreemarkerConfig(); MagnoliaObjectWrapper objectWrapper = new MagnoliaObjectWrapper(freemarkerConfig); TemplateModel templateModel = objectWrapper.wrap(new HashMap()); assertTrue(templateModel instanceof SimpleHash); }
TemplatingFunctions { public Property inheritProperty(Node content, String relPath) throws RepositoryException { if (content == null) { return null; } if (StringUtils.isBlank(relPath)) { throw new IllegalArgumentException("relative path cannot be null or empty"); } try { Node inheritedNode = wrapForInheritance(content); return inheritedNode.getProperty(relPath); } catch (PathNotFoundException e) { } catch (RepositoryException e) { } return null; } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testNonExistingInheritedPropertyShouldReturnNull() throws RepositoryException { Property property = functions.inheritProperty(topPage, "iMaybeExistSomewhereElseButNotHere"); Property property2 = functions.inheritProperty(topPageComponent, "iMaybeExistSomewhereElseButNotHere"); assertNull(property); assertNull(property2); }
TemplatingFunctions { public String link(String workspace, String nodeIdentifier) { try { return LinkUtil.createLink(workspace, nodeIdentifier); } catch (RepositoryException e) { return null; } } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testLinkForPropertyFromNodeDepth1() throws RepositoryException { String value = "value"; String name = "myProperty"; topPage.setProperty(name, value); MockWebContext context = new MockWebContext(); context.setContextPath(CONTEXT_PATH); MgnlContext.setInstance(context); String resultLink = functions.link(PropertyUtil.getPropertyOrNull(topPage,name)); assertEquals(CONTEXT_PATH + topPage.getPath() + "/" + name, resultLink); } @Test public void testLinkForPropertyFromNodeDepth2() throws RepositoryException { String value = "value"; String name = "myProperty"; childPage.setProperty(name, value); MockWebContext context = new MockWebContext(); context.setContextPath(CONTEXT_PATH); MgnlContext.setInstance(context); String resultLink = functions.link(PropertyUtil.getPropertyOrNull(childPage,name)); assertEquals(CONTEXT_PATH + childPage.getPath() + "/" + name, resultLink); } @Test public void testLinkFromNodeDepth1() throws RepositoryException { MockWebContext context = new MockWebContext(); context.setContextPath(CONTEXT_PATH); MgnlContext.setInstance(context); String resultLink = functions.link(topPage); assertEquals(CONTEXT_PATH + topPage.getPath(), resultLink); } @Test public void testLinkFromNodeDepth2() throws RepositoryException { MockWebContext context = new MockWebContext(); context.setContextPath(CONTEXT_PATH); MgnlContext.setInstance(context); String resultLink = functions.link(childPage); assertEquals(CONTEXT_PATH + childPage.getPath(), resultLink); } @Test public void testLinkFromContentMapDepth1() throws RepositoryException { MockWebContext context = new MockWebContext(); context.setContextPath(CONTEXT_PATH); MgnlContext.setInstance(context); String resultLink = functions.link(topPageContentMap); assertEquals(CONTEXT_PATH + topPageContentMap.get("@path"), resultLink); } @Test public void testLinkFromContentMapDepth2() throws RepositoryException { MockWebContext context = new MockWebContext(); context.setContextPath(CONTEXT_PATH); MgnlContext.setInstance(context); String resultLink = functions.link(childPageContentMap); assertEquals(CONTEXT_PATH + childPageContentMap.get("@path"), resultLink); }
TemplatingFunctions { public String language(){ return I18nContentSupportFactory.getI18nSupport().getLocale().toString(); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testLanguage() throws RepositoryException { String langue = "fr"; MockWebContext context = new MockWebContext(); context.setContextPath(CONTEXT_PATH); Locale locale = new Locale(langue); context.setLocale(locale); MgnlContext.setInstance(context); String langueRes = functions.language(); assertEquals(langue,langueRes); }
TemplatingFunctions { public String externalLink(Node content, String linkPropertyName) { String externalLink = PropertyUtil.getString(content, linkPropertyName); if (StringUtils.isBlank(externalLink)) { return StringUtils.EMPTY; } if (!hasProtocol(externalLink)) { externalLink = "http: } return externalLink; } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testExternalLinkFromNodeNoProtocol() { topPage.setProperty("link", "www.external.ch"); String link = functions.externalLink(topPage, "link"); assertEquals("http: } @Test public void testExternalLinkFromNodeWithProtocol() { topPage.setProperty("link", "http: String link = functions.externalLink(topPage, "link"); assertEquals("http: } @Test public void testExternalLinkFromContentMapNoProtocol() { topPage.setProperty("link", "www.external.ch"); String link = functions.externalLink(new ContentMap(topPage), "link"); assertEquals("http: } @Test public void testExternalLinkFromContentMapWithProtocol() { topPage.setProperty("link", "http: String link = functions.externalLink(new ContentMap(topPage), "link"); assertEquals("http: }
TemplatingFunctions { public String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName) { String linkTitle = PropertyUtil.getString(content, linkTitlePropertyName); if (StringUtils.isNotEmpty(linkTitle)) { return linkTitle; } return externalLink(content, linkPropertyName); } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testExternalLinkTitleFromNodeWithTitle() { topPage.setProperty("link", "www.external.ch"); topPage.setProperty("linkTitle", "Link Title"); String linkTitle = functions.externalLinkTitle(topPage, "link", "linkTitle"); assertEquals("Link Title", linkTitle); } @Test public void testExternalLinkTitleFromNodeNoTitleSet() { topPage.setProperty("link", "www.external.ch"); String linkTitle = functions.externalLinkTitle(topPage, "link", "linkTitle"); assertEquals("http: } @Test public void testExternalLinkTitleFromContentMapWithTitle() { topPage.setProperty("link", "www.external.ch"); topPage.setProperty("linkTitle", "Link Title"); String linkTitle = functions.externalLinkTitle(new ContentMap(topPage), "link", "linkTitle"); assertEquals("Link Title", linkTitle); } @Test public void testExternalLinkTitleFromContentMapNoTitleSet() { topPage.setProperty("link", "www.external.ch"); String linkTitle = functions.externalLinkTitle(new ContentMap(topPage), "link", "linkTitle"); assertEquals("http: }
TemplatingFunctions { public List<Node> asNodeList(Collection<ContentMap> contentMapList) { if (contentMapList != null) { List<Node> nodeList = new ArrayList<Node>(); for (ContentMap node : contentMapList) { nodeList.add(node.getJCRNode()); } return nodeList; } return null; } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testAsNodeList() throws RepositoryException { List<Node> compareNodeList = new ArrayList<Node>(); compareNodeList.add(topPage); compareNodeList.add(childPage); compareNodeList.add(childPageSubPage); Iterator<Node> itCompare = compareNodeList.iterator(); List<ContentMap> resultMapList = functions.asContentMapList(compareNodeList); assertEquals(compareNodeList.size(), resultMapList.size()); for (Iterator<ContentMap> itResult = resultMapList.iterator(); itResult.hasNext();) { assertMapEqualsNode(itCompare.next(), itResult.next()); } }
TemplatingFunctions { public List<ContentMap> asContentMapList(Collection<Node> nodeList) { if (nodeList != null) { List<ContentMap> contentMapList = new ArrayList<ContentMap>(); for (Node node : nodeList) { contentMapList.add(asContentMap(node)); } return contentMapList; } return null; } @Inject TemplatingFunctions(Provider<AggregationState> aggregationStateProvider); Node asJCRNode(ContentMap contentMap); ContentMap asContentMap(Node content); List<Node> children(Node content); List<Node> children(Node content, String nodeTypeName); List<ContentMap> children(ContentMap content); List<ContentMap> children(ContentMap content, String nodeTypeName); ContentMap root(ContentMap contentMap); ContentMap root(ContentMap contentMap, String nodeTypeName); Node root(Node content); Node root(Node content, String nodeTypeName); ContentMap parent(ContentMap contentMap); ContentMap parent(ContentMap contentMap, String nodeTypeName); Node parent(Node content); Node parent(Node content, String nodeTypeName); ContentMap page(ContentMap content); Node page(Node content); List<ContentMap> ancestors(ContentMap contentMap); List<ContentMap> ancestors(ContentMap contentMap, String nodeTypeName); List<Node> ancestors(Node content); List<Node> ancestors(Node content, String nodeTypeName); Node inherit(Node content); Node inherit(Node content, String relPath); ContentMap inherit(ContentMap content); ContentMap inherit(ContentMap content, String relPath); Property inheritProperty(Node content, String relPath); Property inheritProperty(ContentMap content, String relPath); List<Node> inheritList(Node content, String relPath); List<ContentMap> inheritList(ContentMap content, String relPath); boolean isInherited(Node content); boolean isInherited(ContentMap content); boolean isFromCurrentPage(Node content); boolean isFromCurrentPage(ContentMap content); String link(String workspace, String nodeIdentifier); @Deprecated String link(Property property); String link(Node content); String link(ContentMap contentMap); String language(); String externalLink(Node content, String linkPropertyName); String externalLink(ContentMap content, String linkPropertyName); String externalLinkTitle(Node content, String linkPropertyName, String linkTitlePropertyName); String externalLinkTitle(ContentMap content, String linkPropertyName, String linkTitlePropertyName); boolean isEditMode(); boolean isPreviewMode(); boolean isAuthorInstance(); boolean isPublicInstance(); String createHtmlAttribute(String name, String value); SiblingsHelper siblings(Node node); SiblingsHelper siblings(ContentMap node); Node content(String path); Node content(String repository, String path); Node contentByIdentifier(String id); Node contentByIdentifier(String repository, String id); List<ContentMap> asContentMapList(Collection<Node> nodeList); List<Node> asNodeList(Collection<ContentMap> contentMapList); ContentMap decode(ContentMap content); Node decode(Node content); Node encode(Node content); String metaData(Node content, String property); String metaData(ContentMap content, String property); Collection<Node> search(String workspace, String statement, String language, String returnItemType); Collection<Node> simpleSearch(String workspace, String statement, String returnItemType, String startPath); }
@Test public void testAsContentMapList() throws RepositoryException { List<ContentMap> compareNodeList = new ArrayList<ContentMap>(); compareNodeList.add(topPageContentMap); compareNodeList.add(childPageContentMap); compareNodeList.add(childPageSubPageContentMap); Iterator<ContentMap> itCompare = compareNodeList.iterator(); List<Node> resultMapList = functions.asNodeList(compareNodeList); assertEquals(compareNodeList.size(), resultMapList.size()); for (Iterator<Node> itResult = resultMapList.iterator(); itResult.hasNext();) { assertNodeEqualsMap(itCompare.next(), itResult.next()); } }
EmailNotificationSender implements NotificationSender { @Override public NotificationMedium getNotificationMedium() { return EMAIL; } @Override NotificationMedium getNotificationMedium(); @Override ServiceResult<Notification> sendNotification(Notification notification); @Override @Transactional(propagation = Propagation.MANDATORY) ServiceResult<Notification> sendNotificationWithFlush(Notification notification); }
@Test public void testGetNotificationMedium() { assertEquals(EMAIL, notificationSender.getNotificationMedium()); }
InterviewInviteController { @GetMapping("/get-all-invites-to-resend/{competitionId}") public RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId, @RequestParam List<Long> inviteIds) { return interviewInviteService.getAllInvitesToResend(competitionId, inviteIds).toGetResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId, @RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId, @RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds, @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable ); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping(value = "/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<InterviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping(value = "/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping("/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview( @PathVariable long competitionId, @RequestParam List<ParticipantStatus> statuses, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<InterviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); }
@Test public void getAllInvitesToResend() throws Exception { AssessorInvitesToSendResource resource = newAssessorInvitesToSendResource().build(); List<Long> inviteIds = asList(1L, 2L); when(interviewInviteServiceMock.getAllInvitesToResend(COMPETITION_ID, inviteIds)).thenReturn(serviceSuccess(resource)); mockMvc.perform(get("/interview-panel-invite/get-all-invites-to-resend/{competitionId}", COMPETITION_ID).contentType(MediaType.APPLICATION_JSON) .param("inviteIds", simpleJoiner(inviteIds, ","))) .andExpect(status().isOk()); verify(interviewInviteServiceMock, only()).getAllInvitesToResend(COMPETITION_ID, inviteIds); }
InterviewInviteController { @PostMapping("/resend-invites") public RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds, @RequestBody AssessorInviteSendResource assessorInviteSendResource) { return interviewInviteService.resendInvites(inviteIds, assessorInviteSendResource).toPostWithBodyResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId, @RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId, @RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds, @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable ); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping(value = "/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<InterviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping(value = "/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping("/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview( @PathVariable long competitionId, @RequestParam List<ParticipantStatus> statuses, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<InterviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); }
@Test public void resendInvites() throws Exception { List<Long> inviteIds = asList(1L, 2L); AssessorInviteSendResource assessorInviteSendResource = newAssessorInviteSendResource() .withSubject("subject") .withContent("content") .build(); when(interviewInviteServiceMock.resendInvites(inviteIds, assessorInviteSendResource)).thenReturn(serviceSuccess()); mockMvc.perform(post("/interview-panel-invite/resend-invites") .contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(assessorInviteSendResource)) .param("inviteIds", simpleJoiner(inviteIds, ","))) .andExpect(status().isOk()); verify(interviewInviteServiceMock).resendInvites(inviteIds, assessorInviteSendResource); }
InterviewInviteController { @GetMapping("/get-invitation-overview/{competitionId}") public RestResult<AssessorInviteOverviewPageResource> getInvitationOverview( @PathVariable long competitionId, @RequestParam List<ParticipantStatus> statuses, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable) { return interviewInviteService.getInvitationOverview(competitionId, pageable, statuses).toGetResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId, @RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId, @RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds, @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable ); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping(value = "/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<InterviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping(value = "/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping("/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview( @PathVariable long competitionId, @RequestParam List<ParticipantStatus> statuses, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<InterviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); }
@Test public void getInvitationOverview() throws Exception { long competitionId = 1L; int page = 2; int size = 10; List<ParticipantStatus> status = Collections.singletonList(ACCEPTED); AssessorInviteOverviewPageResource expectedPageResource = newAssessorInviteOverviewPageResource() .withContent(newAssessorInviteOverviewResource().build(2)) .build(); Pageable pageable = PageRequest.of(page, size, new Sort(Sort.Direction.ASC, "invite.email")); when(interviewInviteServiceMock.getInvitationOverview(competitionId, pageable, status)) .thenReturn(serviceSuccess(expectedPageResource)); mockMvc.perform(get("/interview-panel-invite/get-invitation-overview/{competitionId}", competitionId) .param("page", "2") .param("size", "10") .param("sort", "invite.email") .param("statuses", "ACCEPTED")) .andExpect(status().isOk()) .andExpect(content().json(toJson(expectedPageResource))); verify(interviewInviteServiceMock, only()).getInvitationOverview(competitionId, pageable, status); }
InterviewInviteController { @DeleteMapping("/delete-invite") public RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId) { return interviewInviteService.deleteInvite(email, competitionId).toDeleteResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId, @RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId, @RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds, @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable ); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping(value = "/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<InterviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping(value = "/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping("/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview( @PathVariable long competitionId, @RequestParam List<ParticipantStatus> statuses, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<InterviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); }
@Test public void deleteInvite() throws Exception { String email = "[email protected]"; long competitionId = 1L; when(interviewInviteServiceMock.deleteInvite(email, competitionId)).thenReturn(serviceSuccess()); mockMvc.perform(delete("/interview-panel-invite/delete-invite") .param("email", email) .param("competitionId", String.valueOf(competitionId))) .andExpect(status().isNoContent()); verify(interviewInviteServiceMock, only()).deleteInvite(email, competitionId); }
InterviewInviteController { @DeleteMapping("/delete-all-invites") public RestResult<Void> deleteAllInvites(@RequestParam long competitionId) { return interviewInviteService.deleteAllInvites(competitionId).toDeleteResponse(); } @GetMapping("/get-all-invites-to-send/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToSend(@PathVariable long competitionId); @GetMapping("/get-all-invites-to-resend/{competitionId}") RestResult<AssessorInvitesToSendResource> getAllInvitesToResend(@PathVariable long competitionId, @RequestParam List<Long> inviteIds); @PostMapping("/send-all-invites/{competitionId}") RestResult<Void> sendAllInvites(@PathVariable long competitionId, @RequestBody AssessorInviteSendResource assessorInviteSendResource); @PostMapping("/resend-invites") RestResult<Void> resendInvites(@RequestParam List<Long> inviteIds, @RequestBody AssessorInviteSendResource assessorInviteSendResource); @GetMapping("/get-created-invites/{competitionId}") RestResult<AssessorCreatedInvitePageResource> getCreatedInvites( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "name", direction = Sort.Direction.ASC) Pageable pageable ); @PostMapping("/invite-users") RestResult<Void> inviteUsers(@Valid @RequestBody ExistingUserStagedInviteListResource existingUserStagedInvites); @GetMapping("/get-available-assessors/{competitionId}") RestResult<AvailableAssessorPageResource> getAvailableAssessors( @PathVariable long competitionId, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = {"user.firstName", "user.lastName"}, direction = Sort.Direction.ASC) Pageable pageable); @GetMapping(value = "/get-available-assessor-ids/{competitionId}") RestResult<List<Long>> getAvailableAssessorIds(@PathVariable long competitionId); @GetMapping("/get-all-invites-by-user/{userId}") RestResult<List<InterviewParticipantResource>> getAllInvitesByUser(@PathVariable long userId); @GetMapping(value = "/get-non-accepted-assessor-invite-ids/{competitionId}") RestResult<List<Long>> getNonAcceptedAssessorInviteIds(@PathVariable long competitionId); @GetMapping("/get-invitation-overview/{competitionId}") RestResult<AssessorInviteOverviewPageResource> getInvitationOverview( @PathVariable long competitionId, @RequestParam List<ParticipantStatus> statuses, @PageableDefault(size = DEFAULT_PAGE_SIZE, sort = "invite.name", direction = Sort.Direction.ASC) Pageable pageable); @PostMapping("/open-invite/{inviteHash}") RestResult<InterviewInviteResource> openInvite(@PathVariable String inviteHash); @PostMapping("/accept-invite/{inviteHash}") RestResult<Void> acceptInvite(@PathVariable String inviteHash); @PostMapping("/reject-invite/{inviteHash}") RestResult<Void> rejectInvite(@PathVariable String inviteHash); @GetMapping("/check-existing-user/{inviteHash}") RestResult<Boolean> checkExistingUser(@PathVariable String inviteHash); @DeleteMapping("/delete-invite") RestResult<Void> deleteInvite(@RequestParam String email, @RequestParam long competitionId); @DeleteMapping("/delete-all-invites") RestResult<Void> deleteAllInvites(@RequestParam long competitionId); }
@Test public void deleteAllInvites() throws Exception { long competitionId = 1L; when(interviewInviteServiceMock.deleteAllInvites(competitionId)).thenReturn(serviceSuccess()); mockMvc.perform(delete("/interview-panel-invite/delete-all-invites") .param("competitionId", String.valueOf(competitionId))) .andExpect(status().isNoContent()); verify(interviewInviteServiceMock).deleteAllInvites(competitionId); }
InterviewApplicationFeedbackServiceImpl implements InterviewApplicationFeedbackService { @Override @Transactional(readOnly = true) public ServiceResult<FileEntryResource> findFeedback(long applicationId) { return findAssignmentByApplicationId(applicationId).andOnSuccess(interviewAssignment -> ofNullable(interviewAssignment.getMessage()) .map(InterviewAssignmentMessageOutcome::getFeedback) .map(FileEntry::getId) .map(fileEntryService::findOne) .orElse(ServiceResult.serviceSuccess(null))); } @Override ServiceResult<Void> uploadFeedback(String contentType, String contentLength, String originalFilename, long applicationId, HttpServletRequest request); @Override ServiceResult<Void> deleteFeedback(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileAndContents> downloadFeedback(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileEntryResource> findFeedback(long applicationId); }
@Test public void findFeedback() throws Exception { long applicationId = 1L; FileEntry fileEntry = newFileEntry().build(); InterviewAssignment interviewAssignment = newInterviewAssignment(). withMessage(newInterviewAssignmentMessageOutcome() .withFeedback(fileEntry) .build() ).build(); FileEntryResource fileEntryResource = newFileEntryResource().build(); when(interviewAssignmentRepositoryMock.findOneByTargetId(applicationId)).thenReturn(interviewAssignment); when(fileEntryServiceMock.findOne(fileEntry.getId())).thenReturn(serviceSuccess(fileEntryResource)); FileEntryResource response = service.findFeedback(applicationId).getSuccess(); assertEquals(fileEntryResource, response); }
InterviewApplicationFeedbackServiceImpl implements InterviewApplicationFeedbackService { @Override @Transactional(readOnly = true) public ServiceResult<FileAndContents> downloadFeedback(long applicationId) { return findAssignmentByApplicationId(applicationId).andOnSuccess(interviewAssignment -> fileEntryService.findOne(interviewAssignment.getMessage().getFeedback().getId()) .andOnSuccess(this::getFileAndContents)); } @Override ServiceResult<Void> uploadFeedback(String contentType, String contentLength, String originalFilename, long applicationId, HttpServletRequest request); @Override ServiceResult<Void> deleteFeedback(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileAndContents> downloadFeedback(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileEntryResource> findFeedback(long applicationId); }
@Test public void downloadFeedback() throws Exception { final long applicationId = 1L; final long fileId = 2L; final FileEntry fileEntry = new FileEntry(fileId, "somefile.pdf", MediaType.APPLICATION_PDF, 1111L); InterviewAssignment interviewAssignment = newInterviewAssignment(). withMessage(newInterviewAssignmentMessageOutcome() .withFeedback(fileEntry) .build() ).build(); FileEntryResource fileEntryResource = new FileEntryResource(); fileEntryResource.setId(fileId); when(interviewAssignmentRepositoryMock.findOneByTargetId(applicationId)).thenReturn(interviewAssignment); when(fileEntryServiceMock.findOne(fileId)).thenReturn(serviceSuccess(fileEntryResource)); final Supplier<InputStream> contentSupplier = () -> null; when(fileServiceMock.getFileByFileEntryId(fileEntry.getId())).thenReturn(ServiceResult.serviceSuccess(contentSupplier)); FileAndContents fileAndContents = service.downloadFeedback(applicationId).getSuccess(); assertEquals(fileAndContents.getContentsSupplier(), contentSupplier); assertEquals(fileAndContents.getFileEntry(), fileEntryResource); }
InterviewApplicationFeedbackServiceImpl implements InterviewApplicationFeedbackService { @Override public ServiceResult<Void> deleteFeedback(long applicationId) { return findAssignmentByApplicationId(applicationId).andOnSuccess(interviewAssignment -> { long fileId = interviewAssignment.getMessage().getFeedback().getId(); return fileService.deleteFileIgnoreNotFound(fileId).andOnSuccessReturnVoid(() -> { if (interviewAssignment.getProcessState() == InterviewAssignmentState.CREATED) { InterviewAssignmentMessageOutcome messageOutcome = interviewAssignment.getMessage(); interviewAssignment.removeMessage(); interviewAssignmentMessageOutcomeRepository.delete(messageOutcome); } else { interviewAssignment.getMessage().setFeedback(null); } }); }); } @Override ServiceResult<Void> uploadFeedback(String contentType, String contentLength, String originalFilename, long applicationId, HttpServletRequest request); @Override ServiceResult<Void> deleteFeedback(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileAndContents> downloadFeedback(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileEntryResource> findFeedback(long applicationId); }
@Test public void deleteFeedback_created() throws Exception { final long applicationId = 1L; final long fileId = 101L; final FileEntry fileEntry = new FileEntry(fileId, "somefile.pdf", MediaType.APPLICATION_PDF, 1111L); InterviewAssignmentMessageOutcome messageOutcome = newInterviewAssignmentMessageOutcome() .withId(2L) .withFeedback(fileEntry) .build(); InterviewAssignment interviewAssignment = newInterviewAssignment() .withState(InterviewAssignmentState.CREATED) .withMessage(messageOutcome) .build(); when(interviewAssignmentRepositoryMock.findOneByTargetId(applicationId)).thenReturn(interviewAssignment); when(fileServiceMock.deleteFileIgnoreNotFound(fileId)).thenReturn(ServiceResult.serviceSuccess(fileEntry)); ServiceResult<Void> response = service.deleteFeedback(applicationId); assertTrue(response.isSuccess()); verify(interviewAssignmentMessageOutcomeRepositoryMock).delete(messageOutcome); verify(fileServiceMock).deleteFileIgnoreNotFound(fileId); } @Test public void deleteFeedback_submitted() throws Exception { final long applicationId = 1L; final long fileId = 101L; final FileEntry fileEntry = new FileEntry(fileId, "somefile.pdf", MediaType.APPLICATION_PDF, 1111L); InterviewAssignmentMessageOutcome messageOutcome = newInterviewAssignmentMessageOutcome() .withId(2L) .withFeedback(fileEntry) .build(); InterviewAssignment interviewAssignment = newInterviewAssignment() .withState(InterviewAssignmentState.SUBMITTED_FEEDBACK_RESPONSE) .withMessage(messageOutcome) .build(); when(interviewAssignmentRepositoryMock.findOneByTargetId(applicationId)).thenReturn(interviewAssignment); when(fileServiceMock.deleteFileIgnoreNotFound(fileId)).thenReturn(ServiceResult.serviceSuccess(fileEntry)); ServiceResult<Void> response = service.deleteFeedback(applicationId); assertTrue(response.isSuccess()); verifyZeroInteractions(interviewAssignmentMessageOutcomeRepositoryMock); assertNull(messageOutcome.getFeedback()); }
InterviewAllocationServiceImpl implements InterviewAllocationService { @Override public ServiceResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(long competitionId, Pageable pageable) { Page<InterviewAcceptedAssessorsResource> pagedResult = interviewParticipantRepository.getInterviewAcceptedAssessorsByCompetition( competitionId, pageable); return serviceSuccess(new InterviewAcceptedAssessorsPageResource( pagedResult.getTotalElements(), pagedResult.getTotalPages(), pagedResult.getContent(), pagedResult.getNumber(), pagedResult.getSize() )); } @Override ServiceResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(long competitionId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getUnallocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getAllocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(long competitionId, long assessorUserId); @Override ServiceResult<List<InterviewApplicationResource>> getUnallocatedApplicationsById(List<Long> applicationIds); @Override ServiceResult<List<Long>> getUnallocatedApplicationIds(long competitionId, long assessorId); @Override ServiceResult<AssessorInvitesToSendResource> getInviteToSend(long competitionId, long assessorId); @Override @Transactional ServiceResult<Void> unallocateApplication(long assessorId, long applicationId); @Override @Transactional ServiceResult<Void> notifyAllocation(InterviewNotifyAllocationResource interviewNotifyAllocationResource); }
@Test public void getAllocateApplicationsOverview() { long competitionId = 1L; Pageable pageable = PageRequest.of(0, 5); List<InterviewAcceptedAssessorsResource> expectedParticipants = newInterviewAcceptedAssessorsResource() .withName("Name 1", "Name 2", "Name 3", "Name 4", "Name 5") .build(5); Page<InterviewAcceptedAssessorsResource> pageResult = new PageImpl<>(expectedParticipants, pageable, 10); when(interviewParticipantRepositoryMock.getInterviewAcceptedAssessorsByCompetition( competitionId, pageable )) .thenReturn(pageResult); List<AssessorInviteOverviewResource> overviewResources = newAssessorInviteOverviewResource() .withName("Name 1", "Name 2", "Name 3", "Name 4", "Name 5") .build(5); when(assessorInviteOverviewMapperMock.mapToResource(isA(InterviewParticipant.class))) .thenReturn( overviewResources.get(0), overviewResources.get(1), overviewResources.get(2), overviewResources.get(3), overviewResources.get(4) ); ServiceResult<InterviewAcceptedAssessorsPageResource> result = service.getInterviewAcceptedAssessors(competitionId, pageable); verify(interviewParticipantRepositoryMock) .getInterviewAcceptedAssessorsByCompetition(competitionId, pageable); assertTrue(result.isSuccess()); InterviewAcceptedAssessorsPageResource pageResource = result.getSuccess(); assertEquals(0, pageResource.getNumber()); assertEquals(5, pageResource.getSize()); assertEquals(2, pageResource.getTotalPages()); assertEquals(10, pageResource.getTotalElements()); List<InterviewAcceptedAssessorsResource> content = pageResource.getContent(); assertEquals("Name 1", content.get(0).getName()); assertEquals("Name 2", content.get(1).getName()); assertEquals("Name 3", content.get(2).getName()); assertEquals("Name 4", content.get(3).getName()); assertEquals("Name 5", content.get(4).getName()); }
PublicContentServiceImpl extends BaseTransactionalService implements PublicContentService { @Override @Transactional public ServiceResult<Void> updateSection(PublicContentResource resource, PublicContentSectionType section) { return saveSection(resource, section).andOnSuccessReturnVoid(); } @Override ServiceResult<PublicContentResource> findByCompetitionId(long id); @Override @Transactional ServiceResult<Void> initialiseByCompetitionId(long competitionId); @Override @Transactional ServiceResult<Void> publishByCompetitionId(long competitionId); @Override @Transactional ServiceResult<Void> updateSection(PublicContentResource resource, PublicContentSectionType section); @Override @Transactional ServiceResult<Void> markSectionAsComplete(PublicContentResource resource, PublicContentSectionType section); }
@Test public void testUpdateDatesSection() { PublicContent publicContent = newPublicContent().withContentSections(Collections.emptyList()).build(); List<ContentEventResource> events = newContentEventResource().build(1); PublicContentResource publicContentResource = newPublicContentResource() .withContentEvents(events).build(); when(publicContentMapper.mapToDomain(publicContentResource)).thenReturn(publicContent); when(publicContentRepository.save(publicContent)).thenReturn(publicContent); when(contentEventService.resetAndSaveEvents(publicContent.getId(), events)).thenReturn(serviceSuccess()); ServiceResult<Void> result = service.updateSection(publicContentResource, PublicContentSectionType.DATES); verify(publicContentRepository).save(publicContent); verify(contentEventService).resetAndSaveEvents(publicContent.getId(), events); assertTrue(result.isSuccess()); } @Test public void testUpdateSectionPublished() { PublicContent publicContent = mock(PublicContent.class); PublicContentResource publicContentResource = newPublicContentResource().withKeywords(Collections.emptyList()).build(); when(publicContentMapper.mapToDomain(publicContentResource)).thenReturn(publicContent); when(publicContentRepository.save(publicContent)).thenReturn(publicContent); when(publicContent.getContentSections()).thenReturn(newContentSection().withStatus(PublicContentStatus.COMPLETE).build(1)); when(publicContent.getId()).thenReturn(1L); when(publicContent.getCompetitionId()).thenReturn(COMPETITION_ID); when(publicContent.getPublishDate()).thenReturn(ZonedDateTime.now()); mockPublicMilestonesValid(true); ServiceResult<Void> result = service.updateSection(publicContentResource, PublicContentSectionType.SEARCH); verify(publicContentRepository).save(publicContent); verify(publicContent).setPublishDate(any()); assertTrue(result.isSuccess()); } @Test public void testUpdateSectionNotPublished() { PublicContent publicContent = mock(PublicContent.class); PublicContentResource publicContentResource = newPublicContentResource().withKeywords(Collections.emptyList()).build(); when(publicContentMapper.mapToDomain(publicContentResource)).thenReturn(publicContent); when(publicContentRepository.save(publicContent)).thenReturn(publicContent); ContentSection section = newContentSection().withType(PublicContentSectionType.SEARCH).withStatus(IN_PROGRESS).build(); when(publicContent.getContentSections()).thenReturn(asList(section)); when(publicContent.getId()).thenReturn(1L); when(publicContent.getPublishDate()).thenReturn(null); ServiceResult<Void> result = service.updateSection(publicContentResource, PublicContentSectionType.SEARCH); verify(publicContentRepository).save(publicContent); verify(publicContent, never()).setPublishDate(any()); assertThat(section.getStatus(), equalTo(IN_PROGRESS)); assertTrue(result.isSuccess()); } @Test public void testUpdateSearchSection() { PublicContent publicContent = newPublicContent().withContentSections(Collections.emptyList()).build(); List<String> keywords = asList("key1", "key2"); PublicContentResource publicContentResource = newPublicContentResource() .withKeywords(keywords).build(); when(publicContentMapper.mapToDomain(publicContentResource)).thenReturn(publicContent); when(publicContentRepository.save(publicContent)).thenReturn(publicContent); ServiceResult<Void> result = service.updateSection(publicContentResource, PublicContentSectionType.SEARCH); verify(publicContentRepository).save(publicContent); keywords.forEach(keyword -> verify(keywordRepository).save(keywordMatcher(keyword))); assertTrue(result.isSuccess()); }
InterviewAllocationServiceImpl implements InterviewAllocationService { @Override public ServiceResult<InterviewApplicationPageResource> getAllocatedApplications(long competitionId, long assessorUserId, Pageable pageable) { Page<InterviewApplicationResource> pagedResult = interviewRepository.findApplicationsAssignedToAssessor( competitionId, assessorUserId, pageable); long unallocatedApplications = interviewRepository.countUnallocatedApplications(competitionId, assessorUserId); long allocatedApplications = interviewRepository.countAllocatedApplications(competitionId, assessorUserId); return serviceSuccess(new InterviewApplicationPageResource( pagedResult.getTotalElements(), pagedResult.getTotalPages(), pagedResult.getContent(), pagedResult.getNumber(), pagedResult.getSize(), unallocatedApplications, allocatedApplications )); } @Override ServiceResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(long competitionId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getUnallocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getAllocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(long competitionId, long assessorUserId); @Override ServiceResult<List<InterviewApplicationResource>> getUnallocatedApplicationsById(List<Long> applicationIds); @Override ServiceResult<List<Long>> getUnallocatedApplicationIds(long competitionId, long assessorId); @Override ServiceResult<AssessorInvitesToSendResource> getInviteToSend(long competitionId, long assessorId); @Override @Transactional ServiceResult<Void> unallocateApplication(long assessorId, long applicationId); @Override @Transactional ServiceResult<Void> notifyAllocation(InterviewNotifyAllocationResource interviewNotifyAllocationResource); }
@Test public void getAllocatedApplications() { long competitionId = 1L; long userId = 2L; Pageable pageable = PageRequest.of(0, 5); long allocatedApplications = 3L; long unallocatedApplications = 4L; List<InterviewApplicationResource> expectedParticipants = newInterviewApplicationResource() .build(1); Page<InterviewApplicationResource> pageResult = new PageImpl<>(expectedParticipants, pageable, 10); when(interviewRepositoryMock.findApplicationsAssignedToAssessor( competitionId, userId, pageable )).thenReturn(pageResult); when(interviewRepositoryMock.countAllocatedApplications(competitionId, userId)).thenReturn(allocatedApplications); when(interviewRepositoryMock.countUnallocatedApplications(competitionId, userId)).thenReturn(unallocatedApplications); ServiceResult<InterviewApplicationPageResource> result = service.getAllocatedApplications(competitionId, userId, pageable); verify(interviewRepositoryMock) .findApplicationsAssignedToAssessor(competitionId, userId, pageable); verify(interviewRepositoryMock).countAllocatedApplications(competitionId, userId); verify(interviewRepositoryMock).countUnallocatedApplications(competitionId, userId); assertTrue(result.isSuccess()); InterviewApplicationPageResource pageResource = result.getSuccess(); assertEquals(pageResource.getContent(), expectedParticipants); assertEquals(pageResource.getUnallocatedApplications(), unallocatedApplications); assertEquals(pageResource.getAllocatedApplications(), allocatedApplications); }
InterviewAllocationServiceImpl implements InterviewAllocationService { @Override public ServiceResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(long competitionId, long assessorUserId) { List<Interview> interviews = interviewRepository.findByParticipantUserIdAndTargetCompetitionIdOrderByActivityStateAscIdAsc( assessorUserId, competitionId); List<InterviewResource> interviewResources = interviews.stream() .map(interview -> interviewMapper.mapToResource(interview)) .collect(Collectors.toList()); return serviceSuccess(interviewResources); } @Override ServiceResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(long competitionId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getUnallocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getAllocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(long competitionId, long assessorUserId); @Override ServiceResult<List<InterviewApplicationResource>> getUnallocatedApplicationsById(List<Long> applicationIds); @Override ServiceResult<List<Long>> getUnallocatedApplicationIds(long competitionId, long assessorId); @Override ServiceResult<AssessorInvitesToSendResource> getInviteToSend(long competitionId, long assessorId); @Override @Transactional ServiceResult<Void> unallocateApplication(long assessorId, long applicationId); @Override @Transactional ServiceResult<Void> notifyAllocation(InterviewNotifyAllocationResource interviewNotifyAllocationResource); }
@Test public void getAllocatedApplicationsByAssessorId() { long competitionId = 1L; User user = newUser() .withId(1L) .build(); Application application1 = newApplication() .withId(1L) .withName("Application 1") .build(); Application application2 = newApplication() .withId(1L) .withName("Application 1") .build(); ProcessRole processRole1 = newProcessRole() .withApplication(application1) .withUser(user) .build(); ProcessRole processRole2 = newProcessRole() .withApplication(application2) .withUser(user) .build(); List<Interview> expectedInterviews = newInterview() .withTarget(application1, application2) .withParticipant(processRole1, processRole2) .build(2); List<InterviewResource> expectedInterviewResources = newInterviewResource() .withApplication(application1.getId(), application2.getId()) .withProcessRole(processRole1.getId(), processRole2.getId()) .build(2); when(interviewRepositoryMock.findByParticipantUserIdAndTargetCompetitionIdOrderByActivityStateAscIdAsc( competitionId, user.getId() )).thenReturn(expectedInterviews); when(interviewMapper.mapToResource(expectedInterviews.get(0))).thenReturn(expectedInterviewResources.get(0)); when(interviewMapper.mapToResource(expectedInterviews.get(1))).thenReturn(expectedInterviewResources.get(1)); ServiceResult<List<InterviewResource>> result = service.getAllocatedApplicationsByAssessorId(competitionId, user.getId()); verify(interviewRepositoryMock) .findByParticipantUserIdAndTargetCompetitionIdOrderByActivityStateAscIdAsc(competitionId, user.getId()); assertTrue(result.isSuccess()); List<InterviewResource> interviewResources = result.getSuccess(); assertEquals(interviewResources.get(0).getApplication(), expectedInterviews.get(0).getTarget().getId()); assertEquals(processRole1, expectedInterviews.get(0).getParticipant()); assertEquals(interviewResources.get(1).getApplication(), expectedInterviews.get(1).getTarget().getId()); assertEquals(processRole2, expectedInterviews.get(1).getParticipant()); assertEquals(interviewResources.size(), expectedInterviews.size()); }
InterviewAllocationServiceImpl implements InterviewAllocationService { @Override public ServiceResult<InterviewApplicationPageResource> getUnallocatedApplications(long competitionId, long assessorUserId, Pageable pageable) { Page<InterviewApplicationResource> pagedResult = interviewRepository.findApplicationsNotAssignedToAssessor( competitionId, assessorUserId, pageable); long unallocatedApplications = interviewRepository.countUnallocatedApplications(competitionId, assessorUserId); long allocatedApplications = interviewRepository.countAllocatedApplications(competitionId, assessorUserId); return serviceSuccess(new InterviewApplicationPageResource( pagedResult.getTotalElements(), pagedResult.getTotalPages(), pagedResult.getContent(), pagedResult.getNumber(), pagedResult.getSize(), unallocatedApplications, allocatedApplications )); } @Override ServiceResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(long competitionId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getUnallocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getAllocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(long competitionId, long assessorUserId); @Override ServiceResult<List<InterviewApplicationResource>> getUnallocatedApplicationsById(List<Long> applicationIds); @Override ServiceResult<List<Long>> getUnallocatedApplicationIds(long competitionId, long assessorId); @Override ServiceResult<AssessorInvitesToSendResource> getInviteToSend(long competitionId, long assessorId); @Override @Transactional ServiceResult<Void> unallocateApplication(long assessorId, long applicationId); @Override @Transactional ServiceResult<Void> notifyAllocation(InterviewNotifyAllocationResource interviewNotifyAllocationResource); }
@Test public void getUnallocatedApplications() { long competitionId = 1L; long userId = 2L; Pageable pageable = PageRequest.of(0, 5); long allocatedApplications = 3L; long unallocatedApplications = 4L; List<InterviewApplicationResource> expectedParticipants = newInterviewApplicationResource() .build(1); Page<InterviewApplicationResource> pageResult = new PageImpl<>(expectedParticipants, pageable, 10); when(interviewRepositoryMock.findApplicationsNotAssignedToAssessor( competitionId, userId, pageable )).thenReturn(pageResult); when(interviewRepositoryMock.countAllocatedApplications(competitionId, userId)).thenReturn(allocatedApplications); when(interviewRepositoryMock.countUnallocatedApplications(competitionId, userId)).thenReturn(unallocatedApplications); ServiceResult<InterviewApplicationPageResource> result = service.getUnallocatedApplications(competitionId, userId, pageable); verify(interviewRepositoryMock) .findApplicationsNotAssignedToAssessor(competitionId, userId, pageable); verify(interviewRepositoryMock).countAllocatedApplications(competitionId, userId); verify(interviewRepositoryMock).countUnallocatedApplications(competitionId, userId); assertTrue(result.isSuccess()); InterviewApplicationPageResource pageResource = result.getSuccess(); assertEquals(pageResource.getContent(), expectedParticipants); assertEquals(pageResource.getUnallocatedApplications(), unallocatedApplications); assertEquals(pageResource.getAllocatedApplications(), allocatedApplications); }
InterviewAllocationServiceImpl implements InterviewAllocationService { @Override public ServiceResult<List<Long>> getUnallocatedApplicationIds(long competitionId, long assessorId) { return serviceSuccess(interviewRepository.findApplicationIdsNotAssignedToAssessor(competitionId, assessorId)); } @Override ServiceResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(long competitionId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getUnallocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getAllocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(long competitionId, long assessorUserId); @Override ServiceResult<List<InterviewApplicationResource>> getUnallocatedApplicationsById(List<Long> applicationIds); @Override ServiceResult<List<Long>> getUnallocatedApplicationIds(long competitionId, long assessorId); @Override ServiceResult<AssessorInvitesToSendResource> getInviteToSend(long competitionId, long assessorId); @Override @Transactional ServiceResult<Void> unallocateApplication(long assessorId, long applicationId); @Override @Transactional ServiceResult<Void> notifyAllocation(InterviewNotifyAllocationResource interviewNotifyAllocationResource); }
@Test public void getUnallocatedApplicationIds() { long competitionId = 1L; long userId = 2L; List<Long> ids = asList(4L, 5L); when(interviewRepositoryMock.findApplicationIdsNotAssignedToAssessor( competitionId, userId )).thenReturn(ids); ServiceResult<List<Long>> result = service.getUnallocatedApplicationIds(competitionId, userId); verify(interviewRepositoryMock) .findApplicationIdsNotAssignedToAssessor(competitionId, userId); assertTrue(result.isSuccess()); assertEquals(result.getSuccess(), ids); }
InterviewAllocationServiceImpl implements InterviewAllocationService { @Override public ServiceResult<AssessorInvitesToSendResource> getInviteToSend(long competitionId, long assessorId) { return getCompetition(competitionId).andOnSuccess( competition -> getUser(assessorId).andOnSuccess( user -> serviceSuccess( new AssessorInvitesToSendResource( singletonList(user.getName()), competition.getId(), competition.getName(), getInvitePreviewContent(asMap( "name", user.getName(), "competitionName", competition.getName() )))))); } @Override ServiceResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(long competitionId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getUnallocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getAllocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(long competitionId, long assessorUserId); @Override ServiceResult<List<InterviewApplicationResource>> getUnallocatedApplicationsById(List<Long> applicationIds); @Override ServiceResult<List<Long>> getUnallocatedApplicationIds(long competitionId, long assessorId); @Override ServiceResult<AssessorInvitesToSendResource> getInviteToSend(long competitionId, long assessorId); @Override @Transactional ServiceResult<Void> unallocateApplication(long assessorId, long applicationId); @Override @Transactional ServiceResult<Void> notifyAllocation(InterviewNotifyAllocationResource interviewNotifyAllocationResource); }
@Test public void getInviteToSend() { Competition competition = newCompetition().build(); User user = newUser().build(); String content = "content"; NotificationTarget notificationTarget = new UserNotificationTarget("", ""); String templatePath = PREVIEW_TEMPLATES_PATH + "allocate_interview_applications_to_assessor_text.txt"; Map<String, Object> notificationArguments = asMap( "name", user.getName(), "competitionName", competition.getName() ); AssessorInvitesToSendResource expectedInvitesToSendResource = new AssessorInvitesToSendResource(singletonList(user.getName()), competition.getId(), competition.getName(), content); when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition)); when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user)); when(notificationTemplateRendererMock.renderTemplate(systemNotificationSourceMock, notificationTarget, templatePath, notificationArguments)).thenReturn(serviceSuccess(content)); AssessorInvitesToSendResource actual = service.getInviteToSend(competition.getId(), user.getId()).getSuccess(); assertEquals(expectedInvitesToSendResource, actual); InOrder inOrder = inOrder(competitionRepositoryMock, userRepositoryMock, notificationTemplateRendererMock, systemNotificationSourceMock); inOrder.verify(competitionRepositoryMock).findById(competition.getId()); inOrder.verify(userRepositoryMock).findById(user.getId()); inOrder.verify(notificationTemplateRendererMock).renderTemplate(systemNotificationSourceMock, notificationTarget, templatePath, notificationArguments); inOrder.verifyNoMoreInteractions(); }
InterviewAllocationServiceImpl implements InterviewAllocationService { @Override @Transactional public ServiceResult<Void> notifyAllocation(InterviewNotifyAllocationResource interviewNotifyAllocationResource) { return getInterviewParticipant(interviewNotifyAllocationResource.getAssessorId(), interviewNotifyAllocationResource.getCompetitionId()) .andOnSuccess(assessor -> createInterviews(interviewNotifyAllocationResource, assessor)) .andOnSuccess(assessor -> sendAllocationNotification( interviewNotifyAllocationResource.getSubject(), interviewNotifyAllocationResource.getContent(), assessor, NOTIFY_ASSESSOR_OF_INTERVIEW_ALLOCATIONS )); } @Override ServiceResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(long competitionId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getUnallocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getAllocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(long competitionId, long assessorUserId); @Override ServiceResult<List<InterviewApplicationResource>> getUnallocatedApplicationsById(List<Long> applicationIds); @Override ServiceResult<List<Long>> getUnallocatedApplicationIds(long competitionId, long assessorId); @Override ServiceResult<AssessorInvitesToSendResource> getInviteToSend(long competitionId, long assessorId); @Override @Transactional ServiceResult<Void> unallocateApplication(long assessorId, long applicationId); @Override @Transactional ServiceResult<Void> notifyAllocation(InterviewNotifyAllocationResource interviewNotifyAllocationResource); }
@Test public void notifyAllocation() { Competition competition = newCompetition().build(); User user = newUser().withFirstName("tom").withLastName("baldwin").withEmailAddress("[email protected]").build(); InterviewParticipant interviewParticipant = newInterviewParticipant().withUser(user) .withCompetition(newCompetition().build()) .build(); String subject = "subject"; String content = "content"; List<Application> applications = newApplication().build(1); InterviewNotifyAllocationResource interviewNotifyAllocationResource = new InterviewNotifyAllocationResource(competition.getId(), user.getId(), subject, content, simpleMap(applications, Application::getId)); Interview interview = new Interview(applications.get(0), interviewParticipant); Notification expectedNotification = new Notification( systemNotificationSourceMock, new UserNotificationTarget(user.getName(), user.getEmail()), NOTIFY_ASSESSOR_OF_INTERVIEW_ALLOCATIONS, asMap( "subject", subject, "name", user.getName(), "competitionName", interviewParticipant.getProcess().getName(), "customTextPlain", content, "customTextHtml", content )); when(applicationRepositoryMock.findById(applications.get(0).getId())).thenReturn(Optional.of(applications.get(0))); when(interviewParticipantRepositoryMock .findByUserIdAndCompetitionIdAndRole(user.getId(), competition.getId(), CompetitionParticipantRole.INTERVIEW_ASSESSOR)) .thenReturn(interviewParticipant); when(notificationServiceMock.sendNotificationWithFlush(expectedNotification, EMAIL)).thenReturn(serviceSuccess()); service.notifyAllocation(interviewNotifyAllocationResource).getSuccess(); InOrder inOrder = inOrder(notificationServiceMock, applicationRepositoryMock, interviewParticipantRepositoryMock, interviewWorkflowHandlerMock, interviewRepositoryMock); inOrder.verify(applicationRepositoryMock).findById(applications.get(0).getId()); inOrder.verify(interviewWorkflowHandlerMock).notifyInvitation(interview); inOrder.verify(notificationServiceMock).sendNotificationWithFlush(expectedNotification, EMAIL); inOrder.verifyNoMoreInteractions(); }
InterviewAllocationServiceImpl implements InterviewAllocationService { @Override public ServiceResult<List<InterviewApplicationResource>> getUnallocatedApplicationsById(List<Long> applicationIds) { return serviceSuccess(interviewRepository.findAllNotified(applicationIds)); } @Override ServiceResult<InterviewAcceptedAssessorsPageResource> getInterviewAcceptedAssessors(long competitionId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getUnallocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<InterviewApplicationPageResource> getAllocatedApplications(long competitionId, long assessorUserId, Pageable pageable); @Override ServiceResult<List<InterviewResource>> getAllocatedApplicationsByAssessorId(long competitionId, long assessorUserId); @Override ServiceResult<List<InterviewApplicationResource>> getUnallocatedApplicationsById(List<Long> applicationIds); @Override ServiceResult<List<Long>> getUnallocatedApplicationIds(long competitionId, long assessorId); @Override ServiceResult<AssessorInvitesToSendResource> getInviteToSend(long competitionId, long assessorId); @Override @Transactional ServiceResult<Void> unallocateApplication(long assessorId, long applicationId); @Override @Transactional ServiceResult<Void> notifyAllocation(InterviewNotifyAllocationResource interviewNotifyAllocationResource); }
@Test public void getUnallocatedApplicationsById() { Long[] applicationIds = {1L, 2L}; List<InterviewApplicationResource> expectedInterviewApplications = newInterviewApplicationResource().build(2); when(interviewRepositoryMock.findAllNotified(asList(applicationIds))).thenReturn(expectedInterviewApplications); List<InterviewApplicationResource> actualInterviewApplications = service.getUnallocatedApplicationsById(asList(applicationIds)).getSuccess(); assertEquals(expectedInterviewApplications, actualInterviewApplications); verify(interviewRepositoryMock, only()).findAllNotified(asList(applicationIds)); }
InterviewInviteServiceImpl extends InviteService<InterviewInvite> implements InterviewInviteService { @Override public ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable) { final Page<AssessmentParticipant> pagedResult = assessmentParticipantRepository.findParticipantsNotOnInterviewPanel(competitionId, pageable); return serviceSuccess(new AvailableAssessorPageResource( pagedResult.getTotalElements(), pagedResult.getTotalPages(), simpleMap(pagedResult.getContent(), availableAssessorMapper::mapToResource), pagedResult.getNumber(), pagedResult.getSize() )); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId, Pageable pageable, List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<InterviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<InterviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); }
@Test public void getAvailableAssessors() { long competitionId = 1L; int page = 1; int pageSize = 1; List<InnovationAreaResource> innovationAreaResources = newInnovationAreaResource() .withName("Emerging Tech and Industries") .build(1); List<AvailableAssessorResource> assessorItems = newAvailableAssessorResource() .withId(4L, 8L) .withName("Jeremy Alufson", "Felix Wilson") .withCompliant(TRUE) .withEmail("[email protected]", "[email protected]") .withBusinessType(BUSINESS, ACADEMIC) .withInnovationAreas(innovationAreaResources) .build(2); AvailableAssessorPageResource expected = newAvailableAssessorPageResource() .withContent(assessorItems) .withSize(pageSize) .withNumber(page) .withTotalPages(2) .withTotalElements(2L) .build(); InnovationArea innovationArea = newInnovationArea() .withName("Emerging Tech and Industries") .build(); List<Profile> profile = newProfile() .withSkillsAreas("Java", "Javascript") .withInnovationArea(innovationArea) .withBusinessType(BUSINESS, ACADEMIC) .withAgreementSignedDate(now()) .build(2); List<User> assessors = newUser() .withId(4L, 8L) .withFirstName("Jeremy", "Felix") .withLastName("Alufson", "Wilson") .withEmailAddress("[email protected]", "[email protected]") .withAffiliations(newAffiliation() .withAffiliationType(EMPLOYER) .withOrganisation("Hive IT") .withPosition("Software Developer") .withExists(true) .build(1)) .withProfileId(profile.get(0).getId(), profile.get(1).getId()) .build(2); List<AssessmentParticipant> participants = newAssessmentParticipant() .withUser(assessors.get(0), assessors.get(1)) .build(2); Pageable pageable = PageRequest.of(page, pageSize, new Sort(ASC, "firstName")); Page<AssessmentParticipant> expectedPage = new PageImpl<>(participants, pageable, 2L); when(assessmentParticipantRepositoryMock.findParticipantsNotOnInterviewPanel(competitionId, pageable)) .thenReturn(expectedPage); when(availableAssessorMapper.mapToResource(participants.get(0))) .thenReturn(assessorItems.get(0)); when(availableAssessorMapper.mapToResource(participants.get(1))) .thenReturn(assessorItems.get(1)); AvailableAssessorPageResource actual = service.getAvailableAssessors(competitionId, pageable).getSuccess(); verify(assessmentParticipantRepositoryMock).findParticipantsNotOnInterviewPanel(competitionId, pageable); verify(availableAssessorMapper).mapToResource(participants.get(0)); verify(availableAssessorMapper).mapToResource(participants.get(1)); assertEquals(expected.getNumber(), actual.getNumber()); assertEquals(expected.getSize(), actual.getSize()); assertEquals(expected.getTotalElements(), actual.getTotalElements()); assertEquals(expected.getTotalPages(), actual.getTotalPages()); assertEquals(expected.getContent(), actual.getContent()); } @Test public void getAvailableAssessors_empty() { long competitionId = 1L; int page = 0; int pageSize = 20; Pageable pageable = PageRequest.of(page, pageSize, new Sort(ASC, "firstName")); Page<AssessmentParticipant> assessorPage = new PageImpl<>(emptyList(), pageable, 0); when(assessmentParticipantRepositoryMock.findParticipantsNotOnInterviewPanel(competitionId, pageable)) .thenReturn(assessorPage); AvailableAssessorPageResource result = service.getAvailableAssessors(competitionId, pageable).getSuccess(); verify(assessmentParticipantRepositoryMock).findParticipantsNotOnInterviewPanel(competitionId, pageable); assertEquals(page, result.getNumber()); assertEquals(pageSize, result.getSize()); assertEquals(0, result.getTotalElements()); assertEquals(0, result.getTotalPages()); assertEquals(emptyList(), result.getContent()); }
InterviewInviteServiceImpl extends InviteService<InterviewInvite> implements InterviewInviteService { @Override public ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId) { List<AssessmentParticipant> result = assessmentParticipantRepository.findParticipantsNotOnInterviewPanel(competitionId); return serviceSuccess(simpleMap(result, competitionParticipant -> competitionParticipant.getUser().getId())); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId, Pageable pageable, List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<InterviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<InterviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); }
@Test public void getAvailableAssessorIds() { long competitionId = 1L; InnovationArea innovationArea = newInnovationArea() .withName("Emerging Tech and Industries") .build(); List<Long> expectedAssessorIds = asList(4L, 8L); List<Profile> profiles = newProfile() .withSkillsAreas("Java", "Javascript") .withInnovationArea(innovationArea) .withBusinessType(BUSINESS, ACADEMIC) .withAgreementSignedDate(now()) .build(2); List<User> assessorUsers = newUser() .withId(expectedAssessorIds.get(0), expectedAssessorIds.get(1)) .withFirstName("Jeremy", "Felix") .withLastName("Alufson", "Wilson") .withEmailAddress("[email protected]", "[email protected]") .withAffiliations(newAffiliation() .withAffiliationType(EMPLOYER) .withOrganisation("Hive IT") .withPosition("Software Developer") .withExists(true) .build(1)) .withProfileId(profiles.get(0).getId(), profiles.get(1).getId()) .build(2); List<AssessmentParticipant> participants = newAssessmentParticipant() .withUser(assessorUsers.get(0), assessorUsers.get(1)) .build(2); when(assessmentParticipantRepositoryMock.findParticipantsNotOnInterviewPanel(competitionId)) .thenReturn(participants); List<Long> actualAssessorIds = service.getAvailableAssessorIds(competitionId).getSuccess(); verify(assessmentParticipantRepositoryMock).findParticipantsNotOnInterviewPanel(competitionId); assertEquals(expectedAssessorIds, actualAssessorIds); }
UserPermissionRules { @PermissionRule(value = "READ", description = "Any user can view themselves") public boolean anyUserCanViewThemselves(UserResource userToView, UserResource user) { return userToView.getId().equals(user.getId()); } @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "An internal user can invite a monitoring officer and create the pending user associated.") boolean compAdminProjectFinanceCanCreateMonitoringOfficer(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserRegistrationResource userToCreate, UserResource user); @PermissionRule(value = "VERIFY", description = "A System Registration User can send a new User a verification link by e-mail") boolean systemRegistrationUserCanSendUserVerificationEmail(UserResource userToSendVerificationEmail, UserResource user); @PermissionRule(value = "READ", description = "Any user can view themselves") boolean anyUserCanViewThemselves(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Internal users can view everyone") boolean internalUsersCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can view users in competitions they are assigned to") boolean stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Competition finance users can view users in competitions they are assigned to") boolean competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can view users in projects they are assigned to") boolean monitoringOfficersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ_USER_ORGANISATION", description = "Internal support users can view all users and associated organisations") boolean internalUsersCanViewUserOrganisation(UserOrganisationResource userToView, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "IFS admins can update all users email addresses") boolean ifsAdminCanUpdateAllEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "Support users can update external users email addresses ") boolean supportCanUpdateExternalUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "System Maintenance update all users email addresses") boolean systemMaintenanceUserCanUpdateUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ_INTERNAL", description = "Administrators can view internal users") boolean internalUsersCanViewEveryone(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Support users and administrators can view external users") boolean supportUsersCanViewExternalUsers(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "The System Registration user can view everyone") boolean systemRegistrationUserCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Comp admins and project finance can view assessors") boolean compAdminAndProjectFinanceCanViewAssessors(UserPageResource usersToView, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewOtherConsortiumMembers(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewConsortiumUsersOnApplicationsTheyAreAssessing(UserResource userToView, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "A User should be able to change their own password") boolean usersCanChangeTheirOwnPassword(UserResource userToUpdate, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "The System Registration user should be able to change passwords on behalf of other Users") boolean systemRegistrationUserCanChangePasswordsForUsers(UserResource userToUpdate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A System Registration User can activate Users") boolean systemRegistrationUserCanActivateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "UPDATE", description = "A User can update their own profile") boolean usersCanUpdateTheirOwnProfiles(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE", description = "An admin user can update user details to assign monitoring officers") boolean adminsCanUpdateUserDetails(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile skills") boolean usersCanViewTheirOwnProfileSkills(ProfileSkillsResource profileSkills, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile agreement") boolean usersCanViewTheirOwnProfileAgreement(ProfileAgreementResource profileAgreementResource, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own affiliations") boolean usersCanViewTheirOwnAffiliations(AffiliationResource affiliation, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A user can read their own profile") boolean usersCanViewTheirOwnProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A ifs admin user can read any user's profile") boolean ifsAdminCanViewAnyUsersProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as Comp Admin and Exec can read the user's profile status") boolean usersAndCompAdminCanViewProfileStatus(UserProfileStatusResource profileStatus, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own role") boolean usersCanViewTheirOwnProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the process role of others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewTheProcessRolesOfOtherConsortiumMembers(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Project managers and partners can view the process role for the same organisation") boolean projectPartnersCanViewTheProcessRolesWithinSameApplication(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as internal users can read the user's process role") boolean usersAndInternalUsersCanViewProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the process roles of members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewTheProcessRolesOfConsortiumUsersOnApplicationsTheyAreAssessing(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "CHECK_USER_APPLICATION", description = "The user can check if they have an application for the competition") boolean userCanCheckTheyHaveApplicationForCompetition(UserResource userToCheck, UserResource user); @PermissionRule(value = "EDIT_INTERNAL_USER", description = "Only an IFS Administrator can edit an internal user") boolean ifsAdminCanEditInternalUser(final UserResource userToEdit, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "IFS Administrator can deactivate Users") boolean ifsAdminCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "A Support user can deactivate external Users") boolean supportUserCanDeactivateExternalUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "System Maintenance can deactivate Users") boolean systemMaintenanceUserCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "IFS Administrator can reactivate Users") boolean ifsAdminCanReactivateUsers(UserResource userToReactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A Support user can reactivate external Users") boolean supportUserCanReactivateExternalUsers(UserResource userToActivate, UserResource user); @PermissionRule(value = "AGREE_TERMS", description = "A user can accept the site terms and conditions") boolean usersCanAgreeSiteTermsAndConditions(UserResource userToUpdate, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An assessor can request applicant role") boolean assessorCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant monitoring officer role") boolean isGrantingMonitoringOfficerRoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant a KTA role") boolean isGrantingKTARoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An stakeholder can request applicant role") boolean stakeholderCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An monitoring officer can request applicant role") boolean monitoringOfficerCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "CAN_VIEW_OWN_DASHBOARD", description = "User is requesting own dashboard") boolean isViewingOwnDashboard(UserResource userToView, UserResource user); }
@Test public void anyoneCanViewThemselves() { allGlobalRoleUsers.forEach(user -> allGlobalRoleUsers.forEach(otherUser -> { if (user.equals(otherUser)) { assertTrue(rules.anyUserCanViewThemselves(otherUser, user)); } else { assertFalse(rules.anyUserCanViewThemselves(otherUser, user)); } })); }
InterviewInviteServiceImpl extends InviteService<InterviewInvite> implements InterviewInviteService { @Override public ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable) { Page<InterviewInvite> pagedResult = interviewInviteRepository.getByCompetitionIdAndStatus(competitionId, CREATED, pageable); List<AssessorCreatedInviteResource> createdInvites = simpleMap( pagedResult.getContent(), assessorCreatedInviteMapper::mapToResource ); return serviceSuccess(new AssessorCreatedInvitePageResource( pagedResult.getTotalElements(), pagedResult.getTotalPages(), createdInvites, pagedResult.getNumber(), pagedResult.getSize() )); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId, Pageable pageable, List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<InterviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<InterviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); }
@Test public void getCreatedInvites() { long competitionId = 1L; InnovationArea innovationArea = newInnovationArea().build(); InnovationAreaResource innovationAreaResource = newInnovationAreaResource() .withId(2L) .withName("Earth Observation") .build(); List<InnovationAreaResource> innovationAreaList = singletonList(innovationAreaResource); Profile profile1 = newProfile() .withSkillsAreas("Java") .withAgreementSignedDate(now()) .withInnovationArea(innovationArea) .build(); User compliantUser = newUser() .withAffiliations(newAffiliation() .withAffiliationType(EMPLOYER) .withOrganisation("Hive IT") .withPosition("Software Developer") .withExists(true) .build(1)) .withProfileId(profile1.getId()) .build(); Profile profile2 = newProfile() .withSkillsAreas() .withAgreementSignedDate(now()) .build(); User nonCompliantUserNoSkills = newUser() .withAffiliations(newAffiliation() .withAffiliationType(EMPLOYER) .withOrganisation("Hive IT") .withPosition("Software Developer") .withExists(true) .build(1)) .withProfileId(profile2.getId()) .build(); Profile profile3 = newProfile() .withSkillsAreas("Java") .withAgreementSignedDate(now()) .build(); User nonCompliantUserNoAffiliations = newUser() .withAffiliations() .withProfileId(profile3.getId()) .build(); Profile profile4 = newProfile() .withSkillsAreas("Java") .withAgreementSignedDate() .build(); User nonCompliantUserNoAgreement = newUser() .withAffiliations(newAffiliation() .withAffiliationType(EMPLOYER) .withOrganisation("Hive IT") .withPosition("Software Developer") .withExists(true) .build(1)) .withProfileId(profile4.getId()) .build(); List<InterviewInvite> existingUserInvites = newInterviewInvite() .withId(1L, 2L, 3L, 4L) .withName("John Barnes", "Dave Smith", "Richard Turner", "Oliver Romero") .withEmail("[email protected]", "[email protected]", "[email protected]", "[email protected]") .withUser(compliantUser, nonCompliantUserNoSkills, nonCompliantUserNoAffiliations, nonCompliantUserNoAgreement) .build(4); List<AssessorCreatedInviteResource> expectedInvites = newAssessorCreatedInviteResource() .withId( compliantUser.getId(), nonCompliantUserNoSkills.getId(), nonCompliantUserNoAffiliations.getId(), nonCompliantUserNoAgreement.getId() ) .withInviteId(1L, 2L, 3L, 4L) .withName("John Barnes", "Dave Smith", "Richard Turner", "Oliver Romero") .withInnovationAreas(innovationAreaList, emptyList(), emptyList(), emptyList()) .withCompliant(true, false, false, false) .withEmail("[email protected]", "[email protected]", "[email protected]", "[email protected]") .build(4); long totalElements = 100L; Pageable pageable = PageRequest.of(0, 20); Page<InterviewInvite> page = new PageImpl<>(existingUserInvites, pageable, totalElements); when(interviewInviteRepositoryMock.getByCompetitionIdAndStatus( competitionId, CREATED, pageable )) .thenReturn(page); when(assessorCreatedInviteMapperMock.mapToResource(isA(InterviewInvite.class))).thenReturn( expectedInvites.get(0), expectedInvites.get(1), expectedInvites.get(2), expectedInvites.get(3) ); AssessorCreatedInvitePageResource actual = service.getCreatedInvites(competitionId, pageable).getSuccess(); assertEquals(totalElements, actual.getTotalElements()); assertEquals(5, actual.getTotalPages()); assertEquals(expectedInvites, actual.getContent()); assertEquals(0, actual.getNumber()); assertEquals(20, actual.getSize()); InOrder inOrder = inOrder(interviewInviteRepositoryMock, assessorCreatedInviteMapperMock); inOrder.verify(interviewInviteRepositoryMock) .getByCompetitionIdAndStatus(competitionId, CREATED, pageable); inOrder.verify(assessorCreatedInviteMapperMock, times(4)) .mapToResource(isA(InterviewInvite.class)); inOrder.verifyNoMoreInteractions(); }
InterviewInviteServiceImpl extends InviteService<InterviewInvite> implements InterviewInviteService { @Override public ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites) { return serviceSuccess(mapWithIndex(stagedInvites, (i, invite) -> getUser(invite.getUserId()).andOnSuccess(user -> getByEmailAndCompetition(user.getEmail(), invite.getCompetitionId()).andOnFailure(() -> inviteUserToCompetition(user, invite.getCompetitionId()) )))).andOnSuccessReturnVoid(); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId, Pageable pageable, List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<InterviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<InterviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); }
@Test public void inviteUsers_existing() throws Exception { List<User> existingUsers = newUser() .withEmailAddress("[email protected]", "[email protected]") .withFirstName("fred", "joe") .withLastName("smith", "brown") .build(2); Competition competition = newCompetition() .withName("competition name") .build(); List<ExistingUserStagedInviteResource> existingAssessors = newExistingUserStagedInviteResource() .withUserId(existingUsers.get(0).getId(), existingUsers.get(1).getId()) .withCompetitionId(competition.getId()) .build(2); when(userRepositoryMock.findById(existingUsers.get(0).getId())).thenReturn(Optional.of(existingUsers.get(0))); when(userRepositoryMock.findById(existingUsers.get(1).getId())).thenReturn(Optional.of(existingUsers.get(1))); when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition)); when(interviewInviteRepositoryMock.save(isA(InterviewInvite.class))).thenReturn(new InterviewInvite()); ServiceResult<Void> serviceResult = service.inviteUsers(existingAssessors); assertTrue(serviceResult.isSuccess()); InOrder inOrder = inOrder(userRepositoryMock, competitionRepositoryMock, interviewInviteRepositoryMock); inOrder.verify(userRepositoryMock).findById(existingAssessors.get(0).getUserId()); inOrder.verify(competitionRepositoryMock).findById(competition.getId()); inOrder.verify(interviewInviteRepositoryMock).save(createInviteExpectations(existingUsers.get(0).getName(), existingUsers.get(0).getEmail(), CREATED, competition)); inOrder.verify(userRepositoryMock).findById(existingAssessors.get(1).getUserId()); inOrder.verify(competitionRepositoryMock).findById(competition.getId()); inOrder.verify(interviewInviteRepositoryMock).save(createInviteExpectations(existingUsers.get(1).getName(), existingUsers.get(1).getEmail(), CREATED, competition)); inOrder.verifyNoMoreInteractions(); }
InterviewInviteServiceImpl extends InviteService<InterviewInvite> implements InterviewInviteService { @Override public ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId) { return getCompetition(competitionId).andOnSuccess(competition -> { List<InterviewInvite> invites = interviewInviteRepository.getByCompetitionIdAndStatus(competition.getId(), CREATED); List<String> recipients = simpleMap(invites, InterviewInvite::getName); recipients.sort(String::compareTo); return serviceSuccess(new AssessorInvitesToSendResource( recipients, competition.getId(), competition.getName(), getInvitePreviewContent(competition) )); }); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId, Pageable pageable, List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<InterviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<InterviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); }
@Test public void getAllInvitesToSend() throws Exception { List<String> emails = asList("[email protected]", "[email protected]"); List<String> names = asList("John Barnes", "Peter Jones"); ZonedDateTime acceptsDate = of(2016, 12, 20, 12, 0,0,0, ZoneId.systemDefault()); ZonedDateTime deadlineDate = of(2017, 1, 17, 12, 0,0,0, ZoneId.systemDefault()); Competition competition = newCompetition() .withName("Competition in Assessor Panel") .withAssessorAcceptsDate(acceptsDate) .withAssessorDeadlineDate(deadlineDate) .build(); List<InterviewInvite> invites = newInterviewInvite() .withCompetition(competition) .withEmail(emails.get(0), emails.get(1)) .withHash(Invite.generateInviteHash()) .withName(names.get(0), names.get(1)) .withStatus(CREATED) .withUser(new User()) .build(2); Map<String, Object> expectedNotificationArguments = asMap( "competitionName", competition.getName() ); NotificationTarget notificationTarget = new UserNotificationTarget("", ""); String templatePath = PREVIEW_TEMPLATES_PATH + "invite_assessors_to_interview_panel_text.txt"; when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition)); when(interviewInviteRepositoryMock.getByCompetitionIdAndStatus(competition.getId(), CREATED)).thenReturn(invites); when(notificationTemplateRendererMock.renderTemplate(systemNotificationSourceMock, notificationTarget, templatePath, expectedNotificationArguments)).thenReturn(serviceSuccess("content")); AssessorInvitesToSendResource expectedAssessorInviteToSendResource = newAssessorInvitesToSendResource() .withContent("content") .withCompetitionId(competition.getId()) .withCompetitionName(competition.getName()) .withRecipients(names) .build(); AssessorInvitesToSendResource result = service.getAllInvitesToSend(competition.getId()).getSuccess(); assertEquals(expectedAssessorInviteToSendResource, result); InOrder inOrder = inOrder(competitionRepositoryMock, interviewInviteRepositoryMock, notificationTemplateRendererMock); inOrder.verify(competitionRepositoryMock).findById(competition.getId()); inOrder.verify(interviewInviteRepositoryMock).getByCompetitionIdAndStatus(competition.getId(), CREATED); inOrder.verify(notificationTemplateRendererMock).renderTemplate(systemNotificationSourceMock, notificationTarget, templatePath, expectedNotificationArguments); inOrder.verifyNoMoreInteractions(); }
InterviewInviteServiceImpl extends InviteService<InterviewInvite> implements InterviewInviteService { @Override public ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds) { return getCompetition(competitionId).andOnSuccess(competition -> { List<InterviewInvite> invites = interviewInviteRepository.getByIdIn(inviteIds); List<String> recipients = simpleMap(invites, InterviewInvite::getName); recipients.sort(String::compareTo); return serviceSuccess(new AssessorInvitesToSendResource( recipients, competition.getId(), competition.getName(), getInvitePreviewContent(competition) )); }); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId, Pageable pageable, List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<InterviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<InterviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); }
@Test public void getAllInvitesToResend() throws Exception { List<String> emails = asList("[email protected]", "[email protected]"); List<String> names = asList("John Barnes", "Peter Jones"); List<Long> inviteIds = asList(1L, 2L); ZonedDateTime acceptsDate = of(2016, 12, 20, 12, 0,0,0, ZoneId.systemDefault()); ZonedDateTime deadlineDate = of(2017, 1, 17, 12, 0,0,0, ZoneId.systemDefault()); Competition competition = newCompetition() .withName("my competition") .withAssessorAcceptsDate(acceptsDate) .withAssessorDeadlineDate(deadlineDate) .build(); List<InterviewInvite> invites = newInterviewInvite() .withCompetition(competition) .withEmail(emails.get(0), emails.get(1)) .withHash(Invite.generateInviteHash()) .withName(names.get(0), names.get(1)) .withStatus(SENT) .withUser(newUser()) .build(2); Map<String, Object> expectedNotificationArguments = asMap( "competitionName", competition.getName() ); NotificationTarget notificationTarget = new UserNotificationTarget("", ""); String templatePath = PREVIEW_TEMPLATES_PATH + "invite_assessors_to_interview_panel_text.txt"; when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition)); when(interviewInviteRepositoryMock.getByIdIn(inviteIds)).thenReturn(invites); when(notificationTemplateRendererMock.renderTemplate(systemNotificationSourceMock, notificationTarget, templatePath, expectedNotificationArguments)).thenReturn(serviceSuccess("content")); AssessorInvitesToSendResource expectedAssessorInviteToSendResource = newAssessorInvitesToSendResource() .withContent("content") .withCompetitionId(competition.getId()) .withCompetitionName(competition.getName()) .withRecipients(names) .build(); AssessorInvitesToSendResource result = service.getAllInvitesToResend(competition.getId(), inviteIds).getSuccess(); assertEquals(expectedAssessorInviteToSendResource, result); InOrder inOrder = inOrder(competitionRepositoryMock, interviewInviteRepositoryMock, notificationTemplateRendererMock); inOrder.verify(competitionRepositoryMock).findById(competition.getId()); inOrder.verify(interviewInviteRepositoryMock).getByIdIn(inviteIds); inOrder.verify(notificationTemplateRendererMock).renderTemplate(systemNotificationSourceMock, notificationTarget, templatePath, expectedNotificationArguments); inOrder.verifyNoMoreInteractions(); }
InterviewInviteServiceImpl extends InviteService<InterviewInvite> implements InterviewInviteService { @Override public ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId, Pageable pageable, List<ParticipantStatus> statuses) { Page<InterviewParticipant> pagedResult = interviewParticipantRepository.getInterviewPanelAssessorsByCompetitionAndStatusContains( competitionId, statuses, pageable); List<AssessorInviteOverviewResource> inviteOverviews = simpleMap( pagedResult.getContent(), assessorInviteOverviewMapper::mapToResource ); return serviceSuccess(new AssessorInviteOverviewPageResource( pagedResult.getTotalElements(), pagedResult.getTotalPages(), inviteOverviews, pagedResult.getNumber(), pagedResult.getSize() )); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId, Pageable pageable, List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<InterviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<InterviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); }
@Test public void getInvitationOverview() throws Exception { long competitionId = 1L; Pageable pageable = PageRequest.of(0, 5); List<InterviewParticipant> expectedParticipants = newInterviewParticipant() .withInvite( newInterviewInvite() .withName("Name 1", "Name 2", "Name 3", "Name 4", "Name 5") .withSentOn(now()) .withStatus(SENT) .buildArray(5, InterviewInvite.class) ) .withStatus(PENDING) .build(5); Page<InterviewParticipant> pageResult = new PageImpl<>(expectedParticipants, pageable, 10); when(interviewParticipantRepositoryMock.getInterviewPanelAssessorsByCompetitionAndStatusContains( competitionId, singletonList(PENDING), pageable )) .thenReturn(pageResult); List<AssessorInviteOverviewResource> overviewResources = newAssessorInviteOverviewResource() .withName("Name 1", "Name 2", "Name 3", "Name 4", "Name 5") .build(5); when(assessorInviteOverviewMapperMock.mapToResource(isA(InterviewParticipant.class))) .thenReturn( overviewResources.get(0), overviewResources.get(1), overviewResources.get(2), overviewResources.get(3), overviewResources.get(4) ); ServiceResult<AssessorInviteOverviewPageResource> result = service.getInvitationOverview(competitionId, pageable, singletonList(PENDING)); verify(interviewParticipantRepositoryMock) .getInterviewPanelAssessorsByCompetitionAndStatusContains(competitionId, singletonList(PENDING), pageable); verify(assessorInviteOverviewMapperMock, times(5)) .mapToResource(isA(InterviewParticipant.class)); assertTrue(result.isSuccess()); AssessorInviteOverviewPageResource pageResource = result.getSuccess(); assertEquals(0, pageResource.getNumber()); assertEquals(5, pageResource.getSize()); assertEquals(2, pageResource.getTotalPages()); assertEquals(10, pageResource.getTotalElements()); List<AssessorInviteOverviewResource> content = pageResource.getContent(); assertEquals("Name 1", content.get(0).getName()); assertEquals("Name 2", content.get(1).getName()); assertEquals("Name 3", content.get(2).getName()); assertEquals("Name 4", content.get(3).getName()); assertEquals("Name 5", content.get(4).getName()); content.forEach(this::assertNotExistingAssessorUser); }
InterviewInviteServiceImpl extends InviteService<InterviewInvite> implements InterviewInviteService { @Override public ServiceResult<Void> deleteInvite(String email, long competitionId) { return getByEmailAndCompetition(email, competitionId).andOnSuccess(this::deleteInvite); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId, Pageable pageable, List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<InterviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<InterviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); }
@Test public void deleteInvite() { String email = "[email protected]"; long competitionId = 11L; InterviewInvite interviewInvite = newInterviewInvite() .withStatus(CREATED) .build(); when(interviewInviteRepositoryMock.getByEmailAndCompetitionId(email, competitionId)).thenReturn(interviewInvite); service.deleteInvite(email, competitionId).getSuccess(); InOrder inOrder = inOrder(interviewInviteRepositoryMock); inOrder.verify(interviewInviteRepositoryMock).getByEmailAndCompetitionId(email, competitionId); inOrder.verify(interviewInviteRepositoryMock).delete(interviewInvite); inOrder.verifyNoMoreInteractions(); } @Test public void deleteInvite_sent() { String email = "[email protected]"; long competitionId = 11L; InterviewInvite interviewInvite = newInterviewInvite() .withStatus(SENT) .build(); when(interviewInviteRepositoryMock.getByEmailAndCompetitionId(email, competitionId)).thenReturn(interviewInvite); ServiceResult<Void> serviceResult = service.deleteInvite(email, competitionId); assertTrue(serviceResult.isFailure()); verify(interviewInviteRepositoryMock).getByEmailAndCompetitionId(email, competitionId); verifyNoMoreInteractions(interviewInviteRepositoryMock); }
InterviewInviteServiceImpl extends InviteService<InterviewInvite> implements InterviewInviteService { @Override public ServiceResult<Void> deleteAllInvites(long competitionId) { return find(competitionRepository.findById(competitionId), notFoundError(Competition.class, competitionId)) .andOnSuccessReturnVoid(competition -> interviewInviteRepository.deleteByCompetitionIdAndStatus(competition.getId(), CREATED)); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId, Pageable pageable, List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<InterviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<InterviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); }
@Test public void deleteAllInvites() { long competitionId = 1L; when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.of(newCompetition().build())); assertTrue(service.deleteAllInvites(competitionId).isSuccess()); verify(competitionRepositoryMock).findById(competitionId); } @Test public void deleteAllInvites_noCompetition() { long competitionId = 1L; when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.empty()); assertFalse(service.deleteAllInvites(competitionId).isSuccess()); verify(competitionRepositoryMock).findById(competitionId); }
InterviewInviteServiceImpl extends InviteService<InterviewInvite> implements InterviewInviteService { @Override public ServiceResult<InterviewInviteResource> openInvite(String inviteHash) { return getByHashIfOpen(inviteHash) .andOnSuccessReturn(this::openInvite) .andOnSuccessReturn(interviewInviteMapper::mapToResource); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId, Pageable pageable, List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<InterviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<InterviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); }
@Test public void openInvite() { Milestone milestone = newMilestone() .withType(PANEL_DATE) .withDate(now().plusDays(1)) .build(); InterviewInvite interviewInvite = setUpAssessmentInterviewPanelInvite(newCompetition() .withName("my competition") .withMilestones(singletonList(milestone)) .build(), SENT); when(interviewInviteRepositoryMock.getByHash(isA(String.class))).thenReturn(interviewInvite); ServiceResult<InterviewInviteResource> inviteServiceResult = service.openInvite(INVITE_HASH); assertTrue(inviteServiceResult.isSuccess()); InterviewInviteResource interviewInviteResource = inviteServiceResult.getSuccess(); assertEquals("my competition", interviewInviteResource.getCompetitionName()); InOrder inOrder = inOrder(interviewInviteRepositoryMock, interviewInviteMapperMock); inOrder.verify(interviewInviteRepositoryMock).getByHash(INVITE_HASH); inOrder.verify(interviewInviteRepositoryMock).save(isA(InterviewInvite.class)); inOrder.verify(interviewInviteMapperMock).mapToResource(isA(InterviewInvite.class)); inOrder.verifyNoMoreInteractions(); }
UserPermissionRules { @PermissionRule(value = "READ", description = "Internal users can view everyone") public boolean internalUsersCanViewEveryone(UserResource userToView, UserResource user) { return isInternal(user); } @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "An internal user can invite a monitoring officer and create the pending user associated.") boolean compAdminProjectFinanceCanCreateMonitoringOfficer(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserRegistrationResource userToCreate, UserResource user); @PermissionRule(value = "VERIFY", description = "A System Registration User can send a new User a verification link by e-mail") boolean systemRegistrationUserCanSendUserVerificationEmail(UserResource userToSendVerificationEmail, UserResource user); @PermissionRule(value = "READ", description = "Any user can view themselves") boolean anyUserCanViewThemselves(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Internal users can view everyone") boolean internalUsersCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can view users in competitions they are assigned to") boolean stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Competition finance users can view users in competitions they are assigned to") boolean competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can view users in projects they are assigned to") boolean monitoringOfficersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ_USER_ORGANISATION", description = "Internal support users can view all users and associated organisations") boolean internalUsersCanViewUserOrganisation(UserOrganisationResource userToView, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "IFS admins can update all users email addresses") boolean ifsAdminCanUpdateAllEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "Support users can update external users email addresses ") boolean supportCanUpdateExternalUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "System Maintenance update all users email addresses") boolean systemMaintenanceUserCanUpdateUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ_INTERNAL", description = "Administrators can view internal users") boolean internalUsersCanViewEveryone(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Support users and administrators can view external users") boolean supportUsersCanViewExternalUsers(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "The System Registration user can view everyone") boolean systemRegistrationUserCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Comp admins and project finance can view assessors") boolean compAdminAndProjectFinanceCanViewAssessors(UserPageResource usersToView, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewOtherConsortiumMembers(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewConsortiumUsersOnApplicationsTheyAreAssessing(UserResource userToView, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "A User should be able to change their own password") boolean usersCanChangeTheirOwnPassword(UserResource userToUpdate, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "The System Registration user should be able to change passwords on behalf of other Users") boolean systemRegistrationUserCanChangePasswordsForUsers(UserResource userToUpdate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A System Registration User can activate Users") boolean systemRegistrationUserCanActivateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "UPDATE", description = "A User can update their own profile") boolean usersCanUpdateTheirOwnProfiles(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE", description = "An admin user can update user details to assign monitoring officers") boolean adminsCanUpdateUserDetails(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile skills") boolean usersCanViewTheirOwnProfileSkills(ProfileSkillsResource profileSkills, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile agreement") boolean usersCanViewTheirOwnProfileAgreement(ProfileAgreementResource profileAgreementResource, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own affiliations") boolean usersCanViewTheirOwnAffiliations(AffiliationResource affiliation, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A user can read their own profile") boolean usersCanViewTheirOwnProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A ifs admin user can read any user's profile") boolean ifsAdminCanViewAnyUsersProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as Comp Admin and Exec can read the user's profile status") boolean usersAndCompAdminCanViewProfileStatus(UserProfileStatusResource profileStatus, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own role") boolean usersCanViewTheirOwnProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the process role of others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewTheProcessRolesOfOtherConsortiumMembers(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Project managers and partners can view the process role for the same organisation") boolean projectPartnersCanViewTheProcessRolesWithinSameApplication(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as internal users can read the user's process role") boolean usersAndInternalUsersCanViewProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the process roles of members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewTheProcessRolesOfConsortiumUsersOnApplicationsTheyAreAssessing(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "CHECK_USER_APPLICATION", description = "The user can check if they have an application for the competition") boolean userCanCheckTheyHaveApplicationForCompetition(UserResource userToCheck, UserResource user); @PermissionRule(value = "EDIT_INTERNAL_USER", description = "Only an IFS Administrator can edit an internal user") boolean ifsAdminCanEditInternalUser(final UserResource userToEdit, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "IFS Administrator can deactivate Users") boolean ifsAdminCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "A Support user can deactivate external Users") boolean supportUserCanDeactivateExternalUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "System Maintenance can deactivate Users") boolean systemMaintenanceUserCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "IFS Administrator can reactivate Users") boolean ifsAdminCanReactivateUsers(UserResource userToReactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A Support user can reactivate external Users") boolean supportUserCanReactivateExternalUsers(UserResource userToActivate, UserResource user); @PermissionRule(value = "AGREE_TERMS", description = "A user can accept the site terms and conditions") boolean usersCanAgreeSiteTermsAndConditions(UserResource userToUpdate, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An assessor can request applicant role") boolean assessorCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant monitoring officer role") boolean isGrantingMonitoringOfficerRoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant a KTA role") boolean isGrantingKTARoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An stakeholder can request applicant role") boolean stakeholderCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An monitoring officer can request applicant role") boolean monitoringOfficerCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "CAN_VIEW_OWN_DASHBOARD", description = "User is requesting own dashboard") boolean isViewingOwnDashboard(UserResource userToView, UserResource user); }
@Test public void internalUsersCanViewEveryone() { allGlobalRoleUsers.forEach(user -> allGlobalRoleUsers.forEach(otherUser -> { if (allInternalUsers.contains(user)) { assertTrue(rules.internalUsersCanViewEveryone(otherUser, user)); } else { assertFalse(rules.internalUsersCanViewEveryone(otherUser, user)); } })); } @Test public void internalUsersCanViewEveryoneUserPageResource() { ManageUserPageResource manageUserPageResource = new ManageUserPageResource(); allGlobalRoleUsers.forEach(user -> { if (user.equals(ifsAdminUser())) { assertTrue(rules.internalUsersCanViewEveryone(manageUserPageResource, user)); } else { assertFalse(rules.internalUsersCanViewEveryone(manageUserPageResource, user)); } }); }
InterviewInviteServiceImpl extends InviteService<InterviewInvite> implements InterviewInviteService { @Override public ServiceResult<Void> acceptInvite(String inviteHash) { return getParticipantByInviteHash(inviteHash) .andOnSuccess(InterviewInviteServiceImpl::accept) .andOnSuccessReturnVoid(); } @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToSend(long competitionId); @Override ServiceResult<AssessorInvitesToSendResource> getAllInvitesToResend(long competitionId, List<Long> inviteIds); @Override ServiceResult<Void> sendAllInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<Void> resendInvites(List<Long> inviteIds, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<AvailableAssessorPageResource> getAvailableAssessors(long competitionId, Pageable pageable); @Override ServiceResult<List<Long>> getAvailableAssessorIds(long competitionId); @Override ServiceResult<AssessorCreatedInvitePageResource> getCreatedInvites(long competitionId, Pageable pageable); @Override ServiceResult<Void> inviteUsers(List<ExistingUserStagedInviteResource> stagedInvites); @Override ServiceResult<AssessorInviteOverviewPageResource> getInvitationOverview(long competitionId, Pageable pageable, List<ParticipantStatus> statuses); @Override ServiceResult<List<Long>> getNonAcceptedAssessorInviteIds(long competitionId); @Override ServiceResult<List<InterviewParticipantResource>> getAllInvitesByUser(long userId); @Override ServiceResult<InterviewInviteResource> openInvite(String inviteHash); @Override ServiceResult<Void> acceptInvite(String inviteHash); @Override ServiceResult<Void> rejectInvite(String inviteHash); @Override ServiceResult<Boolean> checkUserExistsForInvite(String inviteHash); @Override ServiceResult<Void> deleteInvite(String email, long competitionId); @Override ServiceResult<Void> deleteAllInvites(long competitionId); }
@Test public void acceptInvite() { String openedInviteHash = "openedInviteHash"; Competition competition = newCompetition().build(); InterviewParticipant interviewParticipant = newInterviewParticipant() .withInvite(newInterviewInvite().withStatus(OPENED)) .withUser(newUser()) .withCompetition(competition) .build(); when(interviewParticipantRepositoryMock.getByInviteHash(openedInviteHash)).thenReturn(interviewParticipant); service.acceptInvite(openedInviteHash).getSuccess(); assertEquals(ParticipantStatus.ACCEPTED, interviewParticipant.getStatus()); InOrder inOrder = inOrder(interviewParticipantRepositoryMock); inOrder.verify(interviewParticipantRepositoryMock).getByInviteHash(openedInviteHash); inOrder.verifyNoMoreInteractions(); } @Test public void acceptInvite_existingApplicationsOnPanel() { String openedInviteHash = "openedInviteHash"; Competition competition = newCompetition().build(); InterviewParticipant interviewParticipant = newInterviewParticipant() .withInvite(newInterviewInvite().withStatus(OPENED)) .withUser(newUser()) .withCompetition(competition) .build(); when(interviewParticipantRepositoryMock.getByInviteHash(openedInviteHash)).thenReturn(interviewParticipant); service.acceptInvite(openedInviteHash).getSuccess(); assertEquals(ParticipantStatus.ACCEPTED, interviewParticipant.getStatus()); InOrder inOrder = inOrder(interviewParticipantRepositoryMock); inOrder.verify(interviewParticipantRepositoryMock).getByInviteHash(openedInviteHash); inOrder.verifyNoMoreInteractions(); }
InterviewResponseServiceImpl implements InterviewResponseService { @Override @Transactional(readOnly = true) public ServiceResult<FileEntryResource> findResponse(long applicationId) { return findAssignmentByApplicationId(applicationId).andOnSuccess(interviewAssignment -> ofNullable(interviewAssignment.getResponse()) .map(InterviewAssignmentResponseOutcome::getFileResponse) .map(FileEntry::getId) .map(fileId -> fileEntryService.findOne(fileId)) .orElse(serviceSuccess(null))); } @Override ServiceResult<Void> uploadResponse(String contentType, String contentLength, String originalFilename, long applicationId, HttpServletRequest request); @Override ServiceResult<Void> deleteResponse(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileAndContents> downloadResponse(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileEntryResource> findResponse(long applicationId); }
@Test public void findResponse() throws Exception { long applicationId = 1L; FileEntry fileEntry = newFileEntry().build(); InterviewAssignment interviewAssignment = newInterviewAssignment(). withResponse(newInterviewAssignmentResponseOutcome() .withFileResponse(fileEntry) .build() ).build(); FileEntryResource fileEntryResource = newFileEntryResource().build(); when(interviewAssignmentRepositoryMock.findOneByTargetId(applicationId)).thenReturn(interviewAssignment); when(fileEntryServiceMock.findOne(fileEntry.getId())).thenReturn(serviceSuccess(fileEntryResource)); FileEntryResource response = service.findResponse(applicationId).getSuccess(); assertEquals(fileEntryResource, response); }
InterviewResponseServiceImpl implements InterviewResponseService { @Override @Transactional(readOnly = true) public ServiceResult<FileAndContents> downloadResponse(long applicationId) { return findAssignmentByApplicationId(applicationId).andOnSuccess(interviewAssignment -> fileEntryService.findOne(interviewAssignment.getResponse().getFileResponse().getId()) .andOnSuccess(this::getFileAndContents)); } @Override ServiceResult<Void> uploadResponse(String contentType, String contentLength, String originalFilename, long applicationId, HttpServletRequest request); @Override ServiceResult<Void> deleteResponse(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileAndContents> downloadResponse(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileEntryResource> findResponse(long applicationId); }
@Test public void downloadResponse() throws Exception { final long applicationId = 1L; final long fileId = 2L; final FileEntry fileEntry = new FileEntry(fileId, "somefile.pdf", MediaType.APPLICATION_PDF, 1111L); InterviewAssignment interviewAssignment = newInterviewAssignment(). withResponse(newInterviewAssignmentResponseOutcome() .withFileResponse(fileEntry) .build() ).build(); FileEntryResource fileEntryResource = new FileEntryResource(); fileEntryResource.setId(fileId); when(interviewAssignmentRepositoryMock.findOneByTargetId(applicationId)).thenReturn(interviewAssignment); when(fileEntryServiceMock.findOne(fileId)).thenReturn(serviceSuccess(fileEntryResource)); final Supplier<InputStream> contentSupplier = () -> null; when(fileServiceMock.getFileByFileEntryId(fileEntry.getId())).thenReturn(ServiceResult.serviceSuccess(contentSupplier)); FileAndContents fileAndContents = service.downloadResponse(applicationId).getSuccess(); assertEquals(fileAndContents.getContentsSupplier(), contentSupplier); assertEquals(fileAndContents.getFileEntry(), fileEntryResource); }
InterviewResponseServiceImpl implements InterviewResponseService { @Override public ServiceResult<Void> deleteResponse(long applicationId) { return findAssignmentByApplicationId(applicationId).andOnSuccessReturnVoid(interviewAssignment -> interviewAssignmentWorkflowHandler.withdrawResponse(interviewAssignment) ); } @Override ServiceResult<Void> uploadResponse(String contentType, String contentLength, String originalFilename, long applicationId, HttpServletRequest request); @Override ServiceResult<Void> deleteResponse(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileAndContents> downloadResponse(long applicationId); @Override @Transactional(readOnly = true) ServiceResult<FileEntryResource> findResponse(long applicationId); }
@Test public void deleteResponse() throws Exception { final long applicationId = 1L; InterviewAssignment interviewAssignment = newInterviewAssignment() .build(); when(interviewAssignmentRepositoryMock.findOneByTargetId(applicationId)).thenReturn(interviewAssignment); when(interviewAssignmentWorkflowHandler.withdrawResponse(interviewAssignment)).thenReturn(true); ServiceResult<Void> response = service.deleteResponse(applicationId); assertTrue(response.isSuccess()); verify(interviewAssignmentWorkflowHandler).withdrawResponse(interviewAssignment); }
InterviewAssignmentServiceImpl implements InterviewAssignmentService { @Override @Transactional(readOnly = true) public ServiceResult<AvailableApplicationPageResource> getAvailableApplications(long competitionId, Pageable pageable) { final Page<Application> pagedResult = applicationRepository.findSubmittedApplicationsNotOnInterviewPanel(competitionId, pageable); return serviceSuccess(new AvailableApplicationPageResource( pagedResult.getTotalElements(), pagedResult.getTotalPages(), simpleMap(pagedResult.getContent(), this::mapToAvailableApplicationResource), pagedResult.getNumber(), pagedResult.getSize() )); } @Override @Transactional(readOnly = true) ServiceResult<AvailableApplicationPageResource> getAvailableApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<List<Long>> getAvailableApplicationIds(long competitionId); @Override ServiceResult<Void> assignApplications(List<StagedApplicationResource> stagedInvites); @Override ServiceResult<Void> unstageApplication(long applicationId); @Override ServiceResult<Void> unstageApplications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<Boolean> isApplicationAssigned(long applicationId); }
@Test public void getAvailableApplications() { Page<Application> expectedPage = new PageImpl<>(EXPECTED_AVAILABLE_APPLICATIONS, PAGE_REQUEST, TOTAL_APPLICATIONS); when(applicationRepositoryMock.findSubmittedApplicationsNotOnInterviewPanel(COMPETITION_ID, PAGE_REQUEST)).thenReturn(expectedPage); when(organisationRepositoryMock.findById(LEAD_ORGANISATION.getId())).thenReturn(Optional.of(LEAD_ORGANISATION)); AvailableApplicationPageResource availableApplicationPageResource = service.getAvailableApplications(COMPETITION_ID, PAGE_REQUEST).getSuccess(); assertPageRequestMatchesPageResource(PAGE_REQUEST, availableApplicationPageResource); assertEquals(TOTAL_APPLICATIONS, availableApplicationPageResource.getTotalElements()); assertAvailableApplicationResourcesMatch(LEAD_ORGANISATION, EXPECTED_AVAILABLE_APPLICATIONS, availableApplicationPageResource); InOrder inOrder = inOrder(applicationRepositoryMock, organisationRepositoryMock); inOrder.verify(applicationRepositoryMock).findSubmittedApplicationsNotOnInterviewPanel(COMPETITION_ID, PAGE_REQUEST); inOrder.verify(organisationRepositoryMock, times(TOTAL_APPLICATIONS)).findById(LEAD_ORGANISATION.getId()); inOrder.verifyNoMoreInteractions(); }
InterviewAssignmentServiceImpl implements InterviewAssignmentService { @Override @Transactional(readOnly = true) public ServiceResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(long competitionId, Pageable pageable) { final Page<InterviewAssignment> pagedResult = interviewAssignmentRepository.findByTargetCompetitionIdAndActivityState( competitionId, CREATED, pageable); return serviceSuccess(new InterviewAssignmentStagedApplicationPageResource( pagedResult.getTotalElements(), pagedResult.getTotalPages(), simpleMap(pagedResult.getContent(), this::mapToPanelCreatedInviteResource), pagedResult.getNumber(), pagedResult.getSize() )); } @Override @Transactional(readOnly = true) ServiceResult<AvailableApplicationPageResource> getAvailableApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<List<Long>> getAvailableApplicationIds(long competitionId); @Override ServiceResult<Void> assignApplications(List<StagedApplicationResource> stagedInvites); @Override ServiceResult<Void> unstageApplication(long applicationId); @Override ServiceResult<Void> unstageApplications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<Boolean> isApplicationAssigned(long applicationId); }
@Test public void getStagedApplications() { List<InterviewAssignment> expectedInterviewPanels = newInterviewAssignment() .withParticipant( newProcessRole() .withRole(Role.INTERVIEW_LEAD_APPLICANT) .withOrganisationId(LEAD_ORGANISATION.getId()) .build() ) .withTarget( newApplication() .build() ) .build(TOTAL_APPLICATIONS); Page<InterviewAssignment> expectedPage = new PageImpl<>(expectedInterviewPanels, PAGE_REQUEST, TOTAL_APPLICATIONS); when(interviewAssignmentRepositoryMock.findByTargetCompetitionIdAndActivityState( COMPETITION_ID, InterviewAssignmentState.CREATED, PAGE_REQUEST)).thenReturn(expectedPage); when(organisationRepositoryMock.findById(LEAD_ORGANISATION.getId())).thenReturn(Optional.of(LEAD_ORGANISATION)); InterviewAssignmentStagedApplicationPageResource stagedApplicationPageResource = service.getStagedApplications(COMPETITION_ID, PAGE_REQUEST).getSuccess(); assertPageRequestMatchesPageResource(PAGE_REQUEST, stagedApplicationPageResource); assertEquals(TOTAL_APPLICATIONS, stagedApplicationPageResource.getTotalElements()); assertEquals(expectedInterviewPanels.size(), stagedApplicationPageResource.getContent().size()); assertStagedApplicationResourcesMatch(LEAD_ORGANISATION, expectedInterviewPanels, stagedApplicationPageResource); InOrder inOrder = inOrder(interviewAssignmentRepositoryMock, organisationRepositoryMock); inOrder.verify(interviewAssignmentRepositoryMock) .findByTargetCompetitionIdAndActivityState(COMPETITION_ID, InterviewAssignmentState.CREATED, PAGE_REQUEST); inOrder.verify(organisationRepositoryMock, times(TOTAL_APPLICATIONS)).findById(LEAD_ORGANISATION.getId()); inOrder.verifyNoMoreInteractions(); }
InterviewAssignmentServiceImpl implements InterviewAssignmentService { @Override @Transactional(readOnly = true) public ServiceResult<List<Long>> getAvailableApplicationIds(long competitionId) { return serviceSuccess( simpleMap( applicationRepository.findSubmittedApplicationsNotOnInterviewPanel(competitionId), Application::getId ) ); } @Override @Transactional(readOnly = true) ServiceResult<AvailableApplicationPageResource> getAvailableApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<List<Long>> getAvailableApplicationIds(long competitionId); @Override ServiceResult<Void> assignApplications(List<StagedApplicationResource> stagedInvites); @Override ServiceResult<Void> unstageApplication(long applicationId); @Override ServiceResult<Void> unstageApplications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<Boolean> isApplicationAssigned(long applicationId); }
@Test public void getAvailableApplicationIds() { when(applicationRepositoryMock.findSubmittedApplicationsNotOnInterviewPanel(COMPETITION_ID)) .thenReturn(EXPECTED_AVAILABLE_APPLICATIONS); List<Long> availableApplicationIds = service.getAvailableApplicationIds(COMPETITION_ID).getSuccess(); assertEquals(simpleMap(EXPECTED_AVAILABLE_APPLICATIONS, Application::getId), availableApplicationIds); verify(applicationRepositoryMock, only()).findSubmittedApplicationsNotOnInterviewPanel(COMPETITION_ID); }
InterviewAssignmentServiceImpl implements InterviewAssignmentService { @Override public ServiceResult<Void> assignApplications(List<StagedApplicationResource> stagedInvites) { stagedInvites.stream() .distinct() .map(invite -> getApplication(invite.getApplicationId())) .forEach(application -> assignApplicationToCompetition(application.getSuccess())); return serviceSuccess(); } @Override @Transactional(readOnly = true) ServiceResult<AvailableApplicationPageResource> getAvailableApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<List<Long>> getAvailableApplicationIds(long competitionId); @Override ServiceResult<Void> assignApplications(List<StagedApplicationResource> stagedInvites); @Override ServiceResult<Void> unstageApplication(long applicationId); @Override ServiceResult<Void> unstageApplications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<Boolean> isApplicationAssigned(long applicationId); }
@Test public void assignApplications() { List<StagedApplicationResource> stagedApplications = newStagedApplicationResource() .withApplicationId(simpleMap(EXPECTED_AVAILABLE_APPLICATIONS, Application::getId).toArray(new Long[TOTAL_APPLICATIONS])) .withCompetitionId(COMPETITION_ID) .build(TOTAL_APPLICATIONS); forEachWithIndex(EXPECTED_AVAILABLE_APPLICATIONS, (i, expectedApplication) -> { when(applicationRepositoryMock.findById(expectedApplication.getId())) .thenReturn(Optional.of(expectedApplication)); when(interviewAssignmentRepositoryMock.save(interviewPanelLambdaMatcher(expectedApplication))) .thenReturn(newInterviewAssignment().build() ); }); service.assignApplications(stagedApplications).getSuccess(); InOrder inOrder = inOrder(applicationRepositoryMock, interviewAssignmentRepositoryMock); forEachWithIndex(EXPECTED_AVAILABLE_APPLICATIONS, (i, expectedApplication) -> { inOrder.verify(applicationRepositoryMock).findById(expectedApplication.getId()); inOrder.verify(interviewAssignmentRepositoryMock).save(interviewPanelLambdaMatcher(expectedApplication)); }); }
InterviewAssignmentServiceImpl implements InterviewAssignmentService { @Override public ServiceResult<Void> unstageApplication(long applicationId) { interviewAssignmentRepository.deleteByTargetIdAndActivityState(applicationId, CREATED); return serviceSuccess(); } @Override @Transactional(readOnly = true) ServiceResult<AvailableApplicationPageResource> getAvailableApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<List<Long>> getAvailableApplicationIds(long competitionId); @Override ServiceResult<Void> assignApplications(List<StagedApplicationResource> stagedInvites); @Override ServiceResult<Void> unstageApplication(long applicationId); @Override ServiceResult<Void> unstageApplications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<Boolean> isApplicationAssigned(long applicationId); }
@Test public void unstageApplication() { long applicationId = 1L; ServiceResult<Void> result = service.unstageApplication(applicationId); assertTrue(result.isSuccess()); verify(interviewAssignmentRepositoryMock).deleteByTargetIdAndActivityState(applicationId, InterviewAssignmentState.CREATED); }
UserPermissionRules { @PermissionRule(value = "READ", description = "Stakeholders can view users in competitions they are assigned to") public boolean stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user) { return userIsInCompetitionAssignedToStakeholder(userToView, user); } @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "An internal user can invite a monitoring officer and create the pending user associated.") boolean compAdminProjectFinanceCanCreateMonitoringOfficer(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserRegistrationResource userToCreate, UserResource user); @PermissionRule(value = "VERIFY", description = "A System Registration User can send a new User a verification link by e-mail") boolean systemRegistrationUserCanSendUserVerificationEmail(UserResource userToSendVerificationEmail, UserResource user); @PermissionRule(value = "READ", description = "Any user can view themselves") boolean anyUserCanViewThemselves(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Internal users can view everyone") boolean internalUsersCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can view users in competitions they are assigned to") boolean stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Competition finance users can view users in competitions they are assigned to") boolean competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can view users in projects they are assigned to") boolean monitoringOfficersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ_USER_ORGANISATION", description = "Internal support users can view all users and associated organisations") boolean internalUsersCanViewUserOrganisation(UserOrganisationResource userToView, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "IFS admins can update all users email addresses") boolean ifsAdminCanUpdateAllEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "Support users can update external users email addresses ") boolean supportCanUpdateExternalUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "System Maintenance update all users email addresses") boolean systemMaintenanceUserCanUpdateUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ_INTERNAL", description = "Administrators can view internal users") boolean internalUsersCanViewEveryone(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Support users and administrators can view external users") boolean supportUsersCanViewExternalUsers(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "The System Registration user can view everyone") boolean systemRegistrationUserCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Comp admins and project finance can view assessors") boolean compAdminAndProjectFinanceCanViewAssessors(UserPageResource usersToView, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewOtherConsortiumMembers(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewConsortiumUsersOnApplicationsTheyAreAssessing(UserResource userToView, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "A User should be able to change their own password") boolean usersCanChangeTheirOwnPassword(UserResource userToUpdate, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "The System Registration user should be able to change passwords on behalf of other Users") boolean systemRegistrationUserCanChangePasswordsForUsers(UserResource userToUpdate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A System Registration User can activate Users") boolean systemRegistrationUserCanActivateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "UPDATE", description = "A User can update their own profile") boolean usersCanUpdateTheirOwnProfiles(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE", description = "An admin user can update user details to assign monitoring officers") boolean adminsCanUpdateUserDetails(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile skills") boolean usersCanViewTheirOwnProfileSkills(ProfileSkillsResource profileSkills, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile agreement") boolean usersCanViewTheirOwnProfileAgreement(ProfileAgreementResource profileAgreementResource, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own affiliations") boolean usersCanViewTheirOwnAffiliations(AffiliationResource affiliation, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A user can read their own profile") boolean usersCanViewTheirOwnProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A ifs admin user can read any user's profile") boolean ifsAdminCanViewAnyUsersProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as Comp Admin and Exec can read the user's profile status") boolean usersAndCompAdminCanViewProfileStatus(UserProfileStatusResource profileStatus, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own role") boolean usersCanViewTheirOwnProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the process role of others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewTheProcessRolesOfOtherConsortiumMembers(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Project managers and partners can view the process role for the same organisation") boolean projectPartnersCanViewTheProcessRolesWithinSameApplication(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as internal users can read the user's process role") boolean usersAndInternalUsersCanViewProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the process roles of members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewTheProcessRolesOfConsortiumUsersOnApplicationsTheyAreAssessing(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "CHECK_USER_APPLICATION", description = "The user can check if they have an application for the competition") boolean userCanCheckTheyHaveApplicationForCompetition(UserResource userToCheck, UserResource user); @PermissionRule(value = "EDIT_INTERNAL_USER", description = "Only an IFS Administrator can edit an internal user") boolean ifsAdminCanEditInternalUser(final UserResource userToEdit, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "IFS Administrator can deactivate Users") boolean ifsAdminCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "A Support user can deactivate external Users") boolean supportUserCanDeactivateExternalUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "System Maintenance can deactivate Users") boolean systemMaintenanceUserCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "IFS Administrator can reactivate Users") boolean ifsAdminCanReactivateUsers(UserResource userToReactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A Support user can reactivate external Users") boolean supportUserCanReactivateExternalUsers(UserResource userToActivate, UserResource user); @PermissionRule(value = "AGREE_TERMS", description = "A user can accept the site terms and conditions") boolean usersCanAgreeSiteTermsAndConditions(UserResource userToUpdate, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An assessor can request applicant role") boolean assessorCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant monitoring officer role") boolean isGrantingMonitoringOfficerRoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant a KTA role") boolean isGrantingKTARoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An stakeholder can request applicant role") boolean stakeholderCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An monitoring officer can request applicant role") boolean monitoringOfficerCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "CAN_VIEW_OWN_DASHBOARD", description = "User is requesting own dashboard") boolean isViewingOwnDashboard(UserResource userToView, UserResource user); }
@Test public void stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo() { Competition competition = newCompetition().build(); Application application = newApplication().withCompetition(competition).build(); Project project = newProject().withApplication(application).build(); Stakeholder stakeholder = newStakeholder().withCompetition(competition).build(); UserResource stakeholderResource = newUserResource().withRoleGlobal(STAKEHOLDER).build(); UserResource userResource = newUserResource().withRoleGlobal(LEADAPPLICANT).build(); User user = newUser().withId(userResource.getId()).build(); List<ProcessRole> processRoles = newProcessRole() .withUser(user) .build(2); List<ProjectUser> projectUsers = newProjectUser() .withProject(project) .withRole(ProjectParticipantRole.PROJECT_MANAGER) .build(2); when(processRoleRepository.findByUserId(userResource.getId())).thenReturn(processRoles); when(projectUserRepository.findByUserId(userResource.getId())).thenReturn(projectUsers); when(stakeholderRepository.findByStakeholderId(stakeholderResource.getId())).thenReturn(singletonList(stakeholder)); assertTrue(rules.stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo(userResource, stakeholderResource)); allInternalUsers.forEach(internalUser -> assertFalse(rules.stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo(userResource, internalUser))); }
InterviewAssignmentServiceImpl implements InterviewAssignmentService { @Override public ServiceResult<Void> unstageApplications(long competitionId) { interviewAssignmentRepository.deleteByTargetCompetitionIdAndActivityState(competitionId, CREATED); return serviceSuccess(); } @Override @Transactional(readOnly = true) ServiceResult<AvailableApplicationPageResource> getAvailableApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<List<Long>> getAvailableApplicationIds(long competitionId); @Override ServiceResult<Void> assignApplications(List<StagedApplicationResource> stagedInvites); @Override ServiceResult<Void> unstageApplication(long applicationId); @Override ServiceResult<Void> unstageApplications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<Boolean> isApplicationAssigned(long applicationId); }
@Test public void unstageApplications() { long competitionId = 1L; ServiceResult<Void> result = service.unstageApplications(1L); assertTrue(result.isSuccess()); verify(interviewAssignmentRepositoryMock).deleteByTargetCompetitionIdAndActivityState(competitionId, InterviewAssignmentState.CREATED); }
InterviewAssignmentServiceImpl implements InterviewAssignmentService { @Override @Transactional(readOnly = true) public ServiceResult<Boolean> isApplicationAssigned(long applicationId) { return serviceSuccess(interviewAssignmentRepository.existsByTargetIdAndActivityStateIn(applicationId, asList(AWAITING_FEEDBACK_RESPONSE, SUBMITTED_FEEDBACK_RESPONSE))); } @Override @Transactional(readOnly = true) ServiceResult<AvailableApplicationPageResource> getAvailableApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentStagedApplicationPageResource> getStagedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<InterviewAssignmentApplicationPageResource> getAssignedApplications(long competitionId, Pageable pageable); @Override @Transactional(readOnly = true) ServiceResult<List<Long>> getAvailableApplicationIds(long competitionId); @Override ServiceResult<Void> assignApplications(List<StagedApplicationResource> stagedInvites); @Override ServiceResult<Void> unstageApplication(long applicationId); @Override ServiceResult<Void> unstageApplications(long competitionId); @Override @Transactional(readOnly = true) ServiceResult<Boolean> isApplicationAssigned(long applicationId); }
@Test public void isApplicationAssigned() { long applicationId = 1L; when(interviewAssignmentRepositoryMock.existsByTargetIdAndActivityStateIn(applicationId, asList(AWAITING_FEEDBACK_RESPONSE, SUBMITTED_FEEDBACK_RESPONSE))) .thenReturn(true); ServiceResult<Boolean> result = service.isApplicationAssigned(applicationId); assertTrue(result.getSuccess()); }
InterviewApplicationInviteServiceImpl implements InterviewApplicationInviteService { @Override public ServiceResult<ApplicantInterviewInviteResource> getEmailTemplate() { NotificationTarget notificationTarget = new UserNotificationTarget("", ""); return renderer.renderTemplate(systemNotificationSource, notificationTarget, PREVIEW_TEMPLATES_PATH + "invite_applicants_to_interview_panel_text.txt", Collections.emptyMap()).andOnSuccessReturn(content -> new ApplicantInterviewInviteResource(content)); } @Override ServiceResult<ApplicantInterviewInviteResource> getEmailTemplate(); @Override ServiceResult<Void> sendInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<InterviewApplicationSentInviteResource> getSentInvite(long applicationId); @Override ServiceResult<Void> resendInvite(long applicationId, AssessorInviteSendResource assessorInviteSendResource); }
@Test public void getEmailTemplate() { when(notificationTemplateRendererMock.renderTemplate(eq(systemNotificationSourceMock), any(NotificationTarget.class), eq(PREVIEW_TEMPLATES_PATH + "invite_applicants_to_interview_panel_text.txt"), any(Map.class))).thenReturn(serviceSuccess("Content")); ServiceResult<ApplicantInterviewInviteResource> result = service.getEmailTemplate(); assertTrue(result.isSuccess()); assertEquals(result.getSuccess().getContent(),"Content"); }
InterviewApplicationInviteServiceImpl implements InterviewApplicationInviteService { @Override public ServiceResult<Void> sendInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource) { List<InterviewAssignment> interviewAssignments = interviewAssignmentRepository.findByTargetCompetitionIdAndActivityState( competitionId, InterviewAssignmentState.CREATED); ServiceResult<Void> result = serviceSuccess(); for (InterviewAssignment assignment : interviewAssignments) { if (result.isSuccess()) { result = sendInvite(assessorInviteSendResource, assignment); } } return result; } @Override ServiceResult<ApplicantInterviewInviteResource> getEmailTemplate(); @Override ServiceResult<Void> sendInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<InterviewApplicationSentInviteResource> getSentInvite(long applicationId); @Override ServiceResult<Void> resendInvite(long applicationId, AssessorInviteSendResource assessorInviteSendResource); }
@Test public void sendInvites() { AssessorInviteSendResource sendResource = new AssessorInviteSendResource("Subject", "Content"); List<InterviewAssignment> interviewAssignments = newInterviewAssignment() .withParticipant( newProcessRole() .withRole(Role.INTERVIEW_LEAD_APPLICANT) .withOrganisationId(LEAD_ORGANISATION.getId()) .withUser(newUser() .withFirstName("Someone").withLastName("SomeName").withEmailAddress("[email protected]").build()) .build() ) .withTarget( newApplication() .withCompetition(newCompetition().build()) .build() ) .withState(InterviewAssignmentState.CREATED) .build(1); InterviewAssignmentMessageOutcome outcome = new InterviewAssignmentMessageOutcome(); outcome.setAssessmentInterviewPanel(interviewAssignments.get(0)); outcome.setMessage(sendResource.getContent()); outcome.setSubject(sendResource.getSubject()); when(interviewAssignmentRepositoryMock.findByTargetCompetitionIdAndActivityState( COMPETITION_ID, InterviewAssignmentState.CREATED)).thenReturn(interviewAssignments); when(notificationServiceMock.sendNotificationWithFlush(any(Notification.class), eq(EMAIL))).thenReturn(serviceSuccess(null)); ServiceResult<Void> result = service.sendInvites(COMPETITION_ID, sendResource); assertTrue(result.isSuccess()); verify(notificationServiceMock, only()).sendNotificationWithFlush(any(Notification.class), eq(EMAIL)); verify(interviewAssignmentWorkflowHandlerMock).notifyInterviewPanel(interviewAssignments.get(0), outcome); }
InterviewApplicationInviteServiceImpl implements InterviewApplicationInviteService { @Override public ServiceResult<InterviewApplicationSentInviteResource> getSentInvite(long applicationId) { InterviewAssignment assignment = interviewAssignmentRepository.findOneByTargetId(applicationId); return ofNullable(assignment.getMessage()) .map(message -> serviceSuccess( new InterviewApplicationSentInviteResource(message.getSubject(), message.getMessage(), message.getCreatedOn()) ) ) .orElse(serviceFailure(GENERAL_NOT_FOUND)); } @Override ServiceResult<ApplicantInterviewInviteResource> getEmailTemplate(); @Override ServiceResult<Void> sendInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<InterviewApplicationSentInviteResource> getSentInvite(long applicationId); @Override ServiceResult<Void> resendInvite(long applicationId, AssessorInviteSendResource assessorInviteSendResource); }
@Test public void getSentInvite() { long applicationId = 1L; String subject = "subject"; String content = "content"; ZonedDateTime assigned = ZonedDateTime.now(); InterviewApplicationSentInviteResource expected = newInterviewApplicationSentInviteResource() .withContent(content) .withSubject(subject) .withAssigned(assigned) .build(); InterviewAssignmentMessageOutcome message = newInterviewAssignmentMessageOutcome() .withSubject(subject) .withMessage(content) .withCreatedOn(assigned) .build(); InterviewAssignment interviewAssignment = newInterviewAssignment() .withMessage(message) .build(); when(interviewAssignmentRepositoryMock.findOneByTargetId(applicationId)).thenReturn(interviewAssignment); ServiceResult<InterviewApplicationSentInviteResource> result = service.getSentInvite(applicationId); assertTrue(result.isSuccess()); assertEquals(expected, result.getSuccess()); }
InterviewApplicationInviteServiceImpl implements InterviewApplicationInviteService { @Override public ServiceResult<Void> resendInvite(long applicationId, AssessorInviteSendResource assessorInviteSendResource) { InterviewAssignment assignment = interviewAssignmentRepository.findOneByTargetId(applicationId); return sendInvite(assessorInviteSendResource, assignment); } @Override ServiceResult<ApplicantInterviewInviteResource> getEmailTemplate(); @Override ServiceResult<Void> sendInvites(long competitionId, AssessorInviteSendResource assessorInviteSendResource); @Override ServiceResult<InterviewApplicationSentInviteResource> getSentInvite(long applicationId); @Override ServiceResult<Void> resendInvite(long applicationId, AssessorInviteSendResource assessorInviteSendResource); }
@Test public void resendInvite() { long applicationId = 1L; AssessorInviteSendResource sendResource = new AssessorInviteSendResource("Subject", "Content"); InterviewAssignmentMessageOutcome message = newInterviewAssignmentMessageOutcome().build(); InterviewAssignment interviewAssignment = newInterviewAssignment() .withParticipant( newProcessRole() .withRole(Role.INTERVIEW_LEAD_APPLICANT) .withOrganisationId(LEAD_ORGANISATION.getId()) .withUser(newUser() .withFirstName("Someone").withLastName("SomeName").withEmailAddress("[email protected]").build()) .build() ) .withTarget( newApplication() .withCompetition(newCompetition().build()) .build() ) .withState(InterviewAssignmentState.SUBMITTED_FEEDBACK_RESPONSE) .withMessage(message) .build(); when(interviewAssignmentRepositoryMock.findOneByTargetId(applicationId)).thenReturn(interviewAssignment); when(notificationServiceMock.sendNotificationWithFlush(any(Notification.class), eq(EMAIL))).thenReturn(serviceSuccess(null)); ServiceResult<Void> result = service.resendInvite(applicationId, sendResource); assertTrue(result.isSuccess()); verify(notificationServiceMock, only()).sendNotificationWithFlush(any(Notification.class), eq(EMAIL)); verify(interviewAssignmentWorkflowHandlerMock).notifyInterviewPanel(interviewAssignment, message); }
CompetitionInitialiser { public Competition initialiseFinanceTypes(Competition competition) { if (competition.getFundingType() == null) { return competition; } List<FinanceRowType> types; switch (competition.getFundingType()) { case LOAN: types = loanFinanceTypes(); break; case PROCUREMENT: types = procurementFinanceTypes(); break; case KTP: types = ktpFinanceTypes(); break; case GRANT: case INVESTOR_PARTNERSHIPS: types = defaultFinanceTypes(); break; default: throw new IllegalArgumentException("Unrecognised funding type when initialising competition."); } IntStream.range(0, types.size()).forEach(i -> competition.getCompetitionFinanceRowTypes().add( competitionFinanceRowsTypesRepository.save( new CompetitionFinanceRowTypes(competition, types.get(i), i))) ); return competition; } Competition initialiseProjectSetupColumns(Competition competition); Competition initialiseFinanceTypes(Competition competition); }
@Test public void initialiseFinance_Loan() { Competition competition = newCompetition().withFundingType(LOAN).build(); Competition competitionWithFinanceTypes = initialiser.initialiseFinanceTypes(competition); assertTrue(competitionWithFinanceTypes.getFinanceRowTypes().containsAll(EnumSet.of( LABOUR, OVERHEADS, MATERIALS, CAPITAL_USAGE, SUBCONTRACTING_COSTS, TRAVEL, OTHER_COSTS, GRANT_CLAIM_AMOUNT, OTHER_FUNDING ))); } @Test public void initialiseFinance_Grant() { Competition competition = newCompetition().withFundingType(GRANT).build(); Competition competitionWithFinanceTypes = initialiser.initialiseFinanceTypes(competition); assertTrue(competitionWithFinanceTypes.getFinanceRowTypes().containsAll(EnumSet.of( LABOUR, OVERHEADS, MATERIALS, CAPITAL_USAGE, SUBCONTRACTING_COSTS, TRAVEL, OTHER_COSTS, FINANCE, OTHER_FUNDING, YOUR_FINANCE ))); } @Test public void initialiseFinance_InvestorPartnership() { Competition competition = newCompetition().withFundingType(INVESTOR_PARTNERSHIPS).build(); Competition competitionWithFinanceTypes = initialiser.initialiseFinanceTypes(competition); assertTrue(competitionWithFinanceTypes.getFinanceRowTypes().containsAll(EnumSet.of( LABOUR, OVERHEADS, MATERIALS, CAPITAL_USAGE, SUBCONTRACTING_COSTS, TRAVEL, OTHER_COSTS, FINANCE, OTHER_FUNDING, YOUR_FINANCE ))); } @Test public void initialiseFinance_Procurement() { Competition competition = newCompetition().withFundingType(PROCUREMENT).build(); Competition competitionWithFinanceTypes = initialiser.initialiseFinanceTypes(competition); assertTrue(competitionWithFinanceTypes.getFinanceRowTypes().containsAll(EnumSet.of( LABOUR, PROCUREMENT_OVERHEADS, MATERIALS, CAPITAL_USAGE, SUBCONTRACTING_COSTS, TRAVEL, OTHER_COSTS, FINANCE, OTHER_FUNDING, VAT ))); } @Test public void initialiseFinance_KTP() { Competition competition = newCompetition().withFundingType(KTP).build(); Competition competitionWithFinanceTypes = initialiser.initialiseFinanceTypes(competition); assertTrue(competitionWithFinanceTypes.getFinanceRowTypes().containsAll(EnumSet.of( ASSOCIATE_SALARY_COSTS, ASSOCIATE_DEVELOPMENT_COSTS, KTP_TRAVEL, CONSUMABLES, KNOWLEDGE_BASE, ESTATE_COSTS, ASSOCIATE_SUPPORT, OTHER_COSTS, ADDITIONAL_COMPANY_COSTS, FINANCE, PREVIOUS_FUNDING ))); }
CompetitionInitialiser { public Competition initialiseProjectSetupColumns(Competition competition) { if (competition.getFundingType() == null) { return competition; } switch (competition.getFundingType()) { case LOAN: addLoanProjectSetupColumns(competition); break; case PROCUREMENT: case GRANT: case KTP: case INVESTOR_PARTNERSHIPS: addDefaultProjectSetupColumns(competition); break; default: break; } return competition; } Competition initialiseProjectSetupColumns(Competition competition); Competition initialiseFinanceTypes(Competition competition); }
@Test public void initialiseProjectSetup_Loan() { Competition competition = newCompetition().withFundingType(LOAN).build(); Competition competitionWithFinanceTypes = initialiser.initialiseProjectSetupColumns(competition); assertTrue(competitionWithFinanceTypes.getProjectSetupStages().containsAll(EnumSet.of( PROJECT_DETAILS, PROJECT_TEAM, MONITORING_OFFICER, FINANCE_CHECKS, SPEND_PROFILE ))); } @Test public void initialiseProjectSetup_Grant() { Competition competition = newCompetition().withFundingType(GRANT).build(); Competition competitionWithFinanceTypes = initialiser.initialiseProjectSetupColumns(competition); assertTrue(competitionWithFinanceTypes.getProjectSetupStages().containsAll(EnumSet.of( PROJECT_DETAILS, PROJECT_TEAM, DOCUMENTS, MONITORING_OFFICER, BANK_DETAILS, FINANCE_CHECKS, SPEND_PROFILE, GRANT_OFFER_LETTER ))); } @Test public void initialiseProjectSetup_InvestorPartnership() { Competition competition = newCompetition().withFundingType(INVESTOR_PARTNERSHIPS).build(); Competition competitionWithFinanceTypes = initialiser.initialiseProjectSetupColumns(competition); assertTrue(competitionWithFinanceTypes.getProjectSetupStages().containsAll(EnumSet.of( PROJECT_DETAILS, PROJECT_TEAM, DOCUMENTS, MONITORING_OFFICER, BANK_DETAILS, FINANCE_CHECKS, SPEND_PROFILE, GRANT_OFFER_LETTER ))); } @Test public void initialiseProjectSetup_Procurement() { Competition competition = newCompetition().withFundingType(PROCUREMENT).build(); Competition competitionWithFinanceTypes = initialiser.initialiseProjectSetupColumns(competition); assertTrue(competitionWithFinanceTypes.getProjectSetupStages().containsAll(EnumSet.of( PROJECT_DETAILS, PROJECT_TEAM, MONITORING_OFFICER, BANK_DETAILS, FINANCE_CHECKS, SPEND_PROFILE, GRANT_OFFER_LETTER ))); } @Test public void initialiseProjectSetup_KTP() { Competition competition = newCompetition().withFundingType(KTP).build(); Competition competitionWithFinanceTypes = initialiser.initialiseProjectSetupColumns(competition); assertTrue(competitionWithFinanceTypes.getProjectSetupStages().containsAll(EnumSet.of( PROJECT_DETAILS, PROJECT_TEAM, DOCUMENTS, MONITORING_OFFICER, BANK_DETAILS, FINANCE_CHECKS, SPEND_PROFILE, GRANT_OFFER_LETTER ))); }
UserPermissionRules { @PermissionRule(value = "READ", description = "Competition finance users can view users in competitions they are assigned to") public boolean competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user) { return userIsInCompetitionAssignedToCompetitionFinance(userToView, user); } @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "An internal user can invite a monitoring officer and create the pending user associated.") boolean compAdminProjectFinanceCanCreateMonitoringOfficer(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserRegistrationResource userToCreate, UserResource user); @PermissionRule(value = "VERIFY", description = "A System Registration User can send a new User a verification link by e-mail") boolean systemRegistrationUserCanSendUserVerificationEmail(UserResource userToSendVerificationEmail, UserResource user); @PermissionRule(value = "READ", description = "Any user can view themselves") boolean anyUserCanViewThemselves(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Internal users can view everyone") boolean internalUsersCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can view users in competitions they are assigned to") boolean stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Competition finance users can view users in competitions they are assigned to") boolean competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can view users in projects they are assigned to") boolean monitoringOfficersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ_USER_ORGANISATION", description = "Internal support users can view all users and associated organisations") boolean internalUsersCanViewUserOrganisation(UserOrganisationResource userToView, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "IFS admins can update all users email addresses") boolean ifsAdminCanUpdateAllEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "Support users can update external users email addresses ") boolean supportCanUpdateExternalUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "System Maintenance update all users email addresses") boolean systemMaintenanceUserCanUpdateUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ_INTERNAL", description = "Administrators can view internal users") boolean internalUsersCanViewEveryone(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Support users and administrators can view external users") boolean supportUsersCanViewExternalUsers(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "The System Registration user can view everyone") boolean systemRegistrationUserCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Comp admins and project finance can view assessors") boolean compAdminAndProjectFinanceCanViewAssessors(UserPageResource usersToView, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewOtherConsortiumMembers(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewConsortiumUsersOnApplicationsTheyAreAssessing(UserResource userToView, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "A User should be able to change their own password") boolean usersCanChangeTheirOwnPassword(UserResource userToUpdate, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "The System Registration user should be able to change passwords on behalf of other Users") boolean systemRegistrationUserCanChangePasswordsForUsers(UserResource userToUpdate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A System Registration User can activate Users") boolean systemRegistrationUserCanActivateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "UPDATE", description = "A User can update their own profile") boolean usersCanUpdateTheirOwnProfiles(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE", description = "An admin user can update user details to assign monitoring officers") boolean adminsCanUpdateUserDetails(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile skills") boolean usersCanViewTheirOwnProfileSkills(ProfileSkillsResource profileSkills, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile agreement") boolean usersCanViewTheirOwnProfileAgreement(ProfileAgreementResource profileAgreementResource, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own affiliations") boolean usersCanViewTheirOwnAffiliations(AffiliationResource affiliation, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A user can read their own profile") boolean usersCanViewTheirOwnProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A ifs admin user can read any user's profile") boolean ifsAdminCanViewAnyUsersProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as Comp Admin and Exec can read the user's profile status") boolean usersAndCompAdminCanViewProfileStatus(UserProfileStatusResource profileStatus, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own role") boolean usersCanViewTheirOwnProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the process role of others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewTheProcessRolesOfOtherConsortiumMembers(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Project managers and partners can view the process role for the same organisation") boolean projectPartnersCanViewTheProcessRolesWithinSameApplication(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as internal users can read the user's process role") boolean usersAndInternalUsersCanViewProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the process roles of members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewTheProcessRolesOfConsortiumUsersOnApplicationsTheyAreAssessing(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "CHECK_USER_APPLICATION", description = "The user can check if they have an application for the competition") boolean userCanCheckTheyHaveApplicationForCompetition(UserResource userToCheck, UserResource user); @PermissionRule(value = "EDIT_INTERNAL_USER", description = "Only an IFS Administrator can edit an internal user") boolean ifsAdminCanEditInternalUser(final UserResource userToEdit, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "IFS Administrator can deactivate Users") boolean ifsAdminCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "A Support user can deactivate external Users") boolean supportUserCanDeactivateExternalUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "System Maintenance can deactivate Users") boolean systemMaintenanceUserCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "IFS Administrator can reactivate Users") boolean ifsAdminCanReactivateUsers(UserResource userToReactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A Support user can reactivate external Users") boolean supportUserCanReactivateExternalUsers(UserResource userToActivate, UserResource user); @PermissionRule(value = "AGREE_TERMS", description = "A user can accept the site terms and conditions") boolean usersCanAgreeSiteTermsAndConditions(UserResource userToUpdate, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An assessor can request applicant role") boolean assessorCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant monitoring officer role") boolean isGrantingMonitoringOfficerRoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant a KTA role") boolean isGrantingKTARoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An stakeholder can request applicant role") boolean stakeholderCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An monitoring officer can request applicant role") boolean monitoringOfficerCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "CAN_VIEW_OWN_DASHBOARD", description = "User is requesting own dashboard") boolean isViewingOwnDashboard(UserResource userToView, UserResource user); }
@Test public void competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo() { Competition competition = newCompetition().build(); Application application = newApplication().withCompetition(competition).build(); Project project = newProject().withApplication(application).build(); ExternalFinance externalFinance = newCompetitionFinance().withCompetition(competition).build(); UserResource competitionFinanceResource = newUserResource().withRoleGlobal(EXTERNAL_FINANCE).build(); UserResource userResource = newUserResource().withRoleGlobal(LEADAPPLICANT).build(); User user = newUser().withId(userResource.getId()).build(); List<ProcessRole> processRoles = newProcessRole() .withUser(user) .build(2); List<ProjectUser> projectUsers = newProjectUser() .withProject(project) .withRole(ProjectParticipantRole.PROJECT_MANAGER) .build(2); when(processRoleRepository.findByUserId(userResource.getId())).thenReturn(processRoles); when(projectUserRepository.findByUserId(userResource.getId())).thenReturn(projectUsers); when(externalFinanceRepository.findByCompetitionFinanceId(competitionFinanceResource.getId())).thenReturn(singletonList(externalFinance)); assertTrue(rules.competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo(userResource, competitionFinanceResource)); allInternalUsers.forEach(internalUser -> assertFalse(rules.competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo(userResource, internalUser))); }
CompetitionSetupController { @PutMapping("/{id}/update-competition-initial-details") public RestResult<Void> updateCompetitionInitialDetails(@Valid @RequestBody CompetitionResource competitionResource, @PathVariable("id") final long id) { CompetitionResource existingCompetitionResource = competitionService.getCompetitionById(id).getSuccess(); return competitionSetupService.updateCompetitionInitialDetails(id, competitionResource, existingCompetitionResource.getLeadTechnologist()).toPutResponse(); } @PutMapping("/{id}") RestResult<CompetitionResource> saveCompetition(@RequestBody CompetitionResource competitionResource, @PathVariable("id") final Long id); @PutMapping("/{id}/update-competition-initial-details") RestResult<Void> updateCompetitionInitialDetails(@Valid @RequestBody CompetitionResource competitionResource, @PathVariable("id") final long id); @PostMapping("/{id}/initialise-form/{competitionTypeId}") RestResult<Void> initialiseForm(@PathVariable("id") Long competitionId, @PathVariable("competitionTypeId") Long competitionType); @PostMapping("/generate-competition-code/{id}") RestResult<String> generateCompetitionCode(@RequestBody ZonedDateTime dateTime, @PathVariable("id") final Long id); @PutMapping("/section-status/complete/{competitionId}/{section}") RestResult<Void> markSectionComplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("section") final CompetitionSetupSection section); @PutMapping("/section-status/incomplete/{competitionId}/{section}") RestResult<Void> markSectionIncomplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("section") final CompetitionSetupSection section); @PutMapping("/subsection-status/complete/{competitionId}/{parentSection}/{subsection}") RestResult<Void> markSubsectionComplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection, @PathVariable("subsection") final CompetitionSetupSubsection subsection); @PutMapping("/subsection-status/incomplete/{competitionId}/{parentSection}/{subsection}") RestResult<Void> markSubsectionIncomplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection, @PathVariable("subsection") final CompetitionSetupSubsection subsection); @GetMapping("/section-status/{competitionId}") RestResult<Map<CompetitionSetupSection, Optional<Boolean>>> getSectionStatuses(@PathVariable("competitionId") final Long competitionId); @GetMapping("/subsection-status/{competitionId}") RestResult<Map<CompetitionSetupSubsection, Optional<Boolean>>> getSubsectionStatuses(@PathVariable("competitionId") final Long competitionId); @PostMapping("/{id}/mark-as-setup") RestResult<Void> markAsSetup(@PathVariable("id") final Long competitionId); @PostMapping("/{id}/return-to-setup") RestResult<Void> returnToSetup(@PathVariable("id") final Long competitionId); @PostMapping RestResult<CompetitionResource> create(); @PostMapping("/non-ifs") RestResult<CompetitionResource> createNonIfs(); @DeleteMapping("{id}") RestResult<Void> deleteIfExists(@PathVariable("id") long competitionId); @PostMapping(value = "/competition-terms", produces = "application/json") RestResult<FileEntryResource> uploadCompetitionTerms( @RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam long competitionId, @RequestParam(value = "filename", required = false) String originalFilename, HttpServletRequest request); @DeleteMapping(value = "/competition-terms", produces = "application/json") RestResult<Void> deleteCompetitionTerms(@RequestParam(value = "competitionId") long competitionId); }
@Test public void updateCompetitionInitialDetails() throws Exception { long leadTechnologistUserId = 7L; CompetitionResource competition = newCompetitionResource() .withInnovationAreaNames(Collections.emptySet()) .withLeadTechnologist(leadTechnologistUserId) .build(); when(competitionServiceMock.getCompetitionById(competition.getId())).thenReturn(serviceSuccess(competition)); when(competitionSetupServiceMock.updateCompetitionInitialDetails(eq(competition.getId()), isA(CompetitionResource.class), eq(leadTechnologistUserId))).thenReturn(serviceSuccess()); mockMvc.perform(put("/competition/setup/{id}/update-competition-initial-details", competition.getId()) .contentType(MediaType.APPLICATION_JSON) .content(toJson(competition))) .andExpect(status().isOk()); verify(competitionServiceMock, only()).getCompetitionById(competition.getId()); verify(competitionSetupServiceMock, only()).updateCompetitionInitialDetails(competition.getId(), competition, leadTechnologistUserId); }
CompetitionSetupController { @PutMapping("/section-status/complete/{competitionId}/{section}") public RestResult<Void> markSectionComplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("section") final CompetitionSetupSection section) { return competitionSetupService.markSectionComplete(competitionId, section).toPutResponse(); } @PutMapping("/{id}") RestResult<CompetitionResource> saveCompetition(@RequestBody CompetitionResource competitionResource, @PathVariable("id") final Long id); @PutMapping("/{id}/update-competition-initial-details") RestResult<Void> updateCompetitionInitialDetails(@Valid @RequestBody CompetitionResource competitionResource, @PathVariable("id") final long id); @PostMapping("/{id}/initialise-form/{competitionTypeId}") RestResult<Void> initialiseForm(@PathVariable("id") Long competitionId, @PathVariable("competitionTypeId") Long competitionType); @PostMapping("/generate-competition-code/{id}") RestResult<String> generateCompetitionCode(@RequestBody ZonedDateTime dateTime, @PathVariable("id") final Long id); @PutMapping("/section-status/complete/{competitionId}/{section}") RestResult<Void> markSectionComplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("section") final CompetitionSetupSection section); @PutMapping("/section-status/incomplete/{competitionId}/{section}") RestResult<Void> markSectionIncomplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("section") final CompetitionSetupSection section); @PutMapping("/subsection-status/complete/{competitionId}/{parentSection}/{subsection}") RestResult<Void> markSubsectionComplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection, @PathVariable("subsection") final CompetitionSetupSubsection subsection); @PutMapping("/subsection-status/incomplete/{competitionId}/{parentSection}/{subsection}") RestResult<Void> markSubsectionIncomplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection, @PathVariable("subsection") final CompetitionSetupSubsection subsection); @GetMapping("/section-status/{competitionId}") RestResult<Map<CompetitionSetupSection, Optional<Boolean>>> getSectionStatuses(@PathVariable("competitionId") final Long competitionId); @GetMapping("/subsection-status/{competitionId}") RestResult<Map<CompetitionSetupSubsection, Optional<Boolean>>> getSubsectionStatuses(@PathVariable("competitionId") final Long competitionId); @PostMapping("/{id}/mark-as-setup") RestResult<Void> markAsSetup(@PathVariable("id") final Long competitionId); @PostMapping("/{id}/return-to-setup") RestResult<Void> returnToSetup(@PathVariable("id") final Long competitionId); @PostMapping RestResult<CompetitionResource> create(); @PostMapping("/non-ifs") RestResult<CompetitionResource> createNonIfs(); @DeleteMapping("{id}") RestResult<Void> deleteIfExists(@PathVariable("id") long competitionId); @PostMapping(value = "/competition-terms", produces = "application/json") RestResult<FileEntryResource> uploadCompetitionTerms( @RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam long competitionId, @RequestParam(value = "filename", required = false) String originalFilename, HttpServletRequest request); @DeleteMapping(value = "/competition-terms", produces = "application/json") RestResult<Void> deleteCompetitionTerms(@RequestParam(value = "competitionId") long competitionId); }
@Test public void markSectionComplete() throws Exception { final Long competitionId = 5L; final CompetitionSetupSection section = CompetitionSetupSection.APPLICATION_FORM; final SetupStatusResource setupStatusResource = newSetupStatusResource().build(); when(competitionSetupServiceMock.markSectionComplete(competitionId, section)) .thenReturn(serviceSuccess(setupStatusResource)); mockMvc.perform(put("/competition/setup/section-status/complete/{competitionId}/{section}", competitionId, section)) .andExpect(status().is2xxSuccessful()); verify(competitionSetupServiceMock, only()).markSectionComplete(competitionId, section); }
CompetitionSetupController { @PutMapping("/section-status/incomplete/{competitionId}/{section}") public RestResult<Void> markSectionIncomplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("section") final CompetitionSetupSection section) { return competitionSetupService.markSectionIncomplete(competitionId, section).toPutResponse(); } @PutMapping("/{id}") RestResult<CompetitionResource> saveCompetition(@RequestBody CompetitionResource competitionResource, @PathVariable("id") final Long id); @PutMapping("/{id}/update-competition-initial-details") RestResult<Void> updateCompetitionInitialDetails(@Valid @RequestBody CompetitionResource competitionResource, @PathVariable("id") final long id); @PostMapping("/{id}/initialise-form/{competitionTypeId}") RestResult<Void> initialiseForm(@PathVariable("id") Long competitionId, @PathVariable("competitionTypeId") Long competitionType); @PostMapping("/generate-competition-code/{id}") RestResult<String> generateCompetitionCode(@RequestBody ZonedDateTime dateTime, @PathVariable("id") final Long id); @PutMapping("/section-status/complete/{competitionId}/{section}") RestResult<Void> markSectionComplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("section") final CompetitionSetupSection section); @PutMapping("/section-status/incomplete/{competitionId}/{section}") RestResult<Void> markSectionIncomplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("section") final CompetitionSetupSection section); @PutMapping("/subsection-status/complete/{competitionId}/{parentSection}/{subsection}") RestResult<Void> markSubsectionComplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection, @PathVariable("subsection") final CompetitionSetupSubsection subsection); @PutMapping("/subsection-status/incomplete/{competitionId}/{parentSection}/{subsection}") RestResult<Void> markSubsectionIncomplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection, @PathVariable("subsection") final CompetitionSetupSubsection subsection); @GetMapping("/section-status/{competitionId}") RestResult<Map<CompetitionSetupSection, Optional<Boolean>>> getSectionStatuses(@PathVariable("competitionId") final Long competitionId); @GetMapping("/subsection-status/{competitionId}") RestResult<Map<CompetitionSetupSubsection, Optional<Boolean>>> getSubsectionStatuses(@PathVariable("competitionId") final Long competitionId); @PostMapping("/{id}/mark-as-setup") RestResult<Void> markAsSetup(@PathVariable("id") final Long competitionId); @PostMapping("/{id}/return-to-setup") RestResult<Void> returnToSetup(@PathVariable("id") final Long competitionId); @PostMapping RestResult<CompetitionResource> create(); @PostMapping("/non-ifs") RestResult<CompetitionResource> createNonIfs(); @DeleteMapping("{id}") RestResult<Void> deleteIfExists(@PathVariable("id") long competitionId); @PostMapping(value = "/competition-terms", produces = "application/json") RestResult<FileEntryResource> uploadCompetitionTerms( @RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam long competitionId, @RequestParam(value = "filename", required = false) String originalFilename, HttpServletRequest request); @DeleteMapping(value = "/competition-terms", produces = "application/json") RestResult<Void> deleteCompetitionTerms(@RequestParam(value = "competitionId") long competitionId); }
@Test public void markSectionIncomplete() throws Exception { final Long competitionId = 5L; final CompetitionSetupSection section = CompetitionSetupSection.APPLICATION_FORM; final List<SetupStatusResource> setupStatusResource = newSetupStatusResource().build(1); when(competitionSetupServiceMock.markSectionIncomplete(competitionId, section)) .thenReturn(serviceSuccess(setupStatusResource)); mockMvc.perform(put("/competition/setup/section-status/incomplete/{competitionId}/{section}", competitionId, section)) .andExpect(status().is2xxSuccessful()); verify(competitionSetupServiceMock, only()).markSectionIncomplete(competitionId, section); }
CompetitionSetupController { @GetMapping("/section-status/{competitionId}") public RestResult<Map<CompetitionSetupSection, Optional<Boolean>>> getSectionStatuses(@PathVariable("competitionId") final Long competitionId) { return competitionSetupService.getSectionStatuses(competitionId).toGetResponse(); } @PutMapping("/{id}") RestResult<CompetitionResource> saveCompetition(@RequestBody CompetitionResource competitionResource, @PathVariable("id") final Long id); @PutMapping("/{id}/update-competition-initial-details") RestResult<Void> updateCompetitionInitialDetails(@Valid @RequestBody CompetitionResource competitionResource, @PathVariable("id") final long id); @PostMapping("/{id}/initialise-form/{competitionTypeId}") RestResult<Void> initialiseForm(@PathVariable("id") Long competitionId, @PathVariable("competitionTypeId") Long competitionType); @PostMapping("/generate-competition-code/{id}") RestResult<String> generateCompetitionCode(@RequestBody ZonedDateTime dateTime, @PathVariable("id") final Long id); @PutMapping("/section-status/complete/{competitionId}/{section}") RestResult<Void> markSectionComplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("section") final CompetitionSetupSection section); @PutMapping("/section-status/incomplete/{competitionId}/{section}") RestResult<Void> markSectionIncomplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("section") final CompetitionSetupSection section); @PutMapping("/subsection-status/complete/{competitionId}/{parentSection}/{subsection}") RestResult<Void> markSubsectionComplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection, @PathVariable("subsection") final CompetitionSetupSubsection subsection); @PutMapping("/subsection-status/incomplete/{competitionId}/{parentSection}/{subsection}") RestResult<Void> markSubsectionIncomplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection, @PathVariable("subsection") final CompetitionSetupSubsection subsection); @GetMapping("/section-status/{competitionId}") RestResult<Map<CompetitionSetupSection, Optional<Boolean>>> getSectionStatuses(@PathVariable("competitionId") final Long competitionId); @GetMapping("/subsection-status/{competitionId}") RestResult<Map<CompetitionSetupSubsection, Optional<Boolean>>> getSubsectionStatuses(@PathVariable("competitionId") final Long competitionId); @PostMapping("/{id}/mark-as-setup") RestResult<Void> markAsSetup(@PathVariable("id") final Long competitionId); @PostMapping("/{id}/return-to-setup") RestResult<Void> returnToSetup(@PathVariable("id") final Long competitionId); @PostMapping RestResult<CompetitionResource> create(); @PostMapping("/non-ifs") RestResult<CompetitionResource> createNonIfs(); @DeleteMapping("{id}") RestResult<Void> deleteIfExists(@PathVariable("id") long competitionId); @PostMapping(value = "/competition-terms", produces = "application/json") RestResult<FileEntryResource> uploadCompetitionTerms( @RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam long competitionId, @RequestParam(value = "filename", required = false) String originalFilename, HttpServletRequest request); @DeleteMapping(value = "/competition-terms", produces = "application/json") RestResult<Void> deleteCompetitionTerms(@RequestParam(value = "competitionId") long competitionId); }
@Test public void getSectionStatuses() throws Exception { final Long competitionId = 5L; final Map<CompetitionSetupSection, Optional<Boolean>> sectionStatuses = asMap(CompetitionSetupSection.INITIAL_DETAILS, Optional.of(TRUE), CompetitionSetupSection.CONTENT, Optional.of(TRUE), CompetitionSetupSection.APPLICATION_FORM, Optional.of(FALSE)); when(competitionSetupServiceMock.getSectionStatuses(competitionId)).thenReturn(serviceSuccess(sectionStatuses)); mockMvc.perform(get("/competition/setup/section-status/{competitionId}", competitionId)) .andExpect(status().is2xxSuccessful()); verify(competitionSetupServiceMock, only()).getSectionStatuses(competitionId); }
UserPermissionRules { @PermissionRule(value = "READ", description = "Monitoring officers can view users in projects they are assigned to") public boolean monitoringOfficersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user) { return userIsInProjectAssignedToMonitoringOfficer(userToView, user); } @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "An internal user can invite a monitoring officer and create the pending user associated.") boolean compAdminProjectFinanceCanCreateMonitoringOfficer(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserRegistrationResource userToCreate, UserResource user); @PermissionRule(value = "VERIFY", description = "A System Registration User can send a new User a verification link by e-mail") boolean systemRegistrationUserCanSendUserVerificationEmail(UserResource userToSendVerificationEmail, UserResource user); @PermissionRule(value = "READ", description = "Any user can view themselves") boolean anyUserCanViewThemselves(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Internal users can view everyone") boolean internalUsersCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can view users in competitions they are assigned to") boolean stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Competition finance users can view users in competitions they are assigned to") boolean competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can view users in projects they are assigned to") boolean monitoringOfficersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ_USER_ORGANISATION", description = "Internal support users can view all users and associated organisations") boolean internalUsersCanViewUserOrganisation(UserOrganisationResource userToView, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "IFS admins can update all users email addresses") boolean ifsAdminCanUpdateAllEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "Support users can update external users email addresses ") boolean supportCanUpdateExternalUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "System Maintenance update all users email addresses") boolean systemMaintenanceUserCanUpdateUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ_INTERNAL", description = "Administrators can view internal users") boolean internalUsersCanViewEveryone(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Support users and administrators can view external users") boolean supportUsersCanViewExternalUsers(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "The System Registration user can view everyone") boolean systemRegistrationUserCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Comp admins and project finance can view assessors") boolean compAdminAndProjectFinanceCanViewAssessors(UserPageResource usersToView, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewOtherConsortiumMembers(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewConsortiumUsersOnApplicationsTheyAreAssessing(UserResource userToView, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "A User should be able to change their own password") boolean usersCanChangeTheirOwnPassword(UserResource userToUpdate, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "The System Registration user should be able to change passwords on behalf of other Users") boolean systemRegistrationUserCanChangePasswordsForUsers(UserResource userToUpdate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A System Registration User can activate Users") boolean systemRegistrationUserCanActivateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "UPDATE", description = "A User can update their own profile") boolean usersCanUpdateTheirOwnProfiles(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE", description = "An admin user can update user details to assign monitoring officers") boolean adminsCanUpdateUserDetails(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile skills") boolean usersCanViewTheirOwnProfileSkills(ProfileSkillsResource profileSkills, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile agreement") boolean usersCanViewTheirOwnProfileAgreement(ProfileAgreementResource profileAgreementResource, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own affiliations") boolean usersCanViewTheirOwnAffiliations(AffiliationResource affiliation, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A user can read their own profile") boolean usersCanViewTheirOwnProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A ifs admin user can read any user's profile") boolean ifsAdminCanViewAnyUsersProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as Comp Admin and Exec can read the user's profile status") boolean usersAndCompAdminCanViewProfileStatus(UserProfileStatusResource profileStatus, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own role") boolean usersCanViewTheirOwnProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the process role of others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewTheProcessRolesOfOtherConsortiumMembers(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Project managers and partners can view the process role for the same organisation") boolean projectPartnersCanViewTheProcessRolesWithinSameApplication(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as internal users can read the user's process role") boolean usersAndInternalUsersCanViewProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the process roles of members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewTheProcessRolesOfConsortiumUsersOnApplicationsTheyAreAssessing(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "CHECK_USER_APPLICATION", description = "The user can check if they have an application for the competition") boolean userCanCheckTheyHaveApplicationForCompetition(UserResource userToCheck, UserResource user); @PermissionRule(value = "EDIT_INTERNAL_USER", description = "Only an IFS Administrator can edit an internal user") boolean ifsAdminCanEditInternalUser(final UserResource userToEdit, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "IFS Administrator can deactivate Users") boolean ifsAdminCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "A Support user can deactivate external Users") boolean supportUserCanDeactivateExternalUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "System Maintenance can deactivate Users") boolean systemMaintenanceUserCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "IFS Administrator can reactivate Users") boolean ifsAdminCanReactivateUsers(UserResource userToReactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A Support user can reactivate external Users") boolean supportUserCanReactivateExternalUsers(UserResource userToActivate, UserResource user); @PermissionRule(value = "AGREE_TERMS", description = "A user can accept the site terms and conditions") boolean usersCanAgreeSiteTermsAndConditions(UserResource userToUpdate, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An assessor can request applicant role") boolean assessorCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant monitoring officer role") boolean isGrantingMonitoringOfficerRoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant a KTA role") boolean isGrantingKTARoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An stakeholder can request applicant role") boolean stakeholderCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An monitoring officer can request applicant role") boolean monitoringOfficerCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "CAN_VIEW_OWN_DASHBOARD", description = "User is requesting own dashboard") boolean isViewingOwnDashboard(UserResource userToView, UserResource user); }
@Test public void monitoringOfficersCanViewUsersInProjectsTheyAreAssignedTo() { Project project = newProject().build(); UserResource userResource = newUserResource().withRoleGlobal(LEADAPPLICANT).build(); List<ProjectUser> projectUsers = newProjectUser() .withProject(project) .withRole(ProjectParticipantRole.PROJECT_MANAGER) .build(2); List<MonitoringOfficer> projectMonitoringOfficers = newMonitoringOfficer() .withProject(project) .build(1); when(projectUserRepository.findByUserId(userResource.getId())).thenReturn(projectUsers); when(projectMonitoringOfficerRepository.findByUserId(monitoringOfficerUser().getId())).thenReturn(projectMonitoringOfficers); allGlobalRoleUsers.forEach(user -> { if (isMonitoringOfficer(user)) { assertTrue(rules.monitoringOfficersCanViewUsersInCompetitionsTheyAreAssignedTo(userResource, monitoringOfficerUser())); } else { assertFalse(rules.monitoringOfficersCanViewUsersInCompetitionsTheyAreAssignedTo(userResource, user)); } }); }
CompetitionSetupController { @PutMapping("/subsection-status/complete/{competitionId}/{parentSection}/{subsection}") public RestResult<Void> markSubsectionComplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection, @PathVariable("subsection") final CompetitionSetupSubsection subsection) { return competitionSetupService.markSubsectionComplete(competitionId, parentSection, subsection).toPutResponse(); } @PutMapping("/{id}") RestResult<CompetitionResource> saveCompetition(@RequestBody CompetitionResource competitionResource, @PathVariable("id") final Long id); @PutMapping("/{id}/update-competition-initial-details") RestResult<Void> updateCompetitionInitialDetails(@Valid @RequestBody CompetitionResource competitionResource, @PathVariable("id") final long id); @PostMapping("/{id}/initialise-form/{competitionTypeId}") RestResult<Void> initialiseForm(@PathVariable("id") Long competitionId, @PathVariable("competitionTypeId") Long competitionType); @PostMapping("/generate-competition-code/{id}") RestResult<String> generateCompetitionCode(@RequestBody ZonedDateTime dateTime, @PathVariable("id") final Long id); @PutMapping("/section-status/complete/{competitionId}/{section}") RestResult<Void> markSectionComplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("section") final CompetitionSetupSection section); @PutMapping("/section-status/incomplete/{competitionId}/{section}") RestResult<Void> markSectionIncomplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("section") final CompetitionSetupSection section); @PutMapping("/subsection-status/complete/{competitionId}/{parentSection}/{subsection}") RestResult<Void> markSubsectionComplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection, @PathVariable("subsection") final CompetitionSetupSubsection subsection); @PutMapping("/subsection-status/incomplete/{competitionId}/{parentSection}/{subsection}") RestResult<Void> markSubsectionIncomplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection, @PathVariable("subsection") final CompetitionSetupSubsection subsection); @GetMapping("/section-status/{competitionId}") RestResult<Map<CompetitionSetupSection, Optional<Boolean>>> getSectionStatuses(@PathVariable("competitionId") final Long competitionId); @GetMapping("/subsection-status/{competitionId}") RestResult<Map<CompetitionSetupSubsection, Optional<Boolean>>> getSubsectionStatuses(@PathVariable("competitionId") final Long competitionId); @PostMapping("/{id}/mark-as-setup") RestResult<Void> markAsSetup(@PathVariable("id") final Long competitionId); @PostMapping("/{id}/return-to-setup") RestResult<Void> returnToSetup(@PathVariable("id") final Long competitionId); @PostMapping RestResult<CompetitionResource> create(); @PostMapping("/non-ifs") RestResult<CompetitionResource> createNonIfs(); @DeleteMapping("{id}") RestResult<Void> deleteIfExists(@PathVariable("id") long competitionId); @PostMapping(value = "/competition-terms", produces = "application/json") RestResult<FileEntryResource> uploadCompetitionTerms( @RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam long competitionId, @RequestParam(value = "filename", required = false) String originalFilename, HttpServletRequest request); @DeleteMapping(value = "/competition-terms", produces = "application/json") RestResult<Void> deleteCompetitionTerms(@RequestParam(value = "competitionId") long competitionId); }
@Test public void markSubsectionComplete() throws Exception { final Long competitionId = 5L; final CompetitionSetupSection parentSection = CompetitionSetupSection.APPLICATION_FORM; final CompetitionSetupSubsection subsection = CompetitionSetupSubsection.APPLICATION_DETAILS; final SetupStatusResource setupStatusResource = newSetupStatusResource().build(); when(competitionSetupServiceMock.markSubsectionComplete(competitionId, parentSection, subsection)) .thenReturn(serviceSuccess(setupStatusResource)); mockMvc.perform(put("/competition/setup/subsection-status/complete/{competitionId}/{parentSection}/{subsection}", competitionId, parentSection, subsection)) .andExpect(status().is2xxSuccessful()); verify(competitionSetupServiceMock, only()).markSubsectionComplete(competitionId, parentSection, subsection); }
CompetitionSetupController { @PutMapping("/subsection-status/incomplete/{competitionId}/{parentSection}/{subsection}") public RestResult<Void> markSubsectionIncomplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection, @PathVariable("subsection") final CompetitionSetupSubsection subsection) { return competitionSetupService.markSubsectionIncomplete(competitionId, parentSection, subsection).toPutResponse(); } @PutMapping("/{id}") RestResult<CompetitionResource> saveCompetition(@RequestBody CompetitionResource competitionResource, @PathVariable("id") final Long id); @PutMapping("/{id}/update-competition-initial-details") RestResult<Void> updateCompetitionInitialDetails(@Valid @RequestBody CompetitionResource competitionResource, @PathVariable("id") final long id); @PostMapping("/{id}/initialise-form/{competitionTypeId}") RestResult<Void> initialiseForm(@PathVariable("id") Long competitionId, @PathVariable("competitionTypeId") Long competitionType); @PostMapping("/generate-competition-code/{id}") RestResult<String> generateCompetitionCode(@RequestBody ZonedDateTime dateTime, @PathVariable("id") final Long id); @PutMapping("/section-status/complete/{competitionId}/{section}") RestResult<Void> markSectionComplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("section") final CompetitionSetupSection section); @PutMapping("/section-status/incomplete/{competitionId}/{section}") RestResult<Void> markSectionIncomplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("section") final CompetitionSetupSection section); @PutMapping("/subsection-status/complete/{competitionId}/{parentSection}/{subsection}") RestResult<Void> markSubsectionComplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection, @PathVariable("subsection") final CompetitionSetupSubsection subsection); @PutMapping("/subsection-status/incomplete/{competitionId}/{parentSection}/{subsection}") RestResult<Void> markSubsectionIncomplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection, @PathVariable("subsection") final CompetitionSetupSubsection subsection); @GetMapping("/section-status/{competitionId}") RestResult<Map<CompetitionSetupSection, Optional<Boolean>>> getSectionStatuses(@PathVariable("competitionId") final Long competitionId); @GetMapping("/subsection-status/{competitionId}") RestResult<Map<CompetitionSetupSubsection, Optional<Boolean>>> getSubsectionStatuses(@PathVariable("competitionId") final Long competitionId); @PostMapping("/{id}/mark-as-setup") RestResult<Void> markAsSetup(@PathVariable("id") final Long competitionId); @PostMapping("/{id}/return-to-setup") RestResult<Void> returnToSetup(@PathVariable("id") final Long competitionId); @PostMapping RestResult<CompetitionResource> create(); @PostMapping("/non-ifs") RestResult<CompetitionResource> createNonIfs(); @DeleteMapping("{id}") RestResult<Void> deleteIfExists(@PathVariable("id") long competitionId); @PostMapping(value = "/competition-terms", produces = "application/json") RestResult<FileEntryResource> uploadCompetitionTerms( @RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam long competitionId, @RequestParam(value = "filename", required = false) String originalFilename, HttpServletRequest request); @DeleteMapping(value = "/competition-terms", produces = "application/json") RestResult<Void> deleteCompetitionTerms(@RequestParam(value = "competitionId") long competitionId); }
@Test public void markSubsectionIncomplete() throws Exception { final Long competitionId = 5L; final CompetitionSetupSection parentSection = CompetitionSetupSection.APPLICATION_FORM; final CompetitionSetupSubsection subsection = CompetitionSetupSubsection.APPLICATION_DETAILS; final SetupStatusResource setupStatusResource = newSetupStatusResource().build(); when(competitionSetupServiceMock.markSubsectionIncomplete(competitionId, parentSection, subsection)) .thenReturn(serviceSuccess(setupStatusResource)); mockMvc.perform(put("/competition/setup/subsection-status/incomplete/{competitionId}/{parentSection}/{subsection}", competitionId, parentSection, subsection)) .andExpect(status().is2xxSuccessful()); verify(competitionSetupServiceMock, only()).markSubsectionIncomplete(competitionId, parentSection, subsection); }
CompetitionSetupController { @GetMapping("/subsection-status/{competitionId}") public RestResult<Map<CompetitionSetupSubsection, Optional<Boolean>>> getSubsectionStatuses(@PathVariable("competitionId") final Long competitionId) { return competitionSetupService.getSubsectionStatuses(competitionId).toGetResponse(); } @PutMapping("/{id}") RestResult<CompetitionResource> saveCompetition(@RequestBody CompetitionResource competitionResource, @PathVariable("id") final Long id); @PutMapping("/{id}/update-competition-initial-details") RestResult<Void> updateCompetitionInitialDetails(@Valid @RequestBody CompetitionResource competitionResource, @PathVariable("id") final long id); @PostMapping("/{id}/initialise-form/{competitionTypeId}") RestResult<Void> initialiseForm(@PathVariable("id") Long competitionId, @PathVariable("competitionTypeId") Long competitionType); @PostMapping("/generate-competition-code/{id}") RestResult<String> generateCompetitionCode(@RequestBody ZonedDateTime dateTime, @PathVariable("id") final Long id); @PutMapping("/section-status/complete/{competitionId}/{section}") RestResult<Void> markSectionComplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("section") final CompetitionSetupSection section); @PutMapping("/section-status/incomplete/{competitionId}/{section}") RestResult<Void> markSectionIncomplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("section") final CompetitionSetupSection section); @PutMapping("/subsection-status/complete/{competitionId}/{parentSection}/{subsection}") RestResult<Void> markSubsectionComplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection, @PathVariable("subsection") final CompetitionSetupSubsection subsection); @PutMapping("/subsection-status/incomplete/{competitionId}/{parentSection}/{subsection}") RestResult<Void> markSubsectionIncomplete(@PathVariable("competitionId") final Long competitionId, @PathVariable("parentSection") final CompetitionSetupSection parentSection, @PathVariable("subsection") final CompetitionSetupSubsection subsection); @GetMapping("/section-status/{competitionId}") RestResult<Map<CompetitionSetupSection, Optional<Boolean>>> getSectionStatuses(@PathVariable("competitionId") final Long competitionId); @GetMapping("/subsection-status/{competitionId}") RestResult<Map<CompetitionSetupSubsection, Optional<Boolean>>> getSubsectionStatuses(@PathVariable("competitionId") final Long competitionId); @PostMapping("/{id}/mark-as-setup") RestResult<Void> markAsSetup(@PathVariable("id") final Long competitionId); @PostMapping("/{id}/return-to-setup") RestResult<Void> returnToSetup(@PathVariable("id") final Long competitionId); @PostMapping RestResult<CompetitionResource> create(); @PostMapping("/non-ifs") RestResult<CompetitionResource> createNonIfs(); @DeleteMapping("{id}") RestResult<Void> deleteIfExists(@PathVariable("id") long competitionId); @PostMapping(value = "/competition-terms", produces = "application/json") RestResult<FileEntryResource> uploadCompetitionTerms( @RequestHeader(value = "Content-Type", required = false) String contentType, @RequestHeader(value = "Content-Length", required = false) String contentLength, @RequestParam long competitionId, @RequestParam(value = "filename", required = false) String originalFilename, HttpServletRequest request); @DeleteMapping(value = "/competition-terms", produces = "application/json") RestResult<Void> deleteCompetitionTerms(@RequestParam(value = "competitionId") long competitionId); }
@Test public void getSubsectionStatuses() throws Exception { final Long competitionId = 5L; final Map<CompetitionSetupSubsection, Optional<Boolean>> subsectionStatuses = asMap(CompetitionSetupSubsection.APPLICATION_DETAILS, Optional.of(TRUE), CompetitionSetupSubsection.FINANCES, Optional.empty()); when(competitionSetupServiceMock.getSubsectionStatuses(competitionId)).thenReturn(serviceSuccess(subsectionStatuses)); mockMvc.perform(get("/competition/setup/subsection-status/{competitionId}", competitionId)) .andExpect(status().is2xxSuccessful()); verify(competitionSetupServiceMock, only()).getSubsectionStatuses(competitionId); }
CompetitionSetupInnovationLeadController { @GetMapping("/{competitionId}/innovation-leads") public RestResult<List<UserResource>> findAvailableInnovationLeadsNotAssignedToCompetition(@PathVariable("competitionId") final long competitionId) { return competitionSetupInnovationLeadService.findInnovationLeads(competitionId).toGetResponse(); } @GetMapping("/{competitionId}/innovation-leads") RestResult<List<UserResource>> findAvailableInnovationLeadsNotAssignedToCompetition(@PathVariable("competitionId") final long competitionId); @GetMapping("/{competitionId}/innovation-leads/find-added") RestResult<List<UserResource>> findInnovationLeadsAddedToCompetition(@PathVariable("competitionId") final long competitionId); @PostMapping("/{competitionId}/add-innovation-lead/{innovationLeadUserId}") RestResult<Void> addInnovationLead(@PathVariable("competitionId") final long competitionId, @PathVariable("innovationLeadUserId") final long innovationLeadUserId); @PostMapping("/{competitionId}/remove-innovation-lead/{innovationLeadUserId}") RestResult<Void> removeInnovationLead(@PathVariable("competitionId") final long competitionId, @PathVariable("innovationLeadUserId") final long innovationLeadUserId); }
@Test public void findAvailableInnovationLeadsNotAssignedToCompetition() throws Exception { final long competitionId = 1L; List<UserResource> innovationLeads = new ArrayList<>(); when(competitionSetupInnovationLeadService.findInnovationLeads(competitionId)).thenReturn(serviceSuccess(innovationLeads)); mockMvc.perform(get("/competition/setup/{id}/innovation-leads", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(innovationLeads))); verify(competitionSetupInnovationLeadService).findInnovationLeads(competitionId); }
CompetitionSetupInnovationLeadController { @GetMapping("/{competitionId}/innovation-leads/find-added") public RestResult<List<UserResource>> findInnovationLeadsAddedToCompetition(@PathVariable("competitionId") final long competitionId) { return competitionSetupInnovationLeadService.findAddedInnovationLeads(competitionId).toGetResponse(); } @GetMapping("/{competitionId}/innovation-leads") RestResult<List<UserResource>> findAvailableInnovationLeadsNotAssignedToCompetition(@PathVariable("competitionId") final long competitionId); @GetMapping("/{competitionId}/innovation-leads/find-added") RestResult<List<UserResource>> findInnovationLeadsAddedToCompetition(@PathVariable("competitionId") final long competitionId); @PostMapping("/{competitionId}/add-innovation-lead/{innovationLeadUserId}") RestResult<Void> addInnovationLead(@PathVariable("competitionId") final long competitionId, @PathVariable("innovationLeadUserId") final long innovationLeadUserId); @PostMapping("/{competitionId}/remove-innovation-lead/{innovationLeadUserId}") RestResult<Void> removeInnovationLead(@PathVariable("competitionId") final long competitionId, @PathVariable("innovationLeadUserId") final long innovationLeadUserId); }
@Test public void findInnovationLeadsAddedToCompetition() throws Exception { final long competitionId = 1L; List<UserResource> innovationLeads = new ArrayList<>(); when(competitionSetupInnovationLeadService.findAddedInnovationLeads(competitionId)).thenReturn(serviceSuccess(innovationLeads)); mockMvc.perform(get("/competition/setup/{id}/innovation-leads/find-added", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(innovationLeads))); verify(competitionSetupInnovationLeadService, only()).findAddedInnovationLeads(competitionId); }
CompetitionSetupInnovationLeadController { @PostMapping("/{competitionId}/add-innovation-lead/{innovationLeadUserId}") public RestResult<Void> addInnovationLead(@PathVariable("competitionId") final long competitionId, @PathVariable("innovationLeadUserId") final long innovationLeadUserId) { return competitionSetupInnovationLeadService.addInnovationLead(competitionId, innovationLeadUserId).toPostResponse(); } @GetMapping("/{competitionId}/innovation-leads") RestResult<List<UserResource>> findAvailableInnovationLeadsNotAssignedToCompetition(@PathVariable("competitionId") final long competitionId); @GetMapping("/{competitionId}/innovation-leads/find-added") RestResult<List<UserResource>> findInnovationLeadsAddedToCompetition(@PathVariable("competitionId") final long competitionId); @PostMapping("/{competitionId}/add-innovation-lead/{innovationLeadUserId}") RestResult<Void> addInnovationLead(@PathVariable("competitionId") final long competitionId, @PathVariable("innovationLeadUserId") final long innovationLeadUserId); @PostMapping("/{competitionId}/remove-innovation-lead/{innovationLeadUserId}") RestResult<Void> removeInnovationLead(@PathVariable("competitionId") final long competitionId, @PathVariable("innovationLeadUserId") final long innovationLeadUserId); }
@Test public void addInnovationLead() throws Exception { final long competitionId = 1L; final long innovationLeadUserId = 2L; when(competitionSetupInnovationLeadService.addInnovationLead(competitionId, innovationLeadUserId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/competition/setup/{id}/add-innovation-lead/{innovationLeadUserId}", competitionId, innovationLeadUserId)) .andExpect(status().isOk()); verify(competitionSetupInnovationLeadService, only()).addInnovationLead(competitionId, innovationLeadUserId); }
CompetitionSetupInnovationLeadController { @PostMapping("/{competitionId}/remove-innovation-lead/{innovationLeadUserId}") public RestResult<Void> removeInnovationLead(@PathVariable("competitionId") final long competitionId, @PathVariable("innovationLeadUserId") final long innovationLeadUserId) { return competitionSetupInnovationLeadService.removeInnovationLead(competitionId, innovationLeadUserId).toPostResponse(); } @GetMapping("/{competitionId}/innovation-leads") RestResult<List<UserResource>> findAvailableInnovationLeadsNotAssignedToCompetition(@PathVariable("competitionId") final long competitionId); @GetMapping("/{competitionId}/innovation-leads/find-added") RestResult<List<UserResource>> findInnovationLeadsAddedToCompetition(@PathVariable("competitionId") final long competitionId); @PostMapping("/{competitionId}/add-innovation-lead/{innovationLeadUserId}") RestResult<Void> addInnovationLead(@PathVariable("competitionId") final long competitionId, @PathVariable("innovationLeadUserId") final long innovationLeadUserId); @PostMapping("/{competitionId}/remove-innovation-lead/{innovationLeadUserId}") RestResult<Void> removeInnovationLead(@PathVariable("competitionId") final long competitionId, @PathVariable("innovationLeadUserId") final long innovationLeadUserId); }
@Test public void removeInnovationLead() throws Exception { final long competitionId = 1L; final long innovationLeadUserId = 2L; when(competitionSetupInnovationLeadService.removeInnovationLead(competitionId, innovationLeadUserId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/competition/setup/{id}/remove-innovation-lead/{innovationLeadUserId}", competitionId, innovationLeadUserId)) .andExpect(status().isOk()); verify(competitionSetupInnovationLeadService).removeInnovationLead(competitionId, innovationLeadUserId); }
CompetitionSetupPostAwardServiceController { @PostMapping("/{competitionId}/post-award-service/{postAwardService}") public RestResult<Void> configurePostAwardService(@PathVariable("competitionId") final long competitionId, @PathVariable("postAwardService") final PostAwardService postAwardService) { return competitionSetupPostAwardServiceService.configurePostAwardService(competitionId, postAwardService).toPostResponse(); } @GetMapping("/{competitionId}/post-award-service") RestResult<CompetitionPostAwardServiceResource> postAwardService(@PathVariable("competitionId") final long competitionId); @PostMapping("/{competitionId}/post-award-service/{postAwardService}") RestResult<Void> configurePostAwardService(@PathVariable("competitionId") final long competitionId, @PathVariable("postAwardService") final PostAwardService postAwardService); }
@Test public void configurePostAwardService() throws Exception { final long competitionId = 1L; final PostAwardService postAwardService = PostAwardService.CONNECT; when(competitionSetupPostAwardServiceService.configurePostAwardService(competitionId, postAwardService)).thenReturn(serviceSuccess()); mockMvc.perform(post("/competition/setup/{id}/post-award-service/{innovationLeadUserId}", competitionId, postAwardService.name())) .andExpect(status().isOk()); verify(competitionSetupPostAwardServiceService, only()).configurePostAwardService(competitionId, postAwardService); }
CompetitionSetupFinanceUserController { @PostMapping("/{competitionId}/finance-users/invite") public RestResult<Void> inviteCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @RequestBody InviteUserResource inviteUserResource) { return competitionSetupFinanceUserService.inviteFinanceUser(inviteUserResource.getInvitedUser(), competitionId).toPostResponse(); } @PostMapping("/{competitionId}/finance-users/invite") RestResult<Void> inviteCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @RequestBody InviteUserResource inviteUserResource); @GetMapping("/{competitionId}/finance-users/find-all") RestResult<List<UserResource>> findCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId); @GetMapping("/get-finance-users-invite/{inviteHash}") RestResult<CompetitionFinanceInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/finance-users/create/{inviteHash}") RestResult<Void> createCompetitionFinanceUser(@PathVariable("inviteHash") String inviteHash, @RequestBody CompetitionFinanceRegistrationResource competitionFinanceRegistrationResource); @PostMapping("/{competitionId}/finance-users/{userId}/add") RestResult<Void> addCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @PathVariable("userId") final long userId); @PostMapping("/{competitionId}/finance-users/{userId}/remove") RestResult<Void> removeCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @PathVariable("userId") final long userId); @GetMapping("/{competitionId}/finance-users/pending-invites") RestResult<List<UserResource>> findPendingCompetitionFinanceUserInvites(@PathVariable("competitionId") final long competitionId); }
@Test public void inviteCompetitionFinanceUser() throws Exception { long competitionId = 1L; when(competitionSetupFinanceUserService.inviteFinanceUser(inviteUserResource.getInvitedUser(), competitionId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/competition/setup/{competitionId}/finance-users/invite", competitionId) .contentType(APPLICATION_JSON) .content(toJson(inviteUserResource))) .andExpect(status().isOk()); verify(competitionSetupFinanceUserService).inviteFinanceUser(inviteUserResource.getInvitedUser(), competitionId); }
CompetitionSetupFinanceUserController { @GetMapping("/{competitionId}/finance-users/find-all") public RestResult<List<UserResource>> findCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId) { return competitionSetupFinanceUserService.findFinanceUser(competitionId).toGetResponse(); } @PostMapping("/{competitionId}/finance-users/invite") RestResult<Void> inviteCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @RequestBody InviteUserResource inviteUserResource); @GetMapping("/{competitionId}/finance-users/find-all") RestResult<List<UserResource>> findCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId); @GetMapping("/get-finance-users-invite/{inviteHash}") RestResult<CompetitionFinanceInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/finance-users/create/{inviteHash}") RestResult<Void> createCompetitionFinanceUser(@PathVariable("inviteHash") String inviteHash, @RequestBody CompetitionFinanceRegistrationResource competitionFinanceRegistrationResource); @PostMapping("/{competitionId}/finance-users/{userId}/add") RestResult<Void> addCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @PathVariable("userId") final long userId); @PostMapping("/{competitionId}/finance-users/{userId}/remove") RestResult<Void> removeCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @PathVariable("userId") final long userId); @GetMapping("/{competitionId}/finance-users/pending-invites") RestResult<List<UserResource>> findPendingCompetitionFinanceUserInvites(@PathVariable("competitionId") final long competitionId); }
@Test public void findCompetitionFinanceUser() throws Exception { long competitionId = 1L; List<UserResource> competitionFinanceUsers = newUserResource().withRoleGlobal(Role.EXTERNAL_FINANCE).build(2); when(competitionSetupFinanceUserService.findFinanceUser(competitionId)).thenReturn(serviceSuccess(competitionFinanceUsers)); mockMvc.perform(get("/competition/setup/{competitionId}/finance-users/find-all", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(competitionFinanceUsers))); verify(competitionSetupFinanceUserService).findFinanceUser(competitionId); }
CompetitionSetupFinanceUserController { @GetMapping("/get-finance-users-invite/{inviteHash}") public RestResult<CompetitionFinanceInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash) { return competitionSetupFinanceUserService.getInviteByHash(inviteHash).toGetResponse(); } @PostMapping("/{competitionId}/finance-users/invite") RestResult<Void> inviteCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @RequestBody InviteUserResource inviteUserResource); @GetMapping("/{competitionId}/finance-users/find-all") RestResult<List<UserResource>> findCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId); @GetMapping("/get-finance-users-invite/{inviteHash}") RestResult<CompetitionFinanceInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/finance-users/create/{inviteHash}") RestResult<Void> createCompetitionFinanceUser(@PathVariable("inviteHash") String inviteHash, @RequestBody CompetitionFinanceRegistrationResource competitionFinanceRegistrationResource); @PostMapping("/{competitionId}/finance-users/{userId}/add") RestResult<Void> addCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @PathVariable("userId") final long userId); @PostMapping("/{competitionId}/finance-users/{userId}/remove") RestResult<Void> removeCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @PathVariable("userId") final long userId); @GetMapping("/{competitionId}/finance-users/pending-invites") RestResult<List<UserResource>> findPendingCompetitionFinanceUserInvites(@PathVariable("competitionId") final long competitionId); }
@Test public void getInvite() throws Exception { CompetitionFinanceInviteResource invite = new CompetitionFinanceInviteResource(); invite.setHash(TEST_HASH); when(competitionSetupFinanceUserService.getInviteByHash(TEST_HASH)).thenReturn(serviceSuccess(invite)); mockMvc.perform(get("/competition/setup/get-finance-users-invite/" + TEST_HASH)) .andExpect(status().isOk()); verify(competitionSetupFinanceUserService).getInviteByHash(TEST_HASH); }
CompetitionSetupFinanceUserController { @PostMapping("/finance-users/create/{inviteHash}") public RestResult<Void> createCompetitionFinanceUser(@PathVariable("inviteHash") String inviteHash, @RequestBody CompetitionFinanceRegistrationResource competitionFinanceRegistrationResource) { return registrationService.createUser(anUserCreationResource() .withFirstName(competitionFinanceRegistrationResource.getFirstName()) .withLastName(competitionFinanceRegistrationResource.getLastName()) .withPassword(competitionFinanceRegistrationResource.getPassword()) .withInviteHash(inviteHash) .withRole(Role.EXTERNAL_FINANCE) .build()) .andOnSuccessReturnVoid() .toPostCreateResponse(); } @PostMapping("/{competitionId}/finance-users/invite") RestResult<Void> inviteCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @RequestBody InviteUserResource inviteUserResource); @GetMapping("/{competitionId}/finance-users/find-all") RestResult<List<UserResource>> findCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId); @GetMapping("/get-finance-users-invite/{inviteHash}") RestResult<CompetitionFinanceInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/finance-users/create/{inviteHash}") RestResult<Void> createCompetitionFinanceUser(@PathVariable("inviteHash") String inviteHash, @RequestBody CompetitionFinanceRegistrationResource competitionFinanceRegistrationResource); @PostMapping("/{competitionId}/finance-users/{userId}/add") RestResult<Void> addCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @PathVariable("userId") final long userId); @PostMapping("/{competitionId}/finance-users/{userId}/remove") RestResult<Void> removeCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @PathVariable("userId") final long userId); @GetMapping("/{competitionId}/finance-users/pending-invites") RestResult<List<UserResource>> findPendingCompetitionFinanceUserInvites(@PathVariable("competitionId") final long competitionId); }
@Test public void createCompetitionFinanceUser() throws Exception { CompetitionFinanceRegistrationResource resource = new CompetitionFinanceRegistrationResource(); resource.setFirstName("Leny"); resource.setLastName("White"); when(registrationService.createUser(any())).thenReturn(serviceSuccess(newUserResource().build())); mockMvc.perform(post("/competition/setup/finance-users/create/" + TEST_HASH) .contentType(APPLICATION_JSON) .content(toJson(resource))) .andExpect(status().is2xxSuccessful()); verify(registrationService).createUser(any()); }
CompetitionSetupFinanceUserController { @PostMapping("/{competitionId}/finance-users/{userId}/remove") public RestResult<Void> removeCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @PathVariable("userId") final long userId) { return competitionSetupFinanceUserService.removeFinanceUser(competitionId, userId).toPostResponse(); } @PostMapping("/{competitionId}/finance-users/invite") RestResult<Void> inviteCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @RequestBody InviteUserResource inviteUserResource); @GetMapping("/{competitionId}/finance-users/find-all") RestResult<List<UserResource>> findCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId); @GetMapping("/get-finance-users-invite/{inviteHash}") RestResult<CompetitionFinanceInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/finance-users/create/{inviteHash}") RestResult<Void> createCompetitionFinanceUser(@PathVariable("inviteHash") String inviteHash, @RequestBody CompetitionFinanceRegistrationResource competitionFinanceRegistrationResource); @PostMapping("/{competitionId}/finance-users/{userId}/add") RestResult<Void> addCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @PathVariable("userId") final long userId); @PostMapping("/{competitionId}/finance-users/{userId}/remove") RestResult<Void> removeCompetitionFinanceUser(@PathVariable("competitionId") final long competitionId, @PathVariable("userId") final long userId); @GetMapping("/{competitionId}/finance-users/pending-invites") RestResult<List<UserResource>> findPendingCompetitionFinanceUserInvites(@PathVariable("competitionId") final long competitionId); }
@Test public void removeCompetitionFinanceUser() throws Exception { long competitionId = 1L; long competitionFinanceUserId = 2L; when(competitionSetupFinanceUserService.removeFinanceUser(competitionId, competitionFinanceUserId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/competition/setup/{competitionId}/finance-users/{userId}/remove", competitionId, competitionFinanceUserId)) .andExpect(status().isOk()); verify(competitionSetupFinanceUserService).removeFinanceUser(competitionId, competitionFinanceUserId); }
CompetitionSetupStakeholderController { @PostMapping("/{competitionId}/stakeholder/invite") public RestResult<Void> inviteStakeholder(@PathVariable("competitionId") final long competitionId, @RequestBody InviteUserResource inviteUserResource) { return competitionSetupStakeholderService.inviteStakeholder(inviteUserResource.getInvitedUser(), competitionId).toPostResponse(); } @PostMapping("/{competitionId}/stakeholder/invite") RestResult<Void> inviteStakeholder(@PathVariable("competitionId") final long competitionId, @RequestBody InviteUserResource inviteUserResource); @GetMapping("/{competitionId}/stakeholder/find-all") RestResult<List<UserResource>> findStakeholders(@PathVariable("competitionId") final long competitionId); @GetMapping("/get-stakeholder-invite/{inviteHash}") RestResult<StakeholderInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/stakeholder/create/{inviteHash}") RestResult<Void> createStakeholder(@PathVariable("inviteHash") String inviteHash, @RequestBody StakeholderRegistrationResource stakeholderRegistrationResource); @PostMapping("/{competitionId}/stakeholder/{stakeholderUserId}/add") RestResult<Void> addStakeholder(@PathVariable("competitionId") final long competitionId, @PathVariable("stakeholderUserId") final long stakeholderUserId); @PostMapping("/{competitionId}/stakeholder/{stakeholderUserId}/remove") RestResult<Void> removeStakeholder(@PathVariable("competitionId") final long competitionId, @PathVariable("stakeholderUserId") final long stakeholderUserId); @GetMapping("/{competitionId}/stakeholder/pending-invites") RestResult<List<UserResource>> findPendingStakeholderInvites(@PathVariable("competitionId") final long competitionId); }
@Test public void inviteStakeholder() throws Exception { long competitionId = 1L; when(competitionSetupStakeholderService.inviteStakeholder(inviteUserResource.getInvitedUser(), competitionId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/competition/setup/{competitionId}/stakeholder/invite", competitionId) .contentType(APPLICATION_JSON) .content(toJson(inviteUserResource))) .andExpect(status().isOk()); verify(competitionSetupStakeholderService).inviteStakeholder(inviteUserResource.getInvitedUser(), competitionId); }
CompetitionSetupStakeholderController { @GetMapping("/{competitionId}/stakeholder/find-all") public RestResult<List<UserResource>> findStakeholders(@PathVariable("competitionId") final long competitionId) { return competitionSetupStakeholderService.findStakeholders(competitionId).toGetResponse(); } @PostMapping("/{competitionId}/stakeholder/invite") RestResult<Void> inviteStakeholder(@PathVariable("competitionId") final long competitionId, @RequestBody InviteUserResource inviteUserResource); @GetMapping("/{competitionId}/stakeholder/find-all") RestResult<List<UserResource>> findStakeholders(@PathVariable("competitionId") final long competitionId); @GetMapping("/get-stakeholder-invite/{inviteHash}") RestResult<StakeholderInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/stakeholder/create/{inviteHash}") RestResult<Void> createStakeholder(@PathVariable("inviteHash") String inviteHash, @RequestBody StakeholderRegistrationResource stakeholderRegistrationResource); @PostMapping("/{competitionId}/stakeholder/{stakeholderUserId}/add") RestResult<Void> addStakeholder(@PathVariable("competitionId") final long competitionId, @PathVariable("stakeholderUserId") final long stakeholderUserId); @PostMapping("/{competitionId}/stakeholder/{stakeholderUserId}/remove") RestResult<Void> removeStakeholder(@PathVariable("competitionId") final long competitionId, @PathVariable("stakeholderUserId") final long stakeholderUserId); @GetMapping("/{competitionId}/stakeholder/pending-invites") RestResult<List<UserResource>> findPendingStakeholderInvites(@PathVariable("competitionId") final long competitionId); }
@Test public void findStakeholders() throws Exception { long competitionId = 1L; List<UserResource> stakeholderUsers = UserResourceBuilder.newUserResource().build(2); when(competitionSetupStakeholderService.findStakeholders(competitionId)).thenReturn(serviceSuccess(stakeholderUsers)); mockMvc.perform(get("/competition/setup/{competitionId}/stakeholder/find-all", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(stakeholderUsers))); verify(competitionSetupStakeholderService).findStakeholders(competitionId); }
CompetitionSetupStakeholderController { @GetMapping("/get-stakeholder-invite/{inviteHash}") public RestResult<StakeholderInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash) { return competitionSetupStakeholderService.getInviteByHash(inviteHash).toGetResponse(); } @PostMapping("/{competitionId}/stakeholder/invite") RestResult<Void> inviteStakeholder(@PathVariable("competitionId") final long competitionId, @RequestBody InviteUserResource inviteUserResource); @GetMapping("/{competitionId}/stakeholder/find-all") RestResult<List<UserResource>> findStakeholders(@PathVariable("competitionId") final long competitionId); @GetMapping("/get-stakeholder-invite/{inviteHash}") RestResult<StakeholderInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/stakeholder/create/{inviteHash}") RestResult<Void> createStakeholder(@PathVariable("inviteHash") String inviteHash, @RequestBody StakeholderRegistrationResource stakeholderRegistrationResource); @PostMapping("/{competitionId}/stakeholder/{stakeholderUserId}/add") RestResult<Void> addStakeholder(@PathVariable("competitionId") final long competitionId, @PathVariable("stakeholderUserId") final long stakeholderUserId); @PostMapping("/{competitionId}/stakeholder/{stakeholderUserId}/remove") RestResult<Void> removeStakeholder(@PathVariable("competitionId") final long competitionId, @PathVariable("stakeholderUserId") final long stakeholderUserId); @GetMapping("/{competitionId}/stakeholder/pending-invites") RestResult<List<UserResource>> findPendingStakeholderInvites(@PathVariable("competitionId") final long competitionId); }
@Test public void getInvite() throws Exception { StakeholderInviteResource invite = newStakeholderInviteResource() .withHash(TEST_HASH) .build(); when(competitionSetupStakeholderService.getInviteByHash(TEST_HASH)).thenReturn(serviceSuccess(invite)); mockMvc.perform(get("/competition/setup/get-stakeholder-invite/" + TEST_HASH)) .andExpect(status().isOk()); verify(competitionSetupStakeholderService).getInviteByHash(TEST_HASH); }
CompetitionSetupStakeholderController { @PostMapping("/{competitionId}/stakeholder/{stakeholderUserId}/add") public RestResult<Void> addStakeholder(@PathVariable("competitionId") final long competitionId, @PathVariable("stakeholderUserId") final long stakeholderUserId) { return competitionSetupStakeholderService.addStakeholder(competitionId, stakeholderUserId).toPostResponse(); } @PostMapping("/{competitionId}/stakeholder/invite") RestResult<Void> inviteStakeholder(@PathVariable("competitionId") final long competitionId, @RequestBody InviteUserResource inviteUserResource); @GetMapping("/{competitionId}/stakeholder/find-all") RestResult<List<UserResource>> findStakeholders(@PathVariable("competitionId") final long competitionId); @GetMapping("/get-stakeholder-invite/{inviteHash}") RestResult<StakeholderInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/stakeholder/create/{inviteHash}") RestResult<Void> createStakeholder(@PathVariable("inviteHash") String inviteHash, @RequestBody StakeholderRegistrationResource stakeholderRegistrationResource); @PostMapping("/{competitionId}/stakeholder/{stakeholderUserId}/add") RestResult<Void> addStakeholder(@PathVariable("competitionId") final long competitionId, @PathVariable("stakeholderUserId") final long stakeholderUserId); @PostMapping("/{competitionId}/stakeholder/{stakeholderUserId}/remove") RestResult<Void> removeStakeholder(@PathVariable("competitionId") final long competitionId, @PathVariable("stakeholderUserId") final long stakeholderUserId); @GetMapping("/{competitionId}/stakeholder/pending-invites") RestResult<List<UserResource>> findPendingStakeholderInvites(@PathVariable("competitionId") final long competitionId); }
@Test public void addStakeholder() throws Exception { long competitionId = 1L; long stakeholderUserId = 2L; when(competitionSetupStakeholderService.addStakeholder(competitionId, stakeholderUserId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/competition/setup/{competitionId}/stakeholder/{stakeholderUserId}/add", competitionId, stakeholderUserId)) .andExpect(status().isOk()); verify(competitionSetupStakeholderService).addStakeholder(competitionId, stakeholderUserId); }
CompetitionSetupStakeholderController { @PostMapping("/{competitionId}/stakeholder/{stakeholderUserId}/remove") public RestResult<Void> removeStakeholder(@PathVariable("competitionId") final long competitionId, @PathVariable("stakeholderUserId") final long stakeholderUserId) { return competitionSetupStakeholderService.removeStakeholder(competitionId, stakeholderUserId).toPostResponse(); } @PostMapping("/{competitionId}/stakeholder/invite") RestResult<Void> inviteStakeholder(@PathVariable("competitionId") final long competitionId, @RequestBody InviteUserResource inviteUserResource); @GetMapping("/{competitionId}/stakeholder/find-all") RestResult<List<UserResource>> findStakeholders(@PathVariable("competitionId") final long competitionId); @GetMapping("/get-stakeholder-invite/{inviteHash}") RestResult<StakeholderInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/stakeholder/create/{inviteHash}") RestResult<Void> createStakeholder(@PathVariable("inviteHash") String inviteHash, @RequestBody StakeholderRegistrationResource stakeholderRegistrationResource); @PostMapping("/{competitionId}/stakeholder/{stakeholderUserId}/add") RestResult<Void> addStakeholder(@PathVariable("competitionId") final long competitionId, @PathVariable("stakeholderUserId") final long stakeholderUserId); @PostMapping("/{competitionId}/stakeholder/{stakeholderUserId}/remove") RestResult<Void> removeStakeholder(@PathVariable("competitionId") final long competitionId, @PathVariable("stakeholderUserId") final long stakeholderUserId); @GetMapping("/{competitionId}/stakeholder/pending-invites") RestResult<List<UserResource>> findPendingStakeholderInvites(@PathVariable("competitionId") final long competitionId); }
@Test public void removeStakeholder() throws Exception { long competitionId = 1L; long stakeholderUserId = 2L; when(competitionSetupStakeholderService.removeStakeholder(competitionId, stakeholderUserId)).thenReturn(serviceSuccess()); mockMvc.perform(post("/competition/setup/{competitionId}/stakeholder/{stakeholderUserId}/remove", competitionId, stakeholderUserId)) .andExpect(status().isOk()); verify(competitionSetupStakeholderService).removeStakeholder(competitionId, stakeholderUserId); }
CompetitionSetupStakeholderController { @GetMapping("/{competitionId}/stakeholder/pending-invites") public RestResult<List<UserResource>> findPendingStakeholderInvites(@PathVariable("competitionId") final long competitionId) { return competitionSetupStakeholderService.findPendingStakeholderInvites(competitionId).toGetResponse(); } @PostMapping("/{competitionId}/stakeholder/invite") RestResult<Void> inviteStakeholder(@PathVariable("competitionId") final long competitionId, @RequestBody InviteUserResource inviteUserResource); @GetMapping("/{competitionId}/stakeholder/find-all") RestResult<List<UserResource>> findStakeholders(@PathVariable("competitionId") final long competitionId); @GetMapping("/get-stakeholder-invite/{inviteHash}") RestResult<StakeholderInviteResource> getInvite(@PathVariable("inviteHash") String inviteHash); @PostMapping("/stakeholder/create/{inviteHash}") RestResult<Void> createStakeholder(@PathVariable("inviteHash") String inviteHash, @RequestBody StakeholderRegistrationResource stakeholderRegistrationResource); @PostMapping("/{competitionId}/stakeholder/{stakeholderUserId}/add") RestResult<Void> addStakeholder(@PathVariable("competitionId") final long competitionId, @PathVariable("stakeholderUserId") final long stakeholderUserId); @PostMapping("/{competitionId}/stakeholder/{stakeholderUserId}/remove") RestResult<Void> removeStakeholder(@PathVariable("competitionId") final long competitionId, @PathVariable("stakeholderUserId") final long stakeholderUserId); @GetMapping("/{competitionId}/stakeholder/pending-invites") RestResult<List<UserResource>> findPendingStakeholderInvites(@PathVariable("competitionId") final long competitionId); }
@Test public void findPendingStakeholderInvites() throws Exception { long competitionId = 1L; List<UserResource> pendingStakeholderInvites = UserResourceBuilder.newUserResource().build(2); when(competitionSetupStakeholderService.findPendingStakeholderInvites(competitionId)).thenReturn(serviceSuccess(pendingStakeholderInvites)); mockMvc.perform(get("/competition/setup/{competitionId}/stakeholder/pending-invites", competitionId)) .andExpect(status().isOk()) .andExpect(content().json(toJson(pendingStakeholderInvites))); verify(competitionSetupStakeholderService).findPendingStakeholderInvites(competitionId); }
CompetitionSetupFinanceServiceImpl extends BaseTransactionalService implements CompetitionSetupFinanceService { @Override @Transactional public ServiceResult<Void> save(CompetitionSetupFinanceResource compSetupFinanceRes) { return getCompetition(compSetupFinanceRes.getCompetitionId()).andOnSuccess(competition -> { competition.setApplicationFinanceType(compSetupFinanceRes.getApplicationFinanceType()); competition.setIncludeJesForm(compSetupFinanceRes.getIncludeJesForm()); competition.setIncludeProjectGrowthTable(compSetupFinanceRes.getIncludeGrowthTable()); competition.setIncludeYourOrganisationSection(compSetupFinanceRes.getIncludeYourOrganisationSection()); return serviceSuccess(); }); } @Override @Transactional ServiceResult<Void> save(CompetitionSetupFinanceResource compSetupFinanceRes); @Override ServiceResult<CompetitionSetupFinanceResource> getForCompetition(long competitionId); }
@Test public void save() { long competitionId = 1L; boolean isIncludeGrowthTable = false; boolean isIncludeYourOrganisationSection = false; boolean includeJesForm = true; CompetitionSetupFinanceResource compSetupFinanceRes = newCompetitionSetupFinanceResource() .withCompetitionId(competitionId) .withIncludeGrowthTable(isIncludeGrowthTable) .withIncludeJesForm(includeJesForm) .withIncludeYourOrganisationSection(isIncludeYourOrganisationSection) .withApplicationFinanceType(STANDARD) .build(); Competition c = newCompetition().with(id(competitionId)) .withApplicationFinanceType(NO_FINANCES) .build(); when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.of(c)); ServiceResult<Void> save = service.save(compSetupFinanceRes); assertTrue(save.isSuccess()); assertEquals(STANDARD, c.getApplicationFinanceType()); assertFalse(c.getIncludeProjectGrowthTable()); assertFalse(c.getIncludeYourOrganisationSection()); assertEquals(c.getIncludeJesForm(), includeJesForm); }
UserPermissionRules { @PermissionRule(value = "READ", description = "The System Registration user can view everyone") public boolean systemRegistrationUserCanViewEveryone(UserResource userToView, UserResource user) { return isSystemRegistrationUser(user); } @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "An internal user can invite a monitoring officer and create the pending user associated.") boolean compAdminProjectFinanceCanCreateMonitoringOfficer(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserRegistrationResource userToCreate, UserResource user); @PermissionRule(value = "VERIFY", description = "A System Registration User can send a new User a verification link by e-mail") boolean systemRegistrationUserCanSendUserVerificationEmail(UserResource userToSendVerificationEmail, UserResource user); @PermissionRule(value = "READ", description = "Any user can view themselves") boolean anyUserCanViewThemselves(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Internal users can view everyone") boolean internalUsersCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can view users in competitions they are assigned to") boolean stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Competition finance users can view users in competitions they are assigned to") boolean competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can view users in projects they are assigned to") boolean monitoringOfficersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ_USER_ORGANISATION", description = "Internal support users can view all users and associated organisations") boolean internalUsersCanViewUserOrganisation(UserOrganisationResource userToView, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "IFS admins can update all users email addresses") boolean ifsAdminCanUpdateAllEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "Support users can update external users email addresses ") boolean supportCanUpdateExternalUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "System Maintenance update all users email addresses") boolean systemMaintenanceUserCanUpdateUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ_INTERNAL", description = "Administrators can view internal users") boolean internalUsersCanViewEveryone(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Support users and administrators can view external users") boolean supportUsersCanViewExternalUsers(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "The System Registration user can view everyone") boolean systemRegistrationUserCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Comp admins and project finance can view assessors") boolean compAdminAndProjectFinanceCanViewAssessors(UserPageResource usersToView, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewOtherConsortiumMembers(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewConsortiumUsersOnApplicationsTheyAreAssessing(UserResource userToView, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "A User should be able to change their own password") boolean usersCanChangeTheirOwnPassword(UserResource userToUpdate, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "The System Registration user should be able to change passwords on behalf of other Users") boolean systemRegistrationUserCanChangePasswordsForUsers(UserResource userToUpdate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A System Registration User can activate Users") boolean systemRegistrationUserCanActivateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "UPDATE", description = "A User can update their own profile") boolean usersCanUpdateTheirOwnProfiles(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE", description = "An admin user can update user details to assign monitoring officers") boolean adminsCanUpdateUserDetails(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile skills") boolean usersCanViewTheirOwnProfileSkills(ProfileSkillsResource profileSkills, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile agreement") boolean usersCanViewTheirOwnProfileAgreement(ProfileAgreementResource profileAgreementResource, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own affiliations") boolean usersCanViewTheirOwnAffiliations(AffiliationResource affiliation, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A user can read their own profile") boolean usersCanViewTheirOwnProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A ifs admin user can read any user's profile") boolean ifsAdminCanViewAnyUsersProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as Comp Admin and Exec can read the user's profile status") boolean usersAndCompAdminCanViewProfileStatus(UserProfileStatusResource profileStatus, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own role") boolean usersCanViewTheirOwnProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the process role of others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewTheProcessRolesOfOtherConsortiumMembers(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Project managers and partners can view the process role for the same organisation") boolean projectPartnersCanViewTheProcessRolesWithinSameApplication(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as internal users can read the user's process role") boolean usersAndInternalUsersCanViewProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the process roles of members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewTheProcessRolesOfConsortiumUsersOnApplicationsTheyAreAssessing(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "CHECK_USER_APPLICATION", description = "The user can check if they have an application for the competition") boolean userCanCheckTheyHaveApplicationForCompetition(UserResource userToCheck, UserResource user); @PermissionRule(value = "EDIT_INTERNAL_USER", description = "Only an IFS Administrator can edit an internal user") boolean ifsAdminCanEditInternalUser(final UserResource userToEdit, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "IFS Administrator can deactivate Users") boolean ifsAdminCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "A Support user can deactivate external Users") boolean supportUserCanDeactivateExternalUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "System Maintenance can deactivate Users") boolean systemMaintenanceUserCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "IFS Administrator can reactivate Users") boolean ifsAdminCanReactivateUsers(UserResource userToReactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A Support user can reactivate external Users") boolean supportUserCanReactivateExternalUsers(UserResource userToActivate, UserResource user); @PermissionRule(value = "AGREE_TERMS", description = "A user can accept the site terms and conditions") boolean usersCanAgreeSiteTermsAndConditions(UserResource userToUpdate, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An assessor can request applicant role") boolean assessorCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant monitoring officer role") boolean isGrantingMonitoringOfficerRoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant a KTA role") boolean isGrantingKTARoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An stakeholder can request applicant role") boolean stakeholderCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An monitoring officer can request applicant role") boolean monitoringOfficerCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "CAN_VIEW_OWN_DASHBOARD", description = "User is requesting own dashboard") boolean isViewingOwnDashboard(UserResource userToView, UserResource user); }
@Test public void systemRegistrationUserCanViewEveryone() { allGlobalRoleUsers.forEach(user -> allGlobalRoleUsers.forEach(otherUser -> { if (user.equals(systemRegistrationUser())) { assertTrue(rules.systemRegistrationUserCanViewEveryone(otherUser, user)); } else { assertFalse(rules.systemRegistrationUserCanViewEveryone(otherUser, user)); } })); }
CompetitionSetupFinanceServiceImpl extends BaseTransactionalService implements CompetitionSetupFinanceService { @Override public ServiceResult<CompetitionSetupFinanceResource> getForCompetition(long competitionId) { return getCompetition(competitionId).andOnSuccessReturn(this::buildCompetitionSetupFinanceResource); } @Override @Transactional ServiceResult<Void> save(CompetitionSetupFinanceResource compSetupFinanceRes); @Override ServiceResult<CompetitionSetupFinanceResource> getForCompetition(long competitionId); }
@Test public void getForCompetition_standardFinanceType() { Competition competition = newCompetition() .withApplicationFinanceType(STANDARD) .withIncludeProjectGrowthTable(true) .withIncludeYourOrganisationSection(true) .build(); when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition)); CompetitionSetupFinanceResource result = service.getForCompetition(competition.getId()).getSuccess(); assertEquals(STANDARD, result.getApplicationFinanceType()); assertTrue(result.getIncludeGrowthTable()); assertTrue(result.getIncludeYourOrganisationSection()); } @Test public void getForCompetition_noFinanceType() { Competition competition = newCompetition() .withApplicationFinanceType(NO_FINANCES) .withIncludeProjectGrowthTable(false) .withIncludeYourOrganisationSection(false) .build(); when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition)); CompetitionSetupFinanceResource result = service.getForCompetition(competition.getId()).getSuccess(); assertEquals(NO_FINANCES, result.getApplicationFinanceType()); assertFalse(result.getIncludeGrowthTable()); assertFalse(result.getIncludeYourOrganisationSection()); } @Test public void getForCompetition_nullFields() { Competition competition = newCompetition().build(); when(competitionRepositoryMock.findById(competition.getId())).thenReturn(Optional.of(competition)); CompetitionSetupFinanceResource result = service.getForCompetition(competition.getId()).getSuccess(); assertNull(result.getApplicationFinanceType()); assertNull(result.getIncludeGrowthTable()); assertNull(result.getIncludeYourOrganisationSection()); }
CompetitionSetupStakeholderServiceImpl extends BaseTransactionalService implements CompetitionSetupStakeholderService { @Override @Transactional public ServiceResult<Void> inviteStakeholder(UserResource invitedUser, long competitionId) { return validateInvite(invitedUser) .andOnSuccess(() -> validateUserIsNotInternal(invitedUser.getEmail())) .andOnSuccess(() -> validateUserInviteNotPending(competitionId, invitedUser)) .andOnSuccess(() -> validateUserNotAlreadyStakeholderOnCompetition(competitionId, invitedUser.getEmail())) .andOnSuccess(() -> getCompetition(competitionId)) .andOnSuccess(competition -> addOrInviteUser(competition, invitedUser) ); } @Override @Transactional ServiceResult<Void> inviteStakeholder(UserResource invitedUser, long competitionId); @Override ServiceResult<List<UserResource>> findStakeholders(long competitionId); @Override ServiceResult<StakeholderInviteResource> getInviteByHash(String hash); @Override @Transactional ServiceResult<Void> addStakeholder(long competitionId, long stakeholderUserId); @Override @Transactional ServiceResult<Void> removeStakeholder(long competitionId, long stakeholderUserId); @Override @Transactional ServiceResult<List<UserResource>> findPendingStakeholderInvites(long competitionId); }
@Test public void inviteStakeholderWhenUserDetailsMissing() throws Exception { UserResource invitedUser = UserResourceBuilder.newUserResource().build(); ServiceResult<Void> result = service.inviteStakeholder(invitedUser, 1L); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(STAKEHOLDER_INVITE_INVALID)); verify(stakeholderInviteRepositoryMock, never()).save(any(StakeholderInvite.class)); } @Test public void inviteStakeholderWhenEmailDomainIsIncorrect() throws Exception { invitedUser.setEmail("[email protected]"); ServiceResult<Void> result = service.inviteStakeholder(invitedUser, 1L); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(STAKEHOLDERS_CANNOT_BE_INTERNAL_USERS)); verify(stakeholderInviteRepositoryMock, never()).save(any(StakeholderInvite.class)); } @Test public void inviteAlreadyInvitedStakeholderFailure() throws Exception { long competitionId = 1L; String user1Name = "Rayon Kevin"; String user2Name = "Sonal Dsilva"; String user1Email = "[email protected]"; String user2Email = "[email protected]"; when(stakeholderInviteRepositoryMock.existsByCompetitionIdAndStatusAndEmail(competitionId, SENT, user1Email)).thenReturn(true); ServiceResult<Void> result = service.inviteStakeholder(invitedUser, 1L); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(STAKEHOLDER_INVITE_TARGET_USER_ALREADY_INVITED)); verify(stakeholderInviteRepositoryMock, never()).save(any(StakeholderInvite.class)); verify(stakeholderInviteRepositoryMock).existsByCompetitionIdAndStatusAndEmail(competitionId, SENT, user1Email); } @Test public void inviteUserAlreadyStakeholderOnCompetitionFailure() { long competitionId = 1L; long stakeholderUser1 = 12L; long stakeholderUser2 = 14L; String email1 = "[email protected]"; String email2 = "[email protected]"; List<User> stakeholderUsers = UserBuilder.newUser() .withId(stakeholderUser1, stakeholderUser2) .withEmailAddress(email1, email2) .build(2); List<Stakeholder> stakeholders = StakeholderBuilder.newStakeholder() .withUser(stakeholderUsers.get(0), stakeholderUsers.get(1)) .build(2); when(stakeholderInviteRepositoryMock.existsByCompetitionIdAndStatusAndEmail(competitionId, SENT, email1)).thenReturn(false); when(stakeholderRepositoryMock.existsByCompetitionIdAndStakeholderEmail(competitionId, email2)).thenReturn(true); ServiceResult<Void> result = service.inviteStakeholder(invitedUser, 1L); assertTrue(result.isFailure()); assertTrue(result.getFailure().is(STAKEHOLDER_HAS_ACCEPTED_INVITE)); } @Test public void addExistingUserAsStakeholder() { long competitionId = 1L; long stakeholderUserId = 2L; String competitionName = "competition1"; Competition competition = CompetitionBuilder.newCompetition() .withId(competitionId) .withName(competitionName) .build(); User stakeholderUser = UserBuilder.newUser() .withId(stakeholderUserId) .withFirstName("Rayon") .withLastName("Kevin") .withEmailAddress("[email protected]") .build(); Stakeholder savedStakeholderInDB = new Stakeholder(competition, stakeholderUser); User user = newUser().withId(stakeholderUserId).withEmailAddress("[email protected]").build(); ArgumentCaptor<Notification> notificationCaptor = ArgumentCaptor.forClass(Notification.class); when(stakeholderInviteRepositoryMock.existsByCompetitionIdAndStatusAndEmail(competitionId, SENT, stakeholderUser.getEmail())).thenReturn(false); when(stakeholderRepositoryMock.existsByCompetitionIdAndStakeholderEmail(competitionId, stakeholderUser.getEmail())).thenReturn(false); when(userRepositoryMock.findByEmail(invitedUser.getEmail())).thenReturn(Optional.of(user)); when(userRepositoryMock.save(any(User.class))).thenReturn(stakeholderUser); when(userRepositoryMock.findById(stakeholderUserId)).thenReturn(Optional.of(stakeholderUser)); when(stakeholderRepositoryMock.save(any(Stakeholder.class))).thenReturn(savedStakeholderInDB); when(notificationServiceMock.sendNotificationWithFlush(any(Notification.class), eq(EMAIL))).thenReturn(serviceSuccess()); when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.of(competition)); ServiceResult<Void> result = service.inviteStakeholder(invitedUser, 1L); assertTrue(result.isSuccess()); verify(userService).evictUserCache(user.getUid()); verify(stakeholderRepositoryMock).save(savedStakeholderInDB); verify(notificationServiceMock).sendNotificationWithFlush(notificationCaptor.capture(), eq(EMAIL)); } @Test public void inviteStakeholderSuccess() throws Exception { long competitionId = 1L; String competitionName = "competition1"; Competition competition = CompetitionBuilder.newCompetition() .withId(competitionId) .withName(competitionName) .build(); when(userRepositoryMock.findByEmail(invitedUser.getEmail())).thenReturn(Optional.empty()); when(stakeholderInviteRepositoryMock.findByEmail(invitedUser.getEmail())).thenReturn(Collections.emptyList()); when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.of(competition)); StakeholderInvite savedStakeholderInvite = new StakeholderInvite(competition, invitedUser.getFirstName() + " " + invitedUser.getLastName(), invitedUser.getEmail(), generateInviteHash(), CREATED); when(stakeholderInviteRepositoryMock.save(any(StakeholderInvite.class))).thenReturn(savedStakeholderInvite); when(notificationServiceMock.sendNotificationWithFlush(any(Notification.class), eq(EMAIL))).thenReturn(serviceSuccess()); User loggedInUser = newUser().build(); when(loggedInUserSupplierMock.get()).thenReturn(loggedInUser); ServiceResult<Void> result = service.inviteStakeholder(invitedUser, competitionId); assertTrue(result.isSuccess()); verify(stakeholderInviteRepositoryMock, times(2)).save(any(StakeholderInvite.class)); ArgumentCaptor<StakeholderInvite> captor = ArgumentCaptor.forClass(StakeholderInvite.class); verify(stakeholderInviteRepositoryMock, times(2)).save(captor.capture()); String expectedName = "Rayon Kevin"; String expectedEmail = "[email protected]"; StakeholderInvite savedStakeholderInvite1 = captor.getAllValues().get(0); assertEquals(competition, savedStakeholderInvite1.getTarget()); assertEquals(expectedName, savedStakeholderInvite1.getName()); assertEquals(expectedEmail, savedStakeholderInvite1.getEmail()); assertNotNull(savedStakeholderInvite1.getHash()); assertEquals(CREATED, savedStakeholderInvite1.getStatus()); assertNull(savedStakeholderInvite1.getSentBy()); assertNull(savedStakeholderInvite1.getSentOn()); ArgumentCaptor<Notification> notificationCaptor = ArgumentCaptor.forClass(Notification.class); verify(notificationServiceMock).sendNotificationWithFlush(notificationCaptor.capture(), eq(EMAIL)); Notification sentNotification = notificationCaptor.getValue(); assertEquals("competition1", sentNotification.getGlobalArguments().get("competitionName")); assertEquals("null/management/stakeholder/" + savedStakeholderInvite.getHash() + "/register", sentNotification.getGlobalArguments().get("inviteUrl")); assertEquals(expectedName, sentNotification.getTo().get(0).getName()); assertEquals(expectedEmail, sentNotification.getTo().get(0).getEmailAddress()); assertEquals(CompetitionSetupStakeholderServiceImpl.Notifications.STAKEHOLDER_INVITE, sentNotification.getMessageKey()); StakeholderInvite savedStakeholderInvite2 = captor.getAllValues().get(1); assertEquals(competition, savedStakeholderInvite2.getTarget()); assertEquals(expectedName, savedStakeholderInvite2.getName()); assertEquals(expectedEmail, savedStakeholderInvite2.getEmail()); assertNotNull(savedStakeholderInvite2.getHash()); assertEquals(SENT, savedStakeholderInvite2.getStatus()); assertEquals(loggedInUser, savedStakeholderInvite2.getSentBy()); assertFalse(now().isBefore(savedStakeholderInvite2.getSentOn())); }
CompetitionSetupStakeholderServiceImpl extends BaseTransactionalService implements CompetitionSetupStakeholderService { @Override public ServiceResult<List<UserResource>> findStakeholders(long competitionId) { List<Stakeholder> stakeholders = stakeholderRepository.findStakeholders(competitionId); List<UserResource> stakeholderUsers = simpleMap(stakeholders, stakeholder -> userMapper.mapToResource(stakeholder.getUser())); return serviceSuccess(stakeholderUsers); } @Override @Transactional ServiceResult<Void> inviteStakeholder(UserResource invitedUser, long competitionId); @Override ServiceResult<List<UserResource>> findStakeholders(long competitionId); @Override ServiceResult<StakeholderInviteResource> getInviteByHash(String hash); @Override @Transactional ServiceResult<Void> addStakeholder(long competitionId, long stakeholderUserId); @Override @Transactional ServiceResult<Void> removeStakeholder(long competitionId, long stakeholderUserId); @Override @Transactional ServiceResult<List<UserResource>> findPendingStakeholderInvites(long competitionId); }
@Test public void findStakeholders() throws Exception { long competitionId = 1L; long stakeholderUser1 = 12L; long stakeholderUser2 = 14L; List<User> stakeholderUsers = UserBuilder.newUser() .withId(stakeholderUser1, stakeholderUser2) .build(2); List<UserResource> stakeholderUserResources = UserResourceBuilder.newUserResource() .withId(stakeholderUser1, stakeholderUser2) .build(2); List<Stakeholder> stakeholders = StakeholderBuilder.newStakeholder() .withUser(stakeholderUsers.get(0), stakeholderUsers.get(1)) .build(2); when(stakeholderRepositoryMock.findStakeholders(competitionId)).thenReturn(stakeholders); when(userMapperMock.mapToResource(stakeholderUsers.get(0))).thenReturn(stakeholderUserResources.get(0)); when(userMapperMock.mapToResource(stakeholderUsers.get(1))).thenReturn(stakeholderUserResources.get(1)); ServiceResult<List<UserResource>> result = service.findStakeholders(competitionId); assertTrue(result.isSuccess()); assertEquals(stakeholderUserResources, result.getSuccess()); verify(stakeholderRepositoryMock).findStakeholders(competitionId); }
UserPermissionRules { @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") public boolean systemRegistrationUserCanCreateUsers(UserCreationResource userToCreate, UserResource user) { return isSystemRegistrationUser(user); } @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "An internal user can invite a monitoring officer and create the pending user associated.") boolean compAdminProjectFinanceCanCreateMonitoringOfficer(UserCreationResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "CREATE", description = "A System Registration User can create new Users on behalf of non-logged in users") boolean systemRegistrationUserCanCreateUsers(UserRegistrationResource userToCreate, UserResource user); @PermissionRule(value = "VERIFY", description = "A System Registration User can send a new User a verification link by e-mail") boolean systemRegistrationUserCanSendUserVerificationEmail(UserResource userToSendVerificationEmail, UserResource user); @PermissionRule(value = "READ", description = "Any user can view themselves") boolean anyUserCanViewThemselves(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Internal users can view everyone") boolean internalUsersCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Stakeholders can view users in competitions they are assigned to") boolean stakeholdersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Competition finance users can view users in competitions they are assigned to") boolean competitionFinanceUsersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Monitoring officers can view users in projects they are assigned to") boolean monitoringOfficersCanViewUsersInCompetitionsTheyAreAssignedTo(UserResource userToView, UserResource user); @PermissionRule(value = "READ_USER_ORGANISATION", description = "Internal support users can view all users and associated organisations") boolean internalUsersCanViewUserOrganisation(UserOrganisationResource userToView, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "IFS admins can update all users email addresses") boolean ifsAdminCanUpdateAllEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "Support users can update external users email addresses ") boolean supportCanUpdateExternalUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE_USER_EMAIL", description = "System Maintenance update all users email addresses") boolean systemMaintenanceUserCanUpdateUsersEmailAddresses(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ_INTERNAL", description = "Administrators can view internal users") boolean internalUsersCanViewEveryone(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Support users and administrators can view external users") boolean supportUsersCanViewExternalUsers(ManageUserPageResource userToView, UserResource user); @PermissionRule(value = "READ", description = "The System Registration user can view everyone") boolean systemRegistrationUserCanViewEveryone(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Comp admins and project finance can view assessors") boolean compAdminAndProjectFinanceCanViewAssessors(UserPageResource usersToView, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewOtherConsortiumMembers(UserResource userToView, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewConsortiumUsersOnApplicationsTheyAreAssessing(UserResource userToView, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "A User should be able to change their own password") boolean usersCanChangeTheirOwnPassword(UserResource userToUpdate, UserResource user); @PermissionRule(value = "CHANGE_PASSWORD", description = "The System Registration user should be able to change passwords on behalf of other Users") boolean systemRegistrationUserCanChangePasswordsForUsers(UserResource userToUpdate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A System Registration User can activate Users") boolean systemRegistrationUserCanActivateUsers(UserResource userToCreate, UserResource user); @PermissionRule(value = "UPDATE", description = "A User can update their own profile") boolean usersCanUpdateTheirOwnProfiles(UserResource userToUpdate, UserResource user); @PermissionRule(value = "UPDATE", description = "An admin user can update user details to assign monitoring officers") boolean adminsCanUpdateUserDetails(UserResource userToUpdate, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile skills") boolean usersCanViewTheirOwnProfileSkills(ProfileSkillsResource profileSkills, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own profile agreement") boolean usersCanViewTheirOwnProfileAgreement(ProfileAgreementResource profileAgreementResource, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own affiliations") boolean usersCanViewTheirOwnAffiliations(AffiliationResource affiliation, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A user can read their own profile") boolean usersCanViewTheirOwnProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ_USER_PROFILE", description = "A ifs admin user can read any user's profile") boolean ifsAdminCanViewAnyUsersProfile(UserProfileResource profileDetails, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as Comp Admin and Exec can read the user's profile status") boolean usersAndCompAdminCanViewProfileStatus(UserProfileStatusResource profileStatus, UserResource user); @PermissionRule(value = "READ", description = "A user can read their own role") boolean usersCanViewTheirOwnProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Consortium members (Lead Applicants and Collaborators) can view the process role of others in their Consortium Teams on their various Applications") boolean consortiumMembersCanViewTheProcessRolesOfOtherConsortiumMembers(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Project managers and partners can view the process role for the same organisation") boolean projectPartnersCanViewTheProcessRolesWithinSameApplication(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "The user, as well as internal users can read the user's process role") boolean usersAndInternalUsersCanViewProcessRole(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "READ", description = "Assessors can view the process roles of members of individual Consortiums on the various Applications that they are assessing") boolean assessorsCanViewTheProcessRolesOfConsortiumUsersOnApplicationsTheyAreAssessing(ProcessRoleResource processRole, UserResource user); @PermissionRule(value = "CHECK_USER_APPLICATION", description = "The user can check if they have an application for the competition") boolean userCanCheckTheyHaveApplicationForCompetition(UserResource userToCheck, UserResource user); @PermissionRule(value = "EDIT_INTERNAL_USER", description = "Only an IFS Administrator can edit an internal user") boolean ifsAdminCanEditInternalUser(final UserResource userToEdit, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "IFS Administrator can deactivate Users") boolean ifsAdminCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "A Support user can deactivate external Users") boolean supportUserCanDeactivateExternalUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "DEACTIVATE", description = "System Maintenance can deactivate Users") boolean systemMaintenanceUserCanDeactivateUsers(UserResource userToDeactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "IFS Administrator can reactivate Users") boolean ifsAdminCanReactivateUsers(UserResource userToReactivate, UserResource user); @PermissionRule(value = "ACTIVATE", description = "A Support user can reactivate external Users") boolean supportUserCanReactivateExternalUsers(UserResource userToActivate, UserResource user); @PermissionRule(value = "AGREE_TERMS", description = "A user can accept the site terms and conditions") boolean usersCanAgreeSiteTermsAndConditions(UserResource userToUpdate, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An assessor can request applicant role") boolean assessorCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant monitoring officer role") boolean isGrantingMonitoringOfficerRoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An admin user can grant a KTA role") boolean isGrantingKTARoleAndHasPermission(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An stakeholder can request applicant role") boolean stakeholderCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "GRANT_ROLE", description = "An monitoring officer can request applicant role") boolean monitoringOfficerCanRequestApplicantRole(GrantRoleCommand roleCommand, UserResource user); @PermissionRule(value = "CAN_VIEW_OWN_DASHBOARD", description = "User is requesting own dashboard") boolean isViewingOwnDashboard(UserResource userToView, UserResource user); }
@Test public void systemRegistrationUserCanCreateUsers() { allGlobalRoleUsers.forEach(user -> { if (user.equals(systemRegistrationUser())) { assertTrue(rules.systemRegistrationUserCanCreateUsers(newUserResource().build(), user)); } else { assertFalse(rules.systemRegistrationUserCanCreateUsers(newUserResource().build(), user)); } }); } @Test public void systemRegistrationUserCanCreateUsers_UserRegistrationResource() { allGlobalRoleUsers.forEach(user -> { if (user.equals(systemRegistrationUser())) { assertTrue(rules.systemRegistrationUserCanCreateUsers(newUserRegistrationResource().build(), user)); } else { assertFalse(rules.systemRegistrationUserCanCreateUsers(newUserRegistrationResource().build(), user)); } }); }
CompetitionSetupStakeholderServiceImpl extends BaseTransactionalService implements CompetitionSetupStakeholderService { @Override @Transactional public ServiceResult<Void> addStakeholder(long competitionId, long stakeholderUserId) { return getCompetition(competitionId) .andOnSuccessReturnVoid(competition -> find(userRepository.findById(stakeholderUserId), notFoundError(User.class, stakeholderUserId)) .andOnSuccess(stakeholderUser -> { Stakeholder savedStakeholder = stakeholderRepository.save(new Stakeholder(competition, stakeholderUser)); return sendAddStakeholderNotification(savedStakeholder, competition); }) ); } @Override @Transactional ServiceResult<Void> inviteStakeholder(UserResource invitedUser, long competitionId); @Override ServiceResult<List<UserResource>> findStakeholders(long competitionId); @Override ServiceResult<StakeholderInviteResource> getInviteByHash(String hash); @Override @Transactional ServiceResult<Void> addStakeholder(long competitionId, long stakeholderUserId); @Override @Transactional ServiceResult<Void> removeStakeholder(long competitionId, long stakeholderUserId); @Override @Transactional ServiceResult<List<UserResource>> findPendingStakeholderInvites(long competitionId); }
@Test public void addStakeholder() throws Exception { long competitionId = 1L; long stakeholderUserId = 2L; String competitionName = "competition1"; Competition competition = CompetitionBuilder.newCompetition() .withId(competitionId) .withName(competitionName) .build(); String stakeholderFirstName = "Rayon"; String stakeholderLastName = "Kevin"; String stakeholderUserEmail = "[email protected]"; User stakeholderUser = UserBuilder.newUser() .withId(stakeholderUserId) .withFirstName(stakeholderFirstName) .withLastName(stakeholderLastName) .withEmailAddress(stakeholderUserEmail) .build(); Stakeholder savedStakeholderInDB = new Stakeholder(competition, stakeholderUser); when(competitionRepositoryMock.findById(competitionId)).thenReturn(Optional.of(competition)); when(userRepositoryMock.findById(stakeholderUserId)).thenReturn(Optional.of(stakeholderUser)); when(stakeholderRepositoryMock.save(any(Stakeholder.class))).thenReturn(savedStakeholderInDB); when(notificationServiceMock.sendNotificationWithFlush(any(Notification.class), eq(EMAIL))).thenReturn(serviceSuccess()); ServiceResult<Void> result = service.addStakeholder(competitionId, stakeholderUserId); assertTrue(result.isSuccess()); verify(stakeholderRepositoryMock).save(any(Stakeholder.class)); ArgumentCaptor<Stakeholder> captor = ArgumentCaptor.forClass(Stakeholder.class); verify(stakeholderRepositoryMock).save(captor.capture()); Stakeholder savedStakeholder = captor.getValue(); assertEquals(competition, savedStakeholder.getProcess()); assertEquals(stakeholderUser, savedStakeholder.getUser()); assertEquals(CompetitionParticipantRole.STAKEHOLDER, savedStakeholder.getRole()); assertEquals(ParticipantStatus.ACCEPTED, savedStakeholder.getStatus()); verify(notificationServiceMock).sendNotificationWithFlush(any(Notification.class), eq(EMAIL)); ArgumentCaptor<Notification> notificationCaptor = ArgumentCaptor.forClass(Notification.class); verify(notificationServiceMock).sendNotificationWithFlush(notificationCaptor.capture(), eq(EMAIL)); Notification sentNotification = notificationCaptor.getValue(); assertEquals(competitionName, sentNotification.getGlobalArguments().get("competitionName")); assertEquals("null/management/dashboard/live", sentNotification.getGlobalArguments().get("dashboardUrl")); assertEquals(stakeholderFirstName + " " + stakeholderLastName, sentNotification.getTo().get(0).getName()); assertEquals(stakeholderUserEmail, sentNotification.getTo().get(0).getEmailAddress()); assertEquals(CompetitionSetupStakeholderServiceImpl.Notifications.ADD_STAKEHOLDER, sentNotification.getMessageKey()); }
CompetitionSetupStakeholderServiceImpl extends BaseTransactionalService implements CompetitionSetupStakeholderService { @Override @Transactional public ServiceResult<Void> removeStakeholder(long competitionId, long stakeholderUserId) { stakeholderRepository.deleteStakeholder(competitionId, stakeholderUserId); return serviceSuccess(); } @Override @Transactional ServiceResult<Void> inviteStakeholder(UserResource invitedUser, long competitionId); @Override ServiceResult<List<UserResource>> findStakeholders(long competitionId); @Override ServiceResult<StakeholderInviteResource> getInviteByHash(String hash); @Override @Transactional ServiceResult<Void> addStakeholder(long competitionId, long stakeholderUserId); @Override @Transactional ServiceResult<Void> removeStakeholder(long competitionId, long stakeholderUserId); @Override @Transactional ServiceResult<List<UserResource>> findPendingStakeholderInvites(long competitionId); }
@Test public void removeStakeholder() throws Exception { long competitionId = 1L; long stakeholderUserId = 2L; ServiceResult<Void> result = service.removeStakeholder(competitionId, stakeholderUserId); assertTrue(result.isSuccess()); verify(stakeholderRepositoryMock).deleteStakeholder(competitionId, stakeholderUserId); }
CompetitionSetupStakeholderServiceImpl extends BaseTransactionalService implements CompetitionSetupStakeholderService { @Override @Transactional public ServiceResult<List<UserResource>> findPendingStakeholderInvites(long competitionId) { List<StakeholderInvite> pendingStakeholderInvites = stakeholderInviteRepository.findByCompetitionIdAndStatus(competitionId, SENT); List<UserResource> pendingStakeholderInviteUsers = simpleMap(pendingStakeholderInvites, pendingStakeholderInvite -> convert(pendingStakeholderInvite)); return serviceSuccess(pendingStakeholderInviteUsers); } @Override @Transactional ServiceResult<Void> inviteStakeholder(UserResource invitedUser, long competitionId); @Override ServiceResult<List<UserResource>> findStakeholders(long competitionId); @Override ServiceResult<StakeholderInviteResource> getInviteByHash(String hash); @Override @Transactional ServiceResult<Void> addStakeholder(long competitionId, long stakeholderUserId); @Override @Transactional ServiceResult<Void> removeStakeholder(long competitionId, long stakeholderUserId); @Override @Transactional ServiceResult<List<UserResource>> findPendingStakeholderInvites(long competitionId); }
@Test public void findPendingStakeholderInvites() throws Exception { long competitionId = 1L; String user1Name = "Rayon Kevin"; String user2Name = "Sonal Dsilva"; String user1Email = "[email protected]"; String user2Email = "[email protected]"; List<StakeholderInvite> pendingStakeholderInvites = StakeholderInviteBuilder.newStakeholderInvite() .withName(user1Name, user2Name) .withEmail(user1Email, user2Email) .build(2); when(stakeholderInviteRepositoryMock.findByCompetitionIdAndStatus(competitionId, SENT)).thenReturn(pendingStakeholderInvites); ServiceResult<List<UserResource>> result = service.findPendingStakeholderInvites(competitionId); assertTrue(result.isSuccess()); verify(stakeholderInviteRepositoryMock).findByCompetitionIdAndStatus(competitionId, SENT); assertEquals(user1Name, result.getSuccess().get(0).getFirstName()); assertEquals(user2Name, result.getSuccess().get(1).getFirstName()); assertEquals(user1Email, result.getSuccess().get(0).getEmail()); assertEquals(user2Email, result.getSuccess().get(1).getEmail()); }
CompetitionSetupServiceImpl extends BaseTransactionalService implements CompetitionSetupService { @Override public ServiceResult<Map<CompetitionSetupSection, Optional<Boolean>>> getSectionStatuses(Long competitionId) { List<SetupStatusResource> setupStatuses = setupStatusService .findByTargetClassNameAndTargetId(Competition.class.getName(), competitionId).getSuccess(); return serviceSuccess(Arrays.stream(CompetitionSetupSection.values()) .collect(Collectors.toMap(section -> section, section -> findStatus(setupStatuses, section.getClass().getName(), section.getId())))); } @Override @Transactional ServiceResult<String> generateCompetitionCode(Long id, ZonedDateTime dateTime); @Override @Transactional ServiceResult<CompetitionResource> save(Long id, CompetitionResource competitionResource); @Override @Transactional ServiceResult<Void> updateCompetitionInitialDetails(final Long competitionId, final CompetitionResource competitionResource, final Long existingInnovationLeadId); @Override @Transactional ServiceResult<CompetitionResource> create(); @Override @Transactional ServiceResult<CompetitionResource> createNonIfs(); @Override ServiceResult<Map<CompetitionSetupSection, Optional<Boolean>>> getSectionStatuses(Long competitionId); @Override ServiceResult<Map<CompetitionSetupSubsection, Optional<Boolean>>> getSubsectionStatuses(Long competitionId); @Override @Transactional ServiceResult<SetupStatusResource> markSectionComplete(Long competitionId, CompetitionSetupSection section); @Override @Transactional ServiceResult<List<SetupStatusResource>> markSectionIncomplete(long competitionId, CompetitionSetupSection section); @Override @Transactional ServiceResult<SetupStatusResource> markSubsectionComplete(Long competitionId, CompetitionSetupSection parentSection, CompetitionSetupSubsection subsection); @Override @Transactional ServiceResult<SetupStatusResource> markSubsectionIncomplete(Long competitionId, CompetitionSetupSection parentSection, CompetitionSetupSubsection subsection); @Override @Transactional ServiceResult<Void> returnToSetup(Long competitionId); @Override @Transactional ServiceResult<Void> markAsSetup(Long competitionId); @Override @Transactional ServiceResult<Void> copyFromCompetitionTypeTemplate(Long competitionId, Long competitionTypeId); @Override @Transactional ServiceResult<Void> deleteCompetition(long competitionId); @Override @Transactional ServiceResult<FileEntryResource> uploadCompetitionTerms(String contentType, String contentLength, String originalFilename, long competitionId, HttpServletRequest request); @Override @Transactional ServiceResult<Void> deleteCompetitionTerms(long competitionId); static final BigDecimal DEFAULT_ASSESSOR_PAY; }
@Test public void testGetSectionStatuses() { final Long competitionId = 6939L; when(setupStatusService.findByTargetClassNameAndTargetId(Competition.class.getName(), competitionId)) .thenReturn(ServiceResult.serviceSuccess(newSetupStatusResource().withId(23L) .withTargetClassName(Competition.class.getName()) .withTargetId(competitionId) .withClassPk(INITIAL_DETAILS.getId()) .withClassName(INITIAL_DETAILS.getClass().getName()) .withCompleted(Boolean.TRUE) .build(1))); Map<CompetitionSetupSection, Optional<Boolean>> resultMap = service.getSectionStatuses(competitionId).getSuccess(); assertTrue(resultMap.containsKey(CompetitionSetupSection.HOME)); assertEquals(Boolean.TRUE, resultMap.get(INITIAL_DETAILS).orElse(Boolean.FALSE)); assertEquals(Boolean.FALSE, resultMap.get(APPLICATION_FORM).orElse(Boolean.FALSE)); }
CompetitionSetupServiceImpl extends BaseTransactionalService implements CompetitionSetupService { @Override @Transactional public ServiceResult<Void> copyFromCompetitionTypeTemplate(Long competitionId, Long competitionTypeId) { return competitionSetupTemplateService.initializeCompetitionByCompetitionTemplate(competitionId, competitionTypeId) .andOnSuccessReturnVoid(); } @Override @Transactional ServiceResult<String> generateCompetitionCode(Long id, ZonedDateTime dateTime); @Override @Transactional ServiceResult<CompetitionResource> save(Long id, CompetitionResource competitionResource); @Override @Transactional ServiceResult<Void> updateCompetitionInitialDetails(final Long competitionId, final CompetitionResource competitionResource, final Long existingInnovationLeadId); @Override @Transactional ServiceResult<CompetitionResource> create(); @Override @Transactional ServiceResult<CompetitionResource> createNonIfs(); @Override ServiceResult<Map<CompetitionSetupSection, Optional<Boolean>>> getSectionStatuses(Long competitionId); @Override ServiceResult<Map<CompetitionSetupSubsection, Optional<Boolean>>> getSubsectionStatuses(Long competitionId); @Override @Transactional ServiceResult<SetupStatusResource> markSectionComplete(Long competitionId, CompetitionSetupSection section); @Override @Transactional ServiceResult<List<SetupStatusResource>> markSectionIncomplete(long competitionId, CompetitionSetupSection section); @Override @Transactional ServiceResult<SetupStatusResource> markSubsectionComplete(Long competitionId, CompetitionSetupSection parentSection, CompetitionSetupSubsection subsection); @Override @Transactional ServiceResult<SetupStatusResource> markSubsectionIncomplete(Long competitionId, CompetitionSetupSection parentSection, CompetitionSetupSubsection subsection); @Override @Transactional ServiceResult<Void> returnToSetup(Long competitionId); @Override @Transactional ServiceResult<Void> markAsSetup(Long competitionId); @Override @Transactional ServiceResult<Void> copyFromCompetitionTypeTemplate(Long competitionId, Long competitionTypeId); @Override @Transactional ServiceResult<Void> deleteCompetition(long competitionId); @Override @Transactional ServiceResult<FileEntryResource> uploadCompetitionTerms(String contentType, String contentLength, String originalFilename, long competitionId, HttpServletRequest request); @Override @Transactional ServiceResult<Void> deleteCompetitionTerms(long competitionId); static final BigDecimal DEFAULT_ASSESSOR_PAY; }
@Test public void copyFromCompetitionTypeTemplate() { long typeId = 4L; long competitionId = 2L; Competition competitionTemplate = newCompetition().build(); when(competitionSetupTemplateService.initializeCompetitionByCompetitionTemplate(competitionId, typeId)).thenReturn(ServiceResult.serviceSuccess(competitionTemplate)); ServiceResult<Void> result = service.copyFromCompetitionTypeTemplate(competitionId, typeId); assertTrue(result.isSuccess()); verify(competitionSetupTemplateService, times(1)).initializeCompetitionByCompetitionTemplate(competitionId, typeId); }
CompetitionSetupServiceImpl extends BaseTransactionalService implements CompetitionSetupService { @Override @Transactional public ServiceResult<Void> markAsSetup(Long competitionId) { Competition competition = competitionRepository.findById(competitionId).get(); competition.setSetupComplete(true); return serviceSuccess(); } @Override @Transactional ServiceResult<String> generateCompetitionCode(Long id, ZonedDateTime dateTime); @Override @Transactional ServiceResult<CompetitionResource> save(Long id, CompetitionResource competitionResource); @Override @Transactional ServiceResult<Void> updateCompetitionInitialDetails(final Long competitionId, final CompetitionResource competitionResource, final Long existingInnovationLeadId); @Override @Transactional ServiceResult<CompetitionResource> create(); @Override @Transactional ServiceResult<CompetitionResource> createNonIfs(); @Override ServiceResult<Map<CompetitionSetupSection, Optional<Boolean>>> getSectionStatuses(Long competitionId); @Override ServiceResult<Map<CompetitionSetupSubsection, Optional<Boolean>>> getSubsectionStatuses(Long competitionId); @Override @Transactional ServiceResult<SetupStatusResource> markSectionComplete(Long competitionId, CompetitionSetupSection section); @Override @Transactional ServiceResult<List<SetupStatusResource>> markSectionIncomplete(long competitionId, CompetitionSetupSection section); @Override @Transactional ServiceResult<SetupStatusResource> markSubsectionComplete(Long competitionId, CompetitionSetupSection parentSection, CompetitionSetupSubsection subsection); @Override @Transactional ServiceResult<SetupStatusResource> markSubsectionIncomplete(Long competitionId, CompetitionSetupSection parentSection, CompetitionSetupSubsection subsection); @Override @Transactional ServiceResult<Void> returnToSetup(Long competitionId); @Override @Transactional ServiceResult<Void> markAsSetup(Long competitionId); @Override @Transactional ServiceResult<Void> copyFromCompetitionTypeTemplate(Long competitionId, Long competitionTypeId); @Override @Transactional ServiceResult<Void> deleteCompetition(long competitionId); @Override @Transactional ServiceResult<FileEntryResource> uploadCompetitionTerms(String contentType, String contentLength, String originalFilename, long competitionId, HttpServletRequest request); @Override @Transactional ServiceResult<Void> deleteCompetitionTerms(long competitionId); static final BigDecimal DEFAULT_ASSESSOR_PAY; }
@Test public void testMarkAsSetup() { Long competitionId = 1L; Competition comp = new Competition(); when(competitionRepository.findById(competitionId)).thenReturn(Optional.of(comp)); service.markAsSetup(competitionId); assertTrue(comp.getSetupComplete()); }
CompetitionSetupServiceImpl extends BaseTransactionalService implements CompetitionSetupService { @Override @Transactional public ServiceResult<Void> returnToSetup(Long competitionId) { Competition competition = competitionRepository.findById(competitionId).get(); competition.setSetupComplete(false); return serviceSuccess(); } @Override @Transactional ServiceResult<String> generateCompetitionCode(Long id, ZonedDateTime dateTime); @Override @Transactional ServiceResult<CompetitionResource> save(Long id, CompetitionResource competitionResource); @Override @Transactional ServiceResult<Void> updateCompetitionInitialDetails(final Long competitionId, final CompetitionResource competitionResource, final Long existingInnovationLeadId); @Override @Transactional ServiceResult<CompetitionResource> create(); @Override @Transactional ServiceResult<CompetitionResource> createNonIfs(); @Override ServiceResult<Map<CompetitionSetupSection, Optional<Boolean>>> getSectionStatuses(Long competitionId); @Override ServiceResult<Map<CompetitionSetupSubsection, Optional<Boolean>>> getSubsectionStatuses(Long competitionId); @Override @Transactional ServiceResult<SetupStatusResource> markSectionComplete(Long competitionId, CompetitionSetupSection section); @Override @Transactional ServiceResult<List<SetupStatusResource>> markSectionIncomplete(long competitionId, CompetitionSetupSection section); @Override @Transactional ServiceResult<SetupStatusResource> markSubsectionComplete(Long competitionId, CompetitionSetupSection parentSection, CompetitionSetupSubsection subsection); @Override @Transactional ServiceResult<SetupStatusResource> markSubsectionIncomplete(Long competitionId, CompetitionSetupSection parentSection, CompetitionSetupSubsection subsection); @Override @Transactional ServiceResult<Void> returnToSetup(Long competitionId); @Override @Transactional ServiceResult<Void> markAsSetup(Long competitionId); @Override @Transactional ServiceResult<Void> copyFromCompetitionTypeTemplate(Long competitionId, Long competitionTypeId); @Override @Transactional ServiceResult<Void> deleteCompetition(long competitionId); @Override @Transactional ServiceResult<FileEntryResource> uploadCompetitionTerms(String contentType, String contentLength, String originalFilename, long competitionId, HttpServletRequest request); @Override @Transactional ServiceResult<Void> deleteCompetitionTerms(long competitionId); static final BigDecimal DEFAULT_ASSESSOR_PAY; }
@Test public void testReturnToSetup() { Long competitionId = 1L; Competition comp = new Competition(); when(competitionRepository.findById(competitionId)).thenReturn(Optional.of(comp)); service.returnToSetup(competitionId); assertFalse(comp.getSetupComplete()); }