diff --git a/.browserslistrc b/.browserslistrc deleted file mode 100644 index 427441dc93..0000000000 --- a/.browserslistrc +++ /dev/null @@ -1,17 +0,0 @@ -# This file is used by the build system to adjust CSS and JS output to support the specified browsers below. -# For additional information regarding the format and rule options, please see: -# https://github.com/browserslist/browserslist#queries - -# For the full list of supported browsers by the Angular framework, please see: -# https://angular.io/guide/browser-support - -# You can see what browsers were selected by your queries by running: -# npx browserslist - -last 1 Chrome version -last 1 Firefox version -last 2 Edge major versions -last 2 Safari major versions -last 2 iOS major versions -Firefox ESR -not IE 11 # Angular supports IE 11 only as an opt-in. To opt-in, remove the 'not' prefix on this line. diff --git a/.github/disabled-workflows/pull_request_opened.yml b/.github/disabled-workflows/pull_request_opened.yml deleted file mode 100644 index 0dc718c0b9..0000000000 --- a/.github/disabled-workflows/pull_request_opened.yml +++ /dev/null @@ -1,26 +0,0 @@ -# This workflow runs whenever a new pull request is created -# TEMPORARILY DISABLED. Unfortunately this doesn't work for PRs created from forked repositories (which is how we tend to create PRs). -# There is no known workaround yet. See https://github.community/t/how-to-use-github-token-for-prs-from-forks/16818 -name: Pull Request opened - -# Only run for newly opened PRs against the "main" branch -on: - pull_request: - types: [opened] - branches: - - main - -jobs: - automation: - runs-on: ubuntu-latest - steps: - # Assign the PR to whomever created it. This is useful for visualizing assignments on project boards - # See https://github.com/marketplace/actions/pull-request-assigner - - name: Assign PR to creator - uses: thomaseizinger/assign-pr-creator-action@v1.0.0 - # Note, this authentication token is created automatically - # See: https://docs.github.com/en/actions/configuring-and-managing-workflows/authenticating-with-the-github_token - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - # Ignore errors. It is possible the PR was created by someone who cannot be assigned - continue-on-error: true diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 6fae54f1f9..219074780e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -31,6 +31,8 @@ jobs: # When Chrome version is specified, we pin to a specific version of Chrome # Comment this out to use the latest release #CHROME_VERSION: "90.0.4430.212-1" + # Bump Node heap size (OOM in CI after upgrading to Angular 15) + NODE_OPTIONS: '--max-old-space-size=4096' strategy: # Create a matrix of Node versions to test against (in parallel) matrix: diff --git a/.github/workflows/codescan.yml b/.github/workflows/codescan.yml index 35a2e2d24a..8b415296c7 100644 --- a/.github/workflows/codescan.yml +++ b/.github/workflows/codescan.yml @@ -5,12 +5,16 @@ # because CodeQL requires a fresh build with all tests *disabled*. name: "Code Scanning" -# Run this code scan for all pushes / PRs to main branch. Also run once a week. +# Run this code scan for all pushes / PRs to main or maintenance branches. Also run once a week. on: push: - branches: [ main ] + branches: + - main + - 'dspace-**' pull_request: - branches: [ main ] + branches: + - main + - 'dspace-**' # Don't run if PR is only updating static documentation paths-ignore: - '**/*.md' diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 9a2c838d83..0c36d5af98 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -15,29 +15,35 @@ on: permissions: contents: read # to fetch code (actions/checkout) + +env: + # Define tags to use for Docker images based on Git tags/branches (for docker/metadata-action) + # For a new commit on default branch (main), use the literal tag 'latest' on Docker image. + # For a new commit on other branches, use the branch name as the tag for Docker image. + # For a new tag, copy that tag name as the tag for Docker image. + IMAGE_TAGS: | + type=raw,value=latest,enable=${{ endsWith(github.ref, github.event.repository.default_branch) }} + type=ref,event=branch,enable=${{ !endsWith(github.ref, github.event.repository.default_branch) }} + type=ref,event=tag + # Define default tag "flavor" for docker/metadata-action per + # https://github.com/docker/metadata-action#flavor-input + # We manage the 'latest' tag ourselves to the 'main' branch (see settings above) + TAGS_FLAVOR: | + latest=false + # Architectures / Platforms for which we will build Docker images + # If this is a PR, we ONLY build for AMD64. For PRs we only do a sanity check test to ensure Docker builds work. + # If this is NOT a PR (e.g. a tag or merge commit), also build for ARM64. + PLATFORMS: linux/amd64${{ github.event_name != 'pull_request' && ', linux/arm64' || '' }} + + jobs: - docker: + ############################################### + # Build/Push the 'dspace/dspace-angular' image + ############################################### + dspace-angular: # Ensure this job never runs on forked repos. It's only executed for 'dspace/dspace-angular' if: github.repository == 'dspace/dspace-angular' runs-on: ubuntu-latest - env: - # Define tags to use for Docker images based on Git tags/branches (for docker/metadata-action) - # For a new commit on default branch (main), use the literal tag 'dspace-7_x' on Docker image. - # For a new commit on other branches, use the branch name as the tag for Docker image. - # For a new tag, copy that tag name as the tag for Docker image. - IMAGE_TAGS: | - type=raw,value=dspace-7_x,enable=${{ endsWith(github.ref, github.event.repository.default_branch) }} - type=ref,event=branch,enable=${{ !endsWith(github.ref, github.event.repository.default_branch) }} - type=ref,event=tag - # Define default tag "flavor" for docker/metadata-action per - # https://github.com/docker/metadata-action#flavor-input - # We turn off 'latest' tag by default. - TAGS_FLAVOR: | - latest=false - # Architectures / Platforms for which we will build Docker images - # If this is a PR, we ONLY build for AMD64. For PRs we only do a sanity check test to ensure Docker builds work. - # If this is NOT a PR (e.g. a tag or merge commit), also build for ARM64. - PLATFORMS: linux/amd64${{ github.event_name != 'pull_request' && ', linux/arm64' || '' }} steps: # https://github.com/actions/checkout @@ -61,9 +67,6 @@ jobs: username: ${{ secrets.DOCKER_USERNAME }} password: ${{ secrets.DOCKER_ACCESS_TOKEN }} - ############################################### - # Build/Push the 'dspace/dspace-angular' image - ############################################### # https://github.com/docker/metadata-action # Get Metadata for docker_build step below - name: Sync metadata (tags, labels) from GitHub to Docker for 'dspace-angular' image @@ -77,7 +80,7 @@ jobs: # https://github.com/docker/build-push-action - name: Build and push 'dspace-angular' image id: docker_build - uses: docker/build-push-action@v3 + uses: docker/build-push-action@v4 with: context: . file: ./Dockerfile @@ -89,9 +92,36 @@ jobs: tags: ${{ steps.meta_build.outputs.tags }} labels: ${{ steps.meta_build.outputs.labels }} - ##################################################### - # Build/Push the 'dspace/dspace-angular' image ('-dist' tag) - ##################################################### + ############################################################# + # Build/Push the 'dspace/dspace-angular' image ('-dist' tag) + ############################################################# + dspace-angular-dist: + # Ensure this job never runs on forked repos. It's only executed for 'dspace/dspace-angular' + if: github.repository == 'dspace/dspace-angular' + runs-on: ubuntu-latest + + steps: + # https://github.com/actions/checkout + - name: Checkout codebase + uses: actions/checkout@v3 + + # https://github.com/docker/setup-buildx-action + - name: Setup Docker Buildx + uses: docker/setup-buildx-action@v2 + + # https://github.com/docker/setup-qemu-action + - name: Set up QEMU emulation to build for multiple architectures + uses: docker/setup-qemu-action@v2 + + # https://github.com/docker/login-action + - name: Login to DockerHub + # Only login if not a PR, as PRs only trigger a Docker build and not a push + if: github.event_name != 'pull_request' + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKER_USERNAME }} + password: ${{ secrets.DOCKER_ACCESS_TOKEN }} + # https://github.com/docker/metadata-action # Get Metadata for docker_build_dist step below - name: Sync metadata (tags, labels) from GitHub to Docker for 'dspace-angular-dist' image @@ -107,7 +137,7 @@ jobs: - name: Build and push 'dspace-angular-dist' image id: docker_build_dist - uses: docker/build-push-action@v3 + uses: docker/build-push-action@v4 with: context: . file: ./Dockerfile.dist diff --git a/.github/workflows/label_merge_conflicts.yml b/.github/workflows/label_merge_conflicts.yml index c1396b6f45..ccc6c401c0 100644 --- a/.github/workflows/label_merge_conflicts.yml +++ b/.github/workflows/label_merge_conflicts.yml @@ -1,11 +1,12 @@ # This workflow checks open PRs for merge conflicts and labels them when conflicts are found name: Check for merge conflicts -# Run whenever the "main" branch is updated -# NOTE: This means merge conflicts are only checked for when a PR is merged to main. +# Run this for all pushes (i.e. merges) to 'main' or maintenance branches on: push: - branches: [ main ] + branches: + - main + - 'dspace-**' # So that the `conflict_label_name` is removed if conflicts are resolved, # we allow this to run for `pull_request_target` so that github secrets are available. pull_request_target: @@ -24,6 +25,8 @@ jobs: # See: https://github.com/prince-chrismc/label-merge-conflicts-action - name: Auto-label PRs with merge conflicts uses: prince-chrismc/label-merge-conflicts-action@v3 + # Ignore any failures -- may occur (randomly?) for older, outdated PRs. + continue-on-error: true # Add "merge conflict" label if a merge conflict is detected. Remove it when resolved. # Note, the authentication token is created automatically # See: https://docs.github.com/en/actions/configuring-and-managing-workflows/authenticating-with-the-github_token diff --git a/.github/workflows/port_merged_pull_request.yml b/.github/workflows/port_merged_pull_request.yml new file mode 100644 index 0000000000..50faf3f886 --- /dev/null +++ b/.github/workflows/port_merged_pull_request.yml @@ -0,0 +1,44 @@ +# This workflow will attempt to port a merged pull request to +# the branch specified in a "port to" label (if exists) +name: Port merged Pull Request + +# Only run for merged PRs against the "main" or maintenance branches +# We allow this to run for `pull_request_target` so that github secrets are available +# (This is required when the PR comes from a forked repo) +on: + pull_request_target: + types: [ closed ] + branches: + - main + - 'dspace-**' + +permissions: + contents: write # so action can add comments + pull-requests: write # so action can create pull requests + +jobs: + port_pr: + runs-on: ubuntu-latest + # Don't run on closed *unmerged* pull requests + if: github.event.pull_request.merged + steps: + # Checkout code + - uses: actions/checkout@v3 + # Port PR to other branch (ONLY if labeled with "port to") + # See https://github.com/korthout/backport-action + - name: Create backport pull requests + uses: korthout/backport-action@v1 + with: + # Trigger based on a "port to [branch]" label on PR + # (This label must specify the branch name to port to) + label_pattern: '^port to ([^ ]+)$' + # Title to add to the (newly created) port PR + pull_title: '[Port ${target_branch}] ${pull_title}' + # Description to add to the (newly created) port PR + pull_description: 'Port of #${pull_number} by @${pull_author} to `${target_branch}`.' + # Copy all labels from original PR to (newly created) port PR + # NOTE: The labels matching 'label_pattern' are automatically excluded + copy_labels_pattern: '.*' + # Use a personal access token (PAT) to create PR as 'dspace-bot' user. + # A PAT is required in order for the new PR to trigger its own actions (for CI checks) + github_token: ${{ secrets.PR_PORT_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/pull_request_opened.yml b/.github/workflows/pull_request_opened.yml new file mode 100644 index 0000000000..9b61af72d1 --- /dev/null +++ b/.github/workflows/pull_request_opened.yml @@ -0,0 +1,24 @@ +# This workflow runs whenever a new pull request is created +name: Pull Request opened + +# Only run for newly opened PRs against the "main" or maintenance branches +# We allow this to run for `pull_request_target` so that github secrets are available +# (This is required to assign a PR back to the creator when the PR comes from a forked repo) +on: + pull_request_target: + types: [ opened ] + branches: + - main + - 'dspace-**' + +permissions: + pull-requests: write + +jobs: + automation: + runs-on: ubuntu-latest + steps: + # Assign the PR to whomever created it. This is useful for visualizing assignments on project boards + # See https://github.com/toshimaru/auto-author-assign + - name: Assign PR to creator + uses: toshimaru/auto-author-assign@v1.6.2 diff --git a/.gitignore b/.gitignore index bdd0d4e589..7d065aca06 100644 --- a/.gitignore +++ b/.gitignore @@ -39,3 +39,5 @@ package-lock.json /nbproject/ junit.xml + +/src/mirador-viewer/config.local.js diff --git a/Dockerfile.dist b/Dockerfile.dist index 2a6a66fc06..e4b467ae26 100644 --- a/Dockerfile.dist +++ b/Dockerfile.dist @@ -2,7 +2,7 @@ # See https://github.com/DSpace/dspace-angular/tree/main/docker for usage details # Test build: -# docker build -f Dockerfile.dist -t dspace/dspace-angular:dspace-7_x-dist . +# docker build -f Dockerfile.dist -t dspace/dspace-angular:latest-dist . FROM node:18-alpine as build diff --git a/README.md b/README.md index c90dc1d08f..689c64a292 100644 --- a/README.md +++ b/README.md @@ -413,8 +413,7 @@ dspace-angular │ ├── merge-i18n-files.ts * │ ├── serve.ts * │ ├── sync-i18n-files.ts * -│ ├── test-rest.ts * -│ └── webpack.js * +│ └── test-rest.ts * ├── src * The source of the application │ ├── app * The source code of the application, subdivided by module/page. │ ├── assets * Folder for static resources diff --git a/angular.json b/angular.json index 56c75d7b2d..5e597d4d30 100644 --- a/angular.json +++ b/angular.json @@ -274,9 +274,18 @@ } } }, - "defaultProject": "dspace-angular", "cli": { "analytics": false, - "defaultCollection": "@angular-eslint/schematics" + "schematicCollections": [ + "@angular-eslint/schematics" + ] + }, + "schematics": { + "@angular-eslint/schematics:application": { + "setParserOptionsProject": true + }, + "@angular-eslint/schematics:library": { + "setParserOptionsProject": true + } } } diff --git a/config/config.example.yml b/config/config.example.yml index f1e6be76aa..ea38303fa3 100644 --- a/config/config.example.yml +++ b/config/config.example.yml @@ -187,6 +187,9 @@ languages: - code: gd label: Gàidhlig active: true + - code: it + label: Italiano + active: true - code: lv label: Latviešu active: true @@ -214,6 +217,9 @@ languages: - code: tr label: Türkçe active: true + - code: vi + label: Tiếng Việt + active: true - code: kk label: Қазақ active: true diff --git a/cypress/e2e/homepage.cy.ts b/cypress/e2e/homepage.cy.ts index 8fdf61dbf7..a387c31a2a 100644 --- a/cypress/e2e/homepage.cy.ts +++ b/cypress/e2e/homepage.cy.ts @@ -6,8 +6,8 @@ describe('Homepage', () => { cy.visit('/'); }); - it('should display translated title "DSpace Angular :: Home"', () => { - cy.title().should('eq', 'DSpace Angular :: Home'); + it('should display translated title "DSpace Repository :: Home"', () => { + cy.title().should('eq', 'DSpace Repository :: Home'); }); it('should contain a news section', () => { diff --git a/docker/README.md b/docker/README.md index 42deb793f9..08801137b0 100644 --- a/docker/README.md +++ b/docker/README.md @@ -23,14 +23,14 @@ the Docker compose scripts in this 'docker' folder. This Dockerfile is used to build a *development* DSpace 7 Angular UI image, published as 'dspace/dspace-angular' ``` -docker build -t dspace/dspace-angular:dspace-7_x . +docker build -t dspace/dspace-angular:latest . ``` This image is built *automatically* after each commit is made to the `main` branch. Admins to our DockerHub repo can manually publish with the following command. ``` -docker push dspace/dspace-angular:dspace-7_x +docker push dspace/dspace-angular:latest ``` ### Dockerfile.dist @@ -39,7 +39,7 @@ The `Dockerfile.dist` is used to generate a *production* build and runtime envir ```bash # build the latest image -docker build -f Dockerfile.dist -t dspace/dspace-angular:dspace-7_x-dist . +docker build -f Dockerfile.dist -t dspace/dspace-angular:latest-dist . ``` A default/demo version of this image is built *automatically*. diff --git a/docker/cli.yml b/docker/cli.yml index 54b83d4503..223ec356b9 100644 --- a/docker/cli.yml +++ b/docker/cli.yml @@ -16,7 +16,7 @@ version: "3.7" services: dspace-cli: - image: "${DOCKER_OWNER:-dspace}/dspace-cli:${DSPACE_VER:-dspace-7_x}" + image: "${DOCKER_OWNER:-dspace}/dspace-cli:${DSPACE_VER:-latest}" container_name: dspace-cli environment: # Below syntax may look odd, but it is how to override dspace.cfg settings via env variables. diff --git a/docker/docker-compose-ci.yml b/docker/docker-compose-ci.yml index 9ec8fe664a..edbb5b0759 100644 --- a/docker/docker-compose-ci.yml +++ b/docker/docker-compose-ci.yml @@ -35,7 +35,7 @@ services: solr__D__statistics__P__autoCommit: 'false' depends_on: - dspacedb - image: dspace/dspace:dspace-7_x-test + image: dspace/dspace:latest-test networks: dspacenet: ports: diff --git a/docker/docker-compose-dist.yml b/docker/docker-compose-dist.yml index 1c75539da9..a9ee4a2656 100644 --- a/docker/docker-compose-dist.yml +++ b/docker/docker-compose-dist.yml @@ -27,7 +27,7 @@ services: DSPACE_REST_HOST: api7.dspace.org DSPACE_REST_PORT: 443 DSPACE_REST_NAMESPACE: /server - image: dspace/dspace-angular:dspace-7_x-dist + image: dspace/dspace-angular:${DSPACE_VER:-latest}-dist build: context: .. dockerfile: Dockerfile.dist diff --git a/docker/docker-compose-rest.yml b/docker/docker-compose-rest.yml index e5f62600e7..ea766600ef 100644 --- a/docker/docker-compose-rest.yml +++ b/docker/docker-compose-rest.yml @@ -39,7 +39,7 @@ services: # proxies.trusted.ipranges: This setting is required for a REST API running in Docker to trust requests # from the host machine. This IP range MUST correspond to the 'dspacenet' subnet defined above. proxies__P__trusted__P__ipranges: '172.23.0' - image: "${DOCKER_OWNER:-dspace}/dspace:${DSPACE_VER:-dspace-7_x-test}" + image: "${DOCKER_OWNER:-dspace}/dspace:${DSPACE_VER:-latest-test}" depends_on: - dspacedb networks: @@ -82,7 +82,7 @@ services: # DSpace Solr container dspacesolr: container_name: dspacesolr - image: "${DOCKER_OWNER:-dspace}/dspace-solr:${DSPACE_VER:-dspace-7_x}" + image: "${DOCKER_OWNER:-dspace}/dspace-solr:${DSPACE_VER:-latest}" # Needs main 'dspace' container to start first to guarantee access to solr_configs depends_on: - dspace diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index 1387b1de39..1071b8d6ce 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -24,7 +24,7 @@ services: DSPACE_REST_HOST: localhost DSPACE_REST_PORT: 8080 DSPACE_REST_NAMESPACE: /server - image: dspace/dspace-angular:dspace-7_x + image: dspace/dspace-angular:${DSPACE_VER:-latest} build: context: .. dockerfile: Dockerfile diff --git a/package.json b/package.json index e1bedeb02b..977a4bdc5e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dspace-angular", - "version": "7.6.0-next", + "version": "8.0.0-next", "scripts": { "ng": "ng", "config:watch": "nodemon", @@ -17,9 +17,9 @@ "build:stats": "ng build --stats-json", "build:prod": "yarn run build:ssr", "build:ssr": "ng build --configuration production && ng run dspace-angular:server:production", - "test": "ng test --sourceMap=true --watch=false --configuration test", - "test:watch": "nodemon --exec \"ng test --sourceMap=true --watch=true --configuration test\"", - "test:headless": "ng test --sourceMap=true --watch=false --configuration test --browsers=ChromeHeadless --code-coverage", + "test": "ng test --source-map=true --watch=false --configuration test", + "test:watch": "nodemon --exec \"ng test --source-map=true --watch=true --configuration test\"", + "test:headless": "ng test --source-map=true --watch=false --configuration test --browsers=ChromeHeadless --code-coverage", "lint": "ng lint", "lint-fix": "ng lint --fix=true", "e2e": "ng e2e", @@ -55,136 +55,136 @@ "ts-node": "10.2.1" }, "dependencies": { - "@angular/animations": "~13.3.12", - "@angular/cdk": "^13.2.6", - "@angular/common": "~13.3.12", - "@angular/compiler": "~13.3.12", - "@angular/core": "~13.3.12", - "@angular/forms": "~13.3.12", - "@angular/localize": "13.3.12", - "@angular/platform-browser": "~13.3.12", - "@angular/platform-browser-dynamic": "~13.3.12", - "@angular/platform-server": "~13.3.12", - "@angular/router": "~13.3.12", - "@babel/runtime": "7.17.2", + "@angular/animations": "^15.2.8", + "@angular/cdk": "^15.2.8", + "@angular/common": "^15.2.8", + "@angular/compiler": "^15.2.8", + "@angular/core": "^15.2.8", + "@angular/forms": "^15.2.8", + "@angular/localize": "15.2.8", + "@angular/platform-browser": "^15.2.8", + "@angular/platform-browser-dynamic": "^15.2.8", + "@angular/platform-server": "^15.2.8", + "@angular/router": "^15.2.8", + "@babel/runtime": "7.21.0", "@kolkov/ngx-gallery": "^2.0.1", "@material-ui/core": "^4.11.0", - "@material-ui/icons": "^4.9.1", + "@material-ui/icons": "^4.11.3", "@ng-bootstrap/ng-bootstrap": "^11.0.0", "@ng-dynamic-forms/core": "^15.0.0", "@ng-dynamic-forms/ui-ng-bootstrap": "^15.0.0", - "@ngrx/effects": "^13.0.2", - "@ngrx/router-store": "^13.0.2", - "@ngrx/store": "^13.0.2", - "@nguniversal/express-engine": "^13.0.2", - "@ngx-translate/core": "^13.0.0", - "@nicky-lenaers/ngx-scroll-to": "^13.0.0", + "@ngrx/effects": "^15.4.0", + "@ngrx/router-store": "^15.4.0", + "@ngrx/store": "^15.4.0", + "@nguniversal/express-engine": "^15.2.1", + "@ngx-translate/core": "^14.0.0", + "@nicky-lenaers/ngx-scroll-to": "^14.0.0", "@types/grecaptcha": "^3.0.4", "angular-idle-preload": "3.0.0", - "angulartics2": "^12.0.0", + "angulartics2": "^12.2.0", "axios": "^0.27.2", "bootstrap": "^4.6.1", "cerialize": "0.1.18", - "cli-progress": "^3.8.0", + "cli-progress": "^3.12.0", "colors": "^1.4.0", "compression": "^1.7.4", - "cookie-parser": "1.4.5", - "core-js": "^3.7.0", + "cookie-parser": "1.4.6", + "core-js": "^3.30.1", "date-fns": "^2.29.3", "date-fns-tz": "^1.3.7", - "deepmerge": "^4.2.2", - "ejs": "^3.1.8", - "express": "^4.17.1", + "deepmerge": "^4.3.1", + "ejs": "^3.1.9", + "express": "^4.18.2", "express-rate-limit": "^5.1.3", - "fast-json-patch": "^3.0.0-1", + "fast-json-patch": "^3.1.1", "filesize": "^6.1.0", "http-proxy-middleware": "^1.0.5", - "isbot": "^3.6.5", + "isbot": "^3.6.10", "js-cookie": "2.2.1", "js-yaml": "^4.1.0", - "json5": "^2.2.2", - "jsonschema": "1.4.0", + "json5": "^2.2.3", + "jsonschema": "1.4.1", "jwt-decode": "^3.1.2", "klaro": "^0.7.18", "lodash": "^4.17.21", "lru-cache": "^7.14.1", "markdown-it": "^13.0.1", - "markdown-it-mathjax3": "^4.3.1", + "markdown-it-mathjax3": "^4.3.2", "mirador": "^3.3.0", "mirador-dl-plugin": "^0.13.0", "mirador-share-plugin": "^0.11.0", "morgan": "^1.10.0", - "ng-mocks": "^13.1.1", + "ng-mocks": "^14.10.0", "ng2-file-upload": "1.4.0", "ng2-nouislider": "^1.8.3", - "ngx-infinite-scroll": "^10.0.1", - "ngx-pagination": "5.0.0", + "ngx-infinite-scroll": "^15.0.0", + "ngx-pagination": "6.0.3", "ngx-sortablejs": "^11.1.0", - "ngx-ui-switch": "^13.0.2", + "ngx-ui-switch": "^14.0.3", "nouislider": "^14.6.3", - "pem": "1.14.4", - "prop-types": "^15.7.2", - "react-copy-to-clipboard": "^5.0.1", + "pem": "1.14.7", + "prop-types": "^15.8.1", + "react-copy-to-clipboard": "^5.1.0", "reflect-metadata": "^0.1.13", - "rxjs": "^7.5.5", - "sanitize-html": "^2.7.2", - "sortablejs": "1.13.0", + "rxjs": "^7.8.0", + "sanitize-html": "^2.10.0", + "sortablejs": "1.15.0", "uuid": "^8.3.2", "webfontloader": "1.6.28", "zone.js": "~0.11.5" }, "devDependencies": { - "@angular-builders/custom-webpack": "~13.1.0", - "@angular-devkit/build-angular": "~13.3.10", - "@angular-eslint/builder": "13.1.0", - "@angular-eslint/eslint-plugin": "13.1.0", - "@angular-eslint/eslint-plugin-template": "13.1.0", - "@angular-eslint/schematics": "13.1.0", - "@angular-eslint/template-parser": "13.1.0", - "@angular/cli": "~13.3.10", - "@angular/compiler-cli": "~13.3.12", - "@angular/language-service": "~13.3.12", + "@angular-builders/custom-webpack": "~15.0.0", + "@angular-devkit/build-angular": "^15.2.6", + "@angular-eslint/builder": "15.2.1", + "@angular-eslint/eslint-plugin": "15.2.1", + "@angular-eslint/eslint-plugin-template": "15.2.1", + "@angular-eslint/schematics": "15.2.1", + "@angular-eslint/template-parser": "15.2.1", + "@angular/cli": "^15.2.6", + "@angular/compiler-cli": "^15.2.8", + "@angular/language-service": "^15.2.8", "@cypress/schematic": "^1.5.0", - "@fortawesome/fontawesome-free": "^6.2.1", - "@ngrx/store-devtools": "^13.0.2", - "@ngtools/webpack": "^13.2.6", - "@nguniversal/builders": "^13.1.1", + "@fortawesome/fontawesome-free": "^6.4.0", + "@ngrx/store-devtools": "^15.4.0", + "@ngtools/webpack": "^15.2.6", + "@nguniversal/builders": "^15.2.1", "@types/deep-freeze": "0.1.2", - "@types/ejs": "^3.1.1", - "@types/express": "^4.17.9", + "@types/ejs": "^3.1.2", + "@types/express": "^4.17.17", "@types/jasmine": "~3.6.0", "@types/js-cookie": "2.2.6", - "@types/lodash": "^4.14.165", + "@types/lodash": "^4.14.194", "@types/node": "^14.14.9", - "@types/sanitize-html": "^2.6.2", - "@typescript-eslint/eslint-plugin": "5.11.0", - "@typescript-eslint/parser": "5.11.0", - "axe-core": "^4.4.3", + "@types/sanitize-html": "^2.9.0", + "@typescript-eslint/eslint-plugin": "^5.59.1", + "@typescript-eslint/parser": "^5.59.1", + "axe-core": "^4.7.0", "compression-webpack-plugin": "^9.2.0", "copy-webpack-plugin": "^6.4.1", "cross-env": "^7.0.3", - "cypress": "12.9.0", - "cypress-axe": "^1.1.0", + "cypress": "12.10.0", + "cypress-axe": "^1.4.0", "deep-freeze": "0.0.1", - "eslint": "^8.2.0", - "eslint-plugin-deprecation": "^1.3.2", - "eslint-plugin-import": "^2.25.4", + "eslint": "^8.39.0", + "eslint-plugin-deprecation": "^1.4.1", + "eslint-plugin-import": "^2.27.5", "eslint-plugin-jsdoc": "^39.6.4", "eslint-plugin-jsonc": "^2.6.0", "eslint-plugin-lodash": "^7.4.0", "eslint-plugin-unused-imports": "^2.0.0", - "express-static-gzip": "^2.1.5", + "express-static-gzip": "^2.1.7", "jasmine-core": "^3.8.0", "jasmine-marbles": "0.9.2", - "karma": "^6.3.14", - "karma-chrome-launcher": "~3.1.0", - "karma-coverage-istanbul-reporter": "~3.0.2", + "karma": "^6.4.2", + "karma-chrome-launcher": "~3.2.0", + "karma-coverage-istanbul-reporter": "~3.0.3", "karma-jasmine": "~4.0.0", "karma-jasmine-html-reporter": "^1.5.0", "karma-mocha-reporter": "2.2.5", "ngx-mask": "^13.1.7", - "nodemon": "^2.0.20", - "postcss": "^8.1", + "nodemon": "^2.0.22", + "postcss": "^8.4", "postcss-apply": "0.12.0", "postcss-import": "^14.0.0", "postcss-loader": "^4.0.3", @@ -194,14 +194,14 @@ "react-dom": "^16.14.0", "rimraf": "^3.0.2", "rxjs-spy": "^8.0.2", - "sass": "~1.33.0", + "sass": "~1.62.0", "sass-loader": "^12.6.0", - "sass-resources-loader": "^2.1.1", + "sass-resources-loader": "^2.2.5", "ts-node": "^8.10.2", - "typescript": "~4.5.5", - "webpack": "^5.76.0", - "webpack-bundle-analyzer": "^4.4.0", + "typescript": "~4.8.4", + "webpack": "5.76.1", + "webpack-bundle-analyzer": "^4.8.0", "webpack-cli": "^4.2.0", - "webpack-dev-server": "^4.5.0" + "webpack-dev-server": "^4.13.3" } } diff --git a/scripts/webpack.js b/scripts/webpack.js deleted file mode 100644 index 93f17b4619..0000000000 --- a/scripts/webpack.js +++ /dev/null @@ -1,13 +0,0 @@ -const path = require('path'); -const child_process = require('child_process'); - -const heapSize = 4096; -const webpackPath = path.join('node_modules', 'webpack', 'bin', 'webpack.js'); - -const params = [ - '--max_old_space_size=' + heapSize, - webpackPath, - ...process.argv.slice(2) -]; - -child_process.spawn('node', params, { stdio:'inherit' }); diff --git a/server.ts b/server.ts index 3e10677a8b..23327c2058 100644 --- a/server.ts +++ b/server.ts @@ -26,7 +26,6 @@ import * as ejs from 'ejs'; import * as compression from 'compression'; import * as expressStaticGzip from 'express-static-gzip'; /* eslint-enable import/no-namespace */ - import axios from 'axios'; import LRU from 'lru-cache'; import isbot from 'isbot'; @@ -34,7 +33,7 @@ import { createCertificate } from 'pem'; import { createServer } from 'https'; import { json } from 'body-parser'; -import { existsSync, readFileSync } from 'fs'; +import { readFileSync } from 'fs'; import { join } from 'path'; import { enableProdMode } from '@angular/core'; @@ -54,7 +53,7 @@ import { buildAppConfig } from './src/config/config.server'; import { APP_CONFIG, AppConfig } from './src/config/app-config.interface'; import { extendEnvironmentWithAppConfig } from './src/config/config.util'; import { logStartupMessage } from './startup-message'; -import { TOKENITEM } from 'src/app/core/auth/models/auth-token-info.model'; +import { TOKENITEM } from './src/app/core/auth/models/auth-token-info.model'; /* @@ -180,6 +179,15 @@ export function app() { changeOrigin: true })); + /** + * Proxy the linksets + */ + router.use('/signposting**', createProxyMiddleware({ + target: `${environment.rest.baseUrl}`, + pathRewrite: path => path.replace(environment.ui.nameSpace, '/'), + changeOrigin: true + })); + /** * Checks if the rateLimiter property is present * When it is present, the rateLimiter will be enabled. When it is undefined, the rateLimiter will be disabled. @@ -366,9 +374,19 @@ function cacheCheck(req, res, next) { } // If cached copy exists, return it to the user. - if (cachedCopy) { + if (cachedCopy && cachedCopy.page) { + if (cachedCopy.headers) { + Object.keys(cachedCopy.headers).forEach((header) => { + if (cachedCopy.headers[header]) { + if (environment.cache.serverSide.debug) { + console.log(`Restore cached ${header} header`); + } + res.setHeader(header, cachedCopy.headers[header]); + } + }); + } res.locals.ssr = true; // mark response as SSR-generated (enables text compression) - res.send(cachedCopy); + res.send(cachedCopy.page); // Tell Express to skip all other handlers for this path // This ensures we don't try to re-render the page since we've already returned the cached copy @@ -443,22 +461,50 @@ function saveToCache(req, page: any) { const key = getCacheKey(req); // Avoid caching "/reload/[random]" paths (these are hard refreshes after logout) if (key.startsWith('/reload')) { return; } + // Avoid caching not successful responses (status code different from 2XX status) + if (hasNotSucceeded(req.res.statusCode)) { return; } + // Retrieve response headers to save, if any + const headers = retrieveHeaders(req.res); // If bot cache is enabled, save it to that cache if it doesn't exist or is expired // (NOTE: has() will return false if page is expired in cache) if (botCacheEnabled() && !botCache.has(key)) { - botCache.set(key, page); + botCache.set(key, { page, headers }); if (environment.cache.serverSide.debug) { console.log(`CACHE SAVE FOR ${key} in bot cache.`); } } // If anonymous cache is enabled, save it to that cache if it doesn't exist or is expired if (anonymousCacheEnabled() && !anonymousCache.has(key)) { - anonymousCache.set(key, page); + anonymousCache.set(key, { page, headers }); if (environment.cache.serverSide.debug) { console.log(`CACHE SAVE FOR ${key} in anonymous cache.`); } } } } +/** + * Check if status code is different from 2XX + * @param statusCode + */ +function hasNotSucceeded(statusCode) { + const rgx = new RegExp(/^20+/); + return !rgx.test(statusCode) +} + +function retrieveHeaders(response) { + const headers = Object.create({}); + if (Array.isArray(environment.cache.serverSide.headers) && environment.cache.serverSide.headers.length > 0) { + environment.cache.serverSide.headers.forEach((header) => { + if (response.hasHeader(header)) { + if (environment.cache.serverSide.debug) { + console.log(`Save ${header} header to cache`); + } + headers[header] = response.getHeader(header); + } + }); + } + + return headers; +} /** * Whether a user is authenticated or not */ diff --git a/src/app/access-control/access-control-routing.module.ts b/src/app/access-control/access-control-routing.module.ts index e64b0d170a..6f6de6cb26 100644 --- a/src/app/access-control/access-control-routing.module.ts +++ b/src/app/access-control/access-control-routing.module.ts @@ -6,8 +6,13 @@ import { GroupsRegistryComponent } from './group-registry/groups-registry.compon import { GROUP_EDIT_PATH } from './access-control-routing-paths'; import { I18nBreadcrumbResolver } from '../core/breadcrumbs/i18n-breadcrumb.resolver'; import { GroupPageGuard } from './group-registry/group-page.guard'; -import { GroupAdministratorGuard } from '../core/data/feature-authorization/feature-authorization-guard/group-administrator.guard'; -import { SiteAdministratorGuard } from '../core/data/feature-authorization/feature-authorization-guard/site-administrator.guard'; +import { + GroupAdministratorGuard +} from '../core/data/feature-authorization/feature-authorization-guard/group-administrator.guard'; +import { + SiteAdministratorGuard +} from '../core/data/feature-authorization/feature-authorization-guard/site-administrator.guard'; +import { BulkAccessComponent } from './bulk-access/bulk-access.component'; @NgModule({ imports: [ @@ -47,7 +52,16 @@ import { SiteAdministratorGuard } from '../core/data/feature-authorization/featu }, data: { title: 'admin.access-control.groups.title.singleGroup', breadcrumbKey: 'admin.access-control.groups.singleGroup' }, canActivate: [GroupPageGuard] - } + }, + { + path: 'bulk-access', + component: BulkAccessComponent, + resolve: { + breadcrumb: I18nBreadcrumbResolver + }, + data: { title: 'admin.access-control.bulk-access.title', breadcrumbKey: 'admin.access-control.bulk-access' }, + canActivate: [SiteAdministratorGuard] + }, ]) ] }) diff --git a/src/app/access-control/access-control.module.ts b/src/app/access-control/access-control.module.ts index 47a971a882..3dc4b6cedc 100644 --- a/src/app/access-control/access-control.module.ts +++ b/src/app/access-control/access-control.module.ts @@ -12,6 +12,12 @@ import { GroupsRegistryComponent } from './group-registry/groups-registry.compon import { FormModule } from '../shared/form/form.module'; import { DYNAMIC_ERROR_MESSAGES_MATCHER, DynamicErrorMessagesMatcher } from '@ng-dynamic-forms/core'; import { AbstractControl } from '@angular/forms'; +import { BulkAccessComponent } from './bulk-access/bulk-access.component'; +import { NgbAccordionModule } from '@ng-bootstrap/ng-bootstrap'; +import { BulkAccessBrowseComponent } from './bulk-access/browse/bulk-access-browse.component'; +import { BulkAccessSettingsComponent } from './bulk-access/settings/bulk-access-settings.component'; +import { SearchModule } from '../shared/search/search.module'; +import { AccessControlFormModule } from '../shared/access-control-form-container/access-control-form.module'; /** * Condition for displaying error messages on email form field @@ -28,6 +34,9 @@ export const ValidateEmailErrorStateMatcher: DynamicErrorMessagesMatcher = RouterModule, AccessControlRoutingModule, FormModule, + NgbAccordionModule, + SearchModule, + AccessControlFormModule, ], exports: [ MembersListComponent, @@ -39,6 +48,9 @@ export const ValidateEmailErrorStateMatcher: DynamicErrorMessagesMatcher = GroupFormComponent, SubgroupsListComponent, MembersListComponent, + BulkAccessComponent, + BulkAccessBrowseComponent, + BulkAccessSettingsComponent, ], providers: [ { diff --git a/src/app/access-control/bulk-access/browse/bulk-access-browse.component.html b/src/app/access-control/bulk-access/browse/bulk-access-browse.component.html new file mode 100644 index 0000000000..c716aedb8b --- /dev/null +++ b/src/app/access-control/bulk-access/browse/bulk-access-browse.component.html @@ -0,0 +1,67 @@ + + + +
+ +
+
+ + +
+
+
+
+ + +
+
+
+
diff --git a/src/app/shared/object-collection/shared/mydspace-item-status/my-dspace-item-status.component.scss b/src/app/access-control/bulk-access/browse/bulk-access-browse.component.scss similarity index 100% rename from src/app/shared/object-collection/shared/mydspace-item-status/my-dspace-item-status.component.scss rename to src/app/access-control/bulk-access/browse/bulk-access-browse.component.scss diff --git a/src/app/access-control/bulk-access/browse/bulk-access-browse.component.spec.ts b/src/app/access-control/bulk-access/browse/bulk-access-browse.component.spec.ts new file mode 100644 index 0000000000..87b2a8d568 --- /dev/null +++ b/src/app/access-control/bulk-access/browse/bulk-access-browse.component.spec.ts @@ -0,0 +1,82 @@ +import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; +import { NO_ERRORS_SCHEMA } from '@angular/core'; + +import { of } from 'rxjs'; +import { NgbAccordionModule, NgbNavModule } from '@ng-bootstrap/ng-bootstrap'; +import { TranslateModule } from '@ngx-translate/core'; + +import { BulkAccessBrowseComponent } from './bulk-access-browse.component'; +import { SelectableListService } from '../../../shared/object-list/selectable-list/selectable-list.service'; +import { SelectableObject } from '../../../shared/object-list/selectable-list/selectable-list.service.spec'; +import { PageInfo } from '../../../core/shared/page-info.model'; +import { buildPaginatedList } from '../../../core/data/paginated-list.model'; +import { createSuccessfulRemoteDataObject } from '../../../shared/remote-data.utils'; + +describe('BulkAccessBrowseComponent', () => { + let component: BulkAccessBrowseComponent; + let fixture: ComponentFixture; + + const listID1 = 'id1'; + const value1 = 'Selected object'; + const value2 = 'Another selected object'; + + const selected1 = new SelectableObject(value1); + const selected2 = new SelectableObject(value2); + + const testSelection = { id: listID1, selection: [selected1, selected2] } ; + + const selectableListService = jasmine.createSpyObj('SelectableListService', ['getSelectableList', 'deselectAll']); + beforeEach(waitForAsync(() => { + TestBed.configureTestingModule({ + imports: [ + NgbAccordionModule, + NgbNavModule, + TranslateModule.forRoot() + ], + declarations: [BulkAccessBrowseComponent], + providers: [ { provide: SelectableListService, useValue: selectableListService }, ], + schemas: [ + NO_ERRORS_SCHEMA + ] + }).compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(BulkAccessBrowseComponent); + component = fixture.componentInstance; + (component as any).selectableListService.getSelectableList.and.returnValue(of(testSelection)); + fixture.detectChanges(); + }); + + afterEach(() => { + fixture.destroy(); + component = null; + }); + + it('should create the component', () => { + expect(component).toBeTruthy(); + }); + + it('should have an initial active nav id of "search"', () => { + expect(component.activateId).toEqual('search'); + }); + + it('should have an initial pagination options object with default values', () => { + expect(component.paginationOptions$.getValue().id).toEqual('bas'); + expect(component.paginationOptions$.getValue().pageSize).toEqual(5); + expect(component.paginationOptions$.getValue().currentPage).toEqual(1); + }); + + it('should have an initial remote data with a paginated list as value', () => { + const list = buildPaginatedList(new PageInfo({ + 'elementsPerPage': 5, + 'totalElements': 2, + 'totalPages': 1, + 'currentPage': 1 + }), [selected1, selected2]) ; + const rd = createSuccessfulRemoteDataObject(list); + + expect(component.objectsSelected$.value).toEqual(rd); + }); + +}); diff --git a/src/app/access-control/bulk-access/browse/bulk-access-browse.component.ts b/src/app/access-control/bulk-access/browse/bulk-access-browse.component.ts new file mode 100644 index 0000000000..e806e729c8 --- /dev/null +++ b/src/app/access-control/bulk-access/browse/bulk-access-browse.component.ts @@ -0,0 +1,119 @@ +import { Component, Input, OnDestroy, OnInit } from '@angular/core'; + +import { BehaviorSubject, Subscription } from 'rxjs'; +import { distinctUntilChanged, map } from 'rxjs/operators'; + +import { SEARCH_CONFIG_SERVICE } from '../../../my-dspace-page/my-dspace-page.component'; +import { SearchConfigurationService } from '../../../core/shared/search/search-configuration.service'; +import { SelectableListService } from '../../../shared/object-list/selectable-list/selectable-list.service'; +import { SelectableListState } from '../../../shared/object-list/selectable-list/selectable-list.reducer'; +import { RemoteData } from '../../../core/data/remote-data'; +import { buildPaginatedList, PaginatedList } from '../../../core/data/paginated-list.model'; +import { ListableObject } from '../../../shared/object-collection/shared/listable-object.model'; +import { createSuccessfulRemoteDataObject } from '../../../shared/remote-data.utils'; +import { PageInfo } from '../../../core/shared/page-info.model'; +import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model'; +import { hasValue } from '../../../shared/empty.util'; + +@Component({ + selector: 'ds-bulk-access-browse', + templateUrl: 'bulk-access-browse.component.html', + styleUrls: ['./bulk-access-browse.component.scss'], + providers: [ + { + provide: SEARCH_CONFIG_SERVICE, + useClass: SearchConfigurationService + } + ] +}) +export class BulkAccessBrowseComponent implements OnInit, OnDestroy { + + /** + * The selection list id + */ + @Input() listId!: string; + + /** + * The active nav id + */ + activateId = 'search'; + + /** + * The list of the objects already selected + */ + objectsSelected$: BehaviorSubject>> = new BehaviorSubject>>(null); + + /** + * The pagination options object used for the list of selected elements + */ + paginationOptions$: BehaviorSubject = new BehaviorSubject(Object.assign(new PaginationComponentOptions(), { + id: 'bas', + pageSize: 5, + currentPage: 1 + })); + + /** + * Array to track all subscriptions and unsubscribe them onDestroy + */ + private subs: Subscription[] = []; + + constructor(private selectableListService: SelectableListService) {} + + /** + * Subscribe to selectable list updates + */ + ngOnInit(): void { + + this.subs.push( + this.selectableListService.getSelectableList(this.listId).pipe( + distinctUntilChanged(), + map((list: SelectableListState) => this.generatePaginatedListBySelectedElements(list)) + ).subscribe(this.objectsSelected$) + ); + } + + pageNext() { + this.paginationOptions$.next(Object.assign(new PaginationComponentOptions(), this.paginationOptions$.value, { + currentPage: this.paginationOptions$.value.currentPage + 1 + })); + } + + pagePrev() { + this.paginationOptions$.next(Object.assign(new PaginationComponentOptions(), this.paginationOptions$.value, { + currentPage: this.paginationOptions$.value.currentPage - 1 + })); + } + + private calculatePageCount(pageSize, totalCount = 0) { + // we suppose that if we have 0 items we want 1 empty page + return totalCount < pageSize ? 1 : Math.ceil(totalCount / pageSize); + } + + /** + * Generate The RemoteData object containing the list of the selected elements + * @param list + * @private + */ + private generatePaginatedListBySelectedElements(list: SelectableListState): RemoteData> { + const pageInfo = new PageInfo({ + elementsPerPage: this.paginationOptions$.value.pageSize, + totalElements: list?.selection.length, + totalPages: this.calculatePageCount(this.paginationOptions$.value.pageSize, list?.selection.length), + currentPage: this.paginationOptions$.value.currentPage + }); + if (pageInfo.currentPage > pageInfo.totalPages) { + pageInfo.currentPage = pageInfo.totalPages; + this.paginationOptions$.next(Object.assign(new PaginationComponentOptions(), this.paginationOptions$.value, { + currentPage: pageInfo.currentPage + })); + } + return createSuccessfulRemoteDataObject(buildPaginatedList(pageInfo, list?.selection || [])); + } + + ngOnDestroy(): void { + this.subs + .filter((sub) => hasValue(sub)) + .forEach((sub) => sub.unsubscribe()); + this.selectableListService.deselectAll(this.listId); + } +} diff --git a/src/app/access-control/bulk-access/bulk-access.component.html b/src/app/access-control/bulk-access/bulk-access.component.html new file mode 100644 index 0000000000..382caf85f4 --- /dev/null +++ b/src/app/access-control/bulk-access/bulk-access.component.html @@ -0,0 +1,19 @@ +
+ +
+ + +
+ +
+ + +
+
+ + + diff --git a/src/themes/custom/app/shared/object-list/collection-list-element/collection-list-element.component.html b/src/app/access-control/bulk-access/bulk-access.component.scss similarity index 100% rename from src/themes/custom/app/shared/object-list/collection-list-element/collection-list-element.component.html rename to src/app/access-control/bulk-access/bulk-access.component.scss diff --git a/src/app/access-control/bulk-access/bulk-access.component.spec.ts b/src/app/access-control/bulk-access/bulk-access.component.spec.ts new file mode 100644 index 0000000000..e9b253147d --- /dev/null +++ b/src/app/access-control/bulk-access/bulk-access.component.spec.ts @@ -0,0 +1,158 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { NO_ERRORS_SCHEMA } from '@angular/core'; + +import { TranslateModule } from '@ngx-translate/core'; +import { of } from 'rxjs'; + +import { BulkAccessComponent } from './bulk-access.component'; +import { BulkAccessControlService } from '../../shared/access-control-form-container/bulk-access-control.service'; +import { SelectableListService } from '../../shared/object-list/selectable-list/selectable-list.service'; +import { SelectableListState } from '../../shared/object-list/selectable-list/selectable-list.reducer'; +import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils'; +import { Process } from '../../process-page/processes/process.model'; +import { RouterTestingModule } from '@angular/router/testing'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { NotificationsServiceStub } from '../../shared/testing/notifications-service.stub'; + +describe('BulkAccessComponent', () => { + let component: BulkAccessComponent; + let fixture: ComponentFixture; + let bulkAccessControlService: any; + let selectableListService: any; + + const selectableListServiceMock = jasmine.createSpyObj('SelectableListService', ['getSelectableList', 'deselectAll']); + const bulkAccessControlServiceMock = jasmine.createSpyObj('bulkAccessControlService', ['createPayloadFile', 'executeScript']); + + const mockFormState = { + 'bitstream': [], + 'item': [ + { + 'name': 'embargo', + 'startDate': { + 'year': 2026, + 'month': 5, + 'day': 31 + }, + 'endDate': null + } + ], + 'state': { + 'item': { + 'toggleStatus': true, + 'accessMode': 'replace' + }, + 'bitstream': { + 'toggleStatus': false, + 'accessMode': '', + 'changesLimit': '', + 'selectedBitstreams': [] + } + } + }; + + const mockFile = { + 'uuids': [ + '1234', '5678' + ], + 'file': { } + }; + + const mockSettings: any = jasmine.createSpyObj('AccessControlFormContainerComponent', { + getValue: jasmine.createSpy('getValue'), + reset: jasmine.createSpy('reset') + }); + const selection: any[] = [{ indexableObject: { uuid: '1234' } }, { indexableObject: { uuid: '5678' } }]; + const selectableListState: SelectableListState = { id: 'test', selection }; + const expectedIdList = ['1234', '5678']; + + const selectableListStateEmpty: SelectableListState = { id: 'test', selection: [] }; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [ + RouterTestingModule, + TranslateModule.forRoot() + ], + declarations: [ BulkAccessComponent ], + providers: [ + { provide: BulkAccessControlService, useValue: bulkAccessControlServiceMock }, + { provide: NotificationsService, useValue: NotificationsServiceStub }, + { provide: SelectableListService, useValue: selectableListServiceMock } + ], + schemas: [NO_ERRORS_SCHEMA] + }) + .compileComponents(); + }); + + beforeEach(() => { + fixture = TestBed.createComponent(BulkAccessComponent); + component = fixture.componentInstance; + bulkAccessControlService = TestBed.inject(BulkAccessControlService); + selectableListService = TestBed.inject(SelectableListService); + + }); + + afterEach(() => { + fixture.destroy(); + }); + + describe('when there are no elements selected', () => { + + beforeEach(() => { + + (component as any).selectableListService.getSelectableList.and.returnValue(of(selectableListStateEmpty)); + fixture.detectChanges(); + component.settings = mockSettings; + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); + + it('should generate the id list by selected elements', () => { + expect(component.objectsSelected$.value).toEqual([]); + }); + + it('should disable the execute button when there are no objects selected', () => { + expect(component.canExport()).toBe(false); + }); + + }); + + describe('when there are elements selected', () => { + + beforeEach(() => { + + (component as any).selectableListService.getSelectableList.and.returnValue(of(selectableListState)); + fixture.detectChanges(); + component.settings = mockSettings; + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); + + it('should generate the id list by selected elements', () => { + expect(component.objectsSelected$.value).toEqual(expectedIdList); + }); + + it('should enable the execute button when there are objects selected', () => { + component.objectsSelected$.next(['1234']); + expect(component.canExport()).toBe(true); + }); + + it('should call the settings reset method when reset is called', () => { + component.reset(); + expect(component.settings.reset).toHaveBeenCalled(); + }); + + it('should call the bulkAccessControlService executeScript method when submit is called', () => { + (component.settings as any).getValue.and.returnValue(mockFormState); + bulkAccessControlService.createPayloadFile.and.returnValue(mockFile); + bulkAccessControlService.executeScript.and.returnValue(createSuccessfulRemoteDataObject$(new Process())); + component.objectsSelected$.next(['1234']); + component.submit(); + expect(bulkAccessControlService.executeScript).toHaveBeenCalled(); + }); + }); +}); diff --git a/src/app/access-control/bulk-access/bulk-access.component.ts b/src/app/access-control/bulk-access/bulk-access.component.ts new file mode 100644 index 0000000000..04724614cb --- /dev/null +++ b/src/app/access-control/bulk-access/bulk-access.component.ts @@ -0,0 +1,94 @@ +import { Component, OnInit, ViewChild } from '@angular/core'; + +import { BehaviorSubject, Subscription } from 'rxjs'; +import { distinctUntilChanged, map } from 'rxjs/operators'; + +import { BulkAccessSettingsComponent } from './settings/bulk-access-settings.component'; +import { BulkAccessControlService } from '../../shared/access-control-form-container/bulk-access-control.service'; +import { SelectableListState } from '../../shared/object-list/selectable-list/selectable-list.reducer'; +import { SelectableListService } from '../../shared/object-list/selectable-list/selectable-list.service'; + +@Component({ + selector: 'ds-bulk-access', + templateUrl: './bulk-access.component.html', + styleUrls: ['./bulk-access.component.scss'] +}) +export class BulkAccessComponent implements OnInit { + + /** + * The selection list id + */ + listId = 'bulk-access-list'; + + /** + * The list of the objects already selected + */ + objectsSelected$: BehaviorSubject = new BehaviorSubject([]); + + /** + * Array to track all subscriptions and unsubscribe them onDestroy + */ + private subs: Subscription[] = []; + + /** + * The SectionsDirective reference + */ + @ViewChild('dsBulkSettings') settings: BulkAccessSettingsComponent; + + constructor( + private bulkAccessControlService: BulkAccessControlService, + private selectableListService: SelectableListService + ) { + } + + ngOnInit(): void { + this.subs.push( + this.selectableListService.getSelectableList(this.listId).pipe( + distinctUntilChanged(), + map((list: SelectableListState) => this.generateIdListBySelectedElements(list)) + ).subscribe(this.objectsSelected$) + ); + } + + canExport(): boolean { + return this.objectsSelected$.value?.length > 0; + } + + /** + * Reset the form to its initial state + * This will also reset the state of the child components (bitstream and item access) + */ + reset(): void { + this.settings.reset(); + } + + /** + * Submit the form + * This will create a payload file and execute the script + */ + submit(): void { + const settings = this.settings.getValue(); + const bitstreamAccess = settings.bitstream; + const itemAccess = settings.item; + + const { file } = this.bulkAccessControlService.createPayloadFile({ + bitstreamAccess, + itemAccess, + state: settings.state + }); + + this.bulkAccessControlService.executeScript( + this.objectsSelected$.value || [], + file + ).subscribe(); + } + + /** + * Generate The RemoteData object containing the list of the selected elements + * @param list + * @private + */ + private generateIdListBySelectedElements(list: SelectableListState): string[] { + return list?.selection?.map((entry: any) => entry.indexableObject.uuid); + } +} diff --git a/src/app/access-control/bulk-access/settings/bulk-access-settings.component.html b/src/app/access-control/bulk-access/settings/bulk-access-settings.component.html new file mode 100644 index 0000000000..01f36ef03f --- /dev/null +++ b/src/app/access-control/bulk-access/settings/bulk-access-settings.component.html @@ -0,0 +1,21 @@ + + + +
+ +
+
+ + +
+
+
+
+ + + +
+
diff --git a/src/app/access-control/bulk-access/settings/bulk-access-settings.component.scss b/src/app/access-control/bulk-access/settings/bulk-access-settings.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/access-control/bulk-access/settings/bulk-access-settings.component.spec.ts b/src/app/access-control/bulk-access/settings/bulk-access-settings.component.spec.ts new file mode 100644 index 0000000000..14e0fdefb2 --- /dev/null +++ b/src/app/access-control/bulk-access/settings/bulk-access-settings.component.spec.ts @@ -0,0 +1,81 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { NgbAccordionModule } from '@ng-bootstrap/ng-bootstrap'; +import { TranslateModule } from '@ngx-translate/core'; +import { BulkAccessSettingsComponent } from './bulk-access-settings.component'; +import { NO_ERRORS_SCHEMA } from '@angular/core'; + +describe('BulkAccessSettingsComponent', () => { + let component: BulkAccessSettingsComponent; + let fixture: ComponentFixture; + const mockFormState = { + 'bitstream': [], + 'item': [ + { + 'name': 'embargo', + 'startDate': { + 'year': 2026, + 'month': 5, + 'day': 31 + }, + 'endDate': null + } + ], + 'state': { + 'item': { + 'toggleStatus': true, + 'accessMode': 'replace' + }, + 'bitstream': { + 'toggleStatus': false, + 'accessMode': '', + 'changesLimit': '', + 'selectedBitstreams': [] + } + } + }; + + const mockControl: any = jasmine.createSpyObj('AccessControlFormContainerComponent', { + getFormValue: jasmine.createSpy('getFormValue'), + reset: jasmine.createSpy('reset') + }); + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [NgbAccordionModule, TranslateModule.forRoot()], + declarations: [BulkAccessSettingsComponent], + schemas: [NO_ERRORS_SCHEMA] + }).compileComponents(); + }); + + beforeEach(() => { + fixture = TestBed.createComponent(BulkAccessSettingsComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + component.controlForm = mockControl; + }); + + it('should create the component', () => { + expect(component).toBeTruthy(); + }); + + it('should have a method to get the form value', () => { + expect(component.getValue).toBeDefined(); + }); + + it('should have a method to reset the form', () => { + expect(component.reset).toBeDefined(); + }); + + it('should return the correct form value', () => { + const expectedValue = mockFormState; + (component.controlForm as any).getFormValue.and.returnValue(mockFormState); + const actualValue = component.getValue(); + // @ts-ignore + expect(actualValue).toEqual(expectedValue); + }); + + it('should call reset on the control form', () => { + component.reset(); + expect(component.controlForm.reset).toHaveBeenCalled(); + }); +}); diff --git a/src/app/access-control/bulk-access/settings/bulk-access-settings.component.ts b/src/app/access-control/bulk-access/settings/bulk-access-settings.component.ts new file mode 100644 index 0000000000..eecc016245 --- /dev/null +++ b/src/app/access-control/bulk-access/settings/bulk-access-settings.component.ts @@ -0,0 +1,34 @@ +import { Component, ViewChild } from '@angular/core'; +import { + AccessControlFormContainerComponent +} from '../../../shared/access-control-form-container/access-control-form-container.component'; + +@Component({ + selector: 'ds-bulk-access-settings', + templateUrl: 'bulk-access-settings.component.html', + styleUrls: ['./bulk-access-settings.component.scss'], + exportAs: 'dsBulkSettings' +}) +export class BulkAccessSettingsComponent { + + /** + * The SectionsDirective reference + */ + @ViewChild('dsAccessControlForm') controlForm: AccessControlFormContainerComponent; + + /** + * Will be used from a parent component to read the value of the form + */ + getValue() { + return this.controlForm.getFormValue(); + } + + /** + * Reset the form to its initial state + * This will also reset the state of the child components (bitstream and item access) + */ + reset() { + this.controlForm.reset(); + } + +} diff --git a/src/app/access-control/epeople-registry/epeople-registry.component.html b/src/app/access-control/epeople-registry/epeople-registry.component.html index 3a7806a231..e3a8e2c590 100644 --- a/src/app/access-control/epeople-registry/epeople-registry.component.html +++ b/src/app/access-control/epeople-registry/epeople-registry.component.html @@ -68,18 +68,18 @@ {{epersonDto.eperson.id}} - {{epersonDto.eperson.name}} + {{ dsoNameService.getName(epersonDto.eperson) }} {{epersonDto.eperson.email}}
diff --git a/src/app/access-control/epeople-registry/epeople-registry.component.ts b/src/app/access-control/epeople-registry/epeople-registry.component.ts index 55233d8173..fb045ebb88 100644 --- a/src/app/access-control/epeople-registry/epeople-registry.component.ts +++ b/src/app/access-control/epeople-registry/epeople-registry.component.ts @@ -1,5 +1,5 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { FormBuilder } from '@angular/forms'; +import { UntypedFormBuilder } from '@angular/forms'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { BehaviorSubject, combineLatest, Observable, Subscription } from 'rxjs'; @@ -21,6 +21,7 @@ import { RequestService } from '../../core/data/request.service'; import { PageInfo } from '../../core/shared/page-info.model'; import { NoContent } from '../../core/shared/NoContent.model'; import { PaginationService } from '../../core/pagination/pagination.service'; +import { DSONameService } from '../../core/breadcrumbs/dso-name.service'; @Component({ selector: 'ds-epeople-registry', @@ -89,11 +90,13 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy { private translateService: TranslateService, private notificationsService: NotificationsService, private authorizationService: AuthorizationDataService, - private formBuilder: FormBuilder, + private formBuilder: UntypedFormBuilder, private router: Router, private modalService: NgbModal, private paginationService: PaginationService, - public requestService: RequestService) { + public requestService: RequestService, + public dsoNameService: DSONameService, + ) { this.currentSearchQuery = ''; this.currentSearchScope = 'metadata'; this.searchForm = this.formBuilder.group(({ @@ -121,7 +124,7 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy { this.subs.push(this.ePeople$.pipe( switchMap((epeople: PaginatedList) => { if (epeople.pageInfo.totalElements > 0) { - return combineLatest(...epeople.page.map((eperson) => { + return combineLatest([...epeople.page.map((eperson: EPerson) => { return this.authorizationService.isAuthorized(FeatureID.CanDelete, hasValue(eperson) ? eperson.self : undefined).pipe( map((authorized) => { const epersonDtoModel: EpersonDtoModel = new EpersonDtoModel(); @@ -130,7 +133,7 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy { return epersonDtoModel; }) ); - })).pipe(map((dtos: EpersonDtoModel[]) => { + })]).pipe(map((dtos: EpersonDtoModel[]) => { return buildPaginatedList(epeople.pageInfo, dtos); })); } else { @@ -237,7 +240,7 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy { if (hasValue(ePerson.id)) { this.epersonService.deleteEPerson(ePerson).pipe(getFirstCompletedRemoteData()).subscribe((restResponse: RemoteData) => { if (restResponse.hasSucceeded) { - this.notificationsService.success(this.translateService.get(this.labelPrefix + 'notification.deleted.success', {name: ePerson.name})); + this.notificationsService.success(this.translateService.get(this.labelPrefix + 'notification.deleted.success', {name: this.dsoNameService.getName(ePerson)})); } else { this.notificationsService.error('Error occured when trying to delete EPerson with id: ' + ePerson.id + ' with code: ' + restResponse.statusCode + ' and message: ' + restResponse.errorMessage); } @@ -284,14 +287,17 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy { /** * This method will set everything to stale, which will cause the lists on this page to update. */ - reset() { + reset(): void { this.epersonService.getBrowseEndpoint().pipe( - take(1) - ).subscribe((href: string) => { - this.requestService.setStaleByHrefSubstring(href).pipe(take(1)).subscribe(() => { - this.epersonService.cancelEditEPerson(); - this.isEPersonFormShown = false; - }); + take(1), + switchMap((href: string) => { + return this.requestService.setStaleByHrefSubstring(href).pipe( + take(1), + ); + }) + ).subscribe(()=>{ + this.epersonService.cancelEditEPerson(); + this.isEPersonFormShown = false; }); } } diff --git a/src/app/access-control/epeople-registry/eperson-form/eperson-form.component.html b/src/app/access-control/epeople-registry/eperson-form/eperson-form.component.html index 7386177ea0..228449a8a5 100644 --- a/src/app/access-control/epeople-registry/eperson-form/eperson-form.component.html +++ b/src/app/access-control/epeople-registry/eperson-form/eperson-form.component.html @@ -65,9 +65,13 @@ {{group.id}} - {{group.name}} - {{(group.object | async)?.payload?.name}} + + + {{ dsoNameService.getName(group) }} + + + {{ dsoNameService.getName(undefined) }} diff --git a/src/app/access-control/epeople-registry/eperson-form/eperson-form.component.spec.ts b/src/app/access-control/epeople-registry/eperson-form/eperson-form.component.spec.ts index bf03e1defb..fb911e709c 100644 --- a/src/app/access-control/epeople-registry/eperson-form/eperson-form.component.spec.ts +++ b/src/app/access-control/epeople-registry/eperson-form/eperson-form.component.spec.ts @@ -2,7 +2,7 @@ import { Observable, of as observableOf } from 'rxjs'; import { CommonModule } from '@angular/common'; import { NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; -import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'; +import { UntypedFormControl, UntypedFormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms'; import { BrowserModule, By } from '@angular/platform-browser'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; @@ -116,9 +116,9 @@ describe('EPersonFormComponent', () => { const controlModel = model; const controlState = { value: controlModel.value, disabled: controlModel.disabled }; const controlOptions = this.createAbstractControlOptions(controlModel.validators, controlModel.asyncValidators, controlModel.updateOn); - controls[model.id] = new FormControl(controlState, controlOptions); + controls[model.id] = new UntypedFormControl(controlState, controlOptions); }); - return new FormGroup(controls, options); + return new UntypedFormGroup(controls, options); }, createAbstractControlOptions(validatorsConfig = null, asyncValidatorsConfig = null, updateOn = null) { return { diff --git a/src/app/access-control/epeople-registry/eperson-form/eperson-form.component.ts b/src/app/access-control/epeople-registry/eperson-form/eperson-form.component.ts index 5a7ab735ca..d009d56058 100644 --- a/src/app/access-control/epeople-registry/eperson-form/eperson-form.component.ts +++ b/src/app/access-control/epeople-registry/eperson-form/eperson-form.component.ts @@ -1,5 +1,5 @@ import { ChangeDetectorRef, Component, EventEmitter, OnDestroy, OnInit, Output } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { DynamicCheckboxModel, DynamicFormControlModel, @@ -8,7 +8,7 @@ import { } from '@ng-dynamic-forms/core'; import { TranslateService } from '@ngx-translate/core'; import { combineLatest as observableCombineLatest, Observable, of as observableOf, Subscription } from 'rxjs'; -import { debounceTime, switchMap, take } from 'rxjs/operators'; +import { debounceTime, finalize, map, switchMap, take } from 'rxjs/operators'; import { PaginatedList } from '../../../core/data/paginated-list.model'; import { RemoteData } from '../../../core/data/remote-data'; import { EPersonDataService } from '../../../core/eperson/eperson-data.service'; @@ -37,6 +37,7 @@ import { ValidateEmailNotTaken } from './validators/email-taken.validator'; import { Registration } from '../../../core/shared/registration.model'; import { EpersonRegistrationService } from '../../../core/data/eperson-registration.service'; import { TYPE_REQUEST_FORGOT } from '../../../register-email-form/register-email-form.component'; +import { DSONameService } from '../../../core/breadcrumbs/dso-name.service'; @Component({ selector: 'ds-eperson-form', @@ -108,7 +109,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy { /** * A FormGroup that combines all inputs */ - formGroup: FormGroup; + formGroup: UntypedFormGroup; /** * An EventEmitter that's fired whenever the form is being submitted @@ -192,6 +193,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy { private paginationService: PaginationService, public requestService: RequestService, private epersonRegistrationService: EpersonRegistrationService, + public dsoNameService: DSONameService, ) { this.subs.push(this.epersonService.getActiveEPerson().subscribe((eperson: EPerson) => { this.epersonInitial = eperson; @@ -212,14 +214,14 @@ export class EPersonFormComponent implements OnInit, OnDestroy { */ initialisePage() { - observableCombineLatest( + observableCombineLatest([ this.translateService.get(`${this.messagePrefix}.firstName`), this.translateService.get(`${this.messagePrefix}.lastName`), this.translateService.get(`${this.messagePrefix}.email`), this.translateService.get(`${this.messagePrefix}.canLogIn`), this.translateService.get(`${this.messagePrefix}.requireCertificate`), this.translateService.get(`${this.messagePrefix}.emailHint`), - ).subscribe(([firstName, lastName, email, canLogIn, requireCertificate, emailHint]) => { + ]).subscribe(([firstName, lastName, email, canLogIn, requireCertificate, emailHint]) => { this.firstName = new DynamicInputModel({ id: 'firstName', label: firstName, @@ -386,10 +388,10 @@ export class EPersonFormComponent implements OnInit, OnDestroy { getFirstCompletedRemoteData() ).subscribe((rd: RemoteData) => { if (rd.hasSucceeded) { - this.notificationsService.success(this.translateService.get(this.labelPrefix + 'notification.created.success', { name: ePersonToCreate.name })); + this.notificationsService.success(this.translateService.get(this.labelPrefix + 'notification.created.success', { name: this.dsoNameService.getName(ePersonToCreate) })); this.submitForm.emit(ePersonToCreate); } else { - this.notificationsService.error(this.translateService.get(this.labelPrefix + 'notification.created.failure', { name: ePersonToCreate.name })); + this.notificationsService.error(this.translateService.get(this.labelPrefix + 'notification.created.failure', { name: this.dsoNameService.getName(ePersonToCreate) })); this.cancelForm.emit(); } }); @@ -425,10 +427,10 @@ export class EPersonFormComponent implements OnInit, OnDestroy { const response = this.epersonService.updateEPerson(editedEperson); response.pipe(getFirstCompletedRemoteData()).subscribe((rd: RemoteData) => { if (rd.hasSucceeded) { - this.notificationsService.success(this.translateService.get(this.labelPrefix + 'notification.edited.success', { name: editedEperson.name })); + this.notificationsService.success(this.translateService.get(this.labelPrefix + 'notification.edited.success', { name: this.dsoNameService.getName(editedEperson) })); this.submitForm.emit(editedEperson); } else { - this.notificationsService.error(this.translateService.get(this.labelPrefix + 'notification.edited.failure', { name: editedEperson.name })); + this.notificationsService.error(this.translateService.get(this.labelPrefix + 'notification.edited.failure', { name: this.dsoNameService.getName(editedEperson) })); this.cancelForm.emit(); } }); @@ -461,31 +463,42 @@ export class EPersonFormComponent implements OnInit, OnDestroy { * Deletes the EPerson from the Repository. The EPerson will be the only that this form is showing. * It'll either show a success or error message depending on whether the delete was successful or not. */ - delete() { - this.epersonService.getActiveEPerson().pipe(take(1)).subscribe((eperson: EPerson) => { - const modalRef = this.modalService.open(ConfirmationModalComponent); - modalRef.componentInstance.dso = eperson; - modalRef.componentInstance.headerLabel = 'confirmation-modal.delete-eperson.header'; - modalRef.componentInstance.infoLabel = 'confirmation-modal.delete-eperson.info'; - modalRef.componentInstance.cancelLabel = 'confirmation-modal.delete-eperson.cancel'; - modalRef.componentInstance.confirmLabel = 'confirmation-modal.delete-eperson.confirm'; - modalRef.componentInstance.brandColor = 'danger'; - modalRef.componentInstance.confirmIcon = 'fas fa-trash'; - modalRef.componentInstance.response.pipe(take(1)).subscribe((confirm: boolean) => { - if (confirm) { - if (hasValue(eperson.id)) { - this.epersonService.deleteEPerson(eperson).pipe(getFirstCompletedRemoteData()).subscribe((restResponse: RemoteData) => { - if (restResponse.hasSucceeded) { - this.notificationsService.success(this.translateService.get(this.labelPrefix + 'notification.deleted.success', { name: eperson.name })); - this.submitForm.emit(); - } else { - this.notificationsService.error('Error occured when trying to delete EPerson with id: ' + eperson.id + ' with code: ' + restResponse.statusCode + ' and message: ' + restResponse.errorMessage); - } - this.cancelForm.emit(); - }); - } - } - }); + delete(): void { + this.epersonService.getActiveEPerson().pipe( + take(1), + switchMap((eperson: EPerson) => { + const modalRef = this.modalService.open(ConfirmationModalComponent); + modalRef.componentInstance.dso = eperson; + modalRef.componentInstance.headerLabel = 'confirmation-modal.delete-eperson.header'; + modalRef.componentInstance.infoLabel = 'confirmation-modal.delete-eperson.info'; + modalRef.componentInstance.cancelLabel = 'confirmation-modal.delete-eperson.cancel'; + modalRef.componentInstance.confirmLabel = 'confirmation-modal.delete-eperson.confirm'; + modalRef.componentInstance.brandColor = 'danger'; + modalRef.componentInstance.confirmIcon = 'fas fa-trash'; + + return modalRef.componentInstance.response.pipe( + take(1), + switchMap((confirm: boolean) => { + if (confirm && hasValue(eperson.id)) { + this.canDelete$ = observableOf(false); + return this.epersonService.deleteEPerson(eperson).pipe( + getFirstCompletedRemoteData(), + map((restResponse: RemoteData) => ({ restResponse, eperson })) + ); + } else { + return observableOf(null); + } + }), + finalize(() => this.canDelete$ = observableOf(true)) + ); + }) + ).subscribe(({ restResponse, eperson }: { restResponse: RemoteData | null, eperson: EPerson }) => { + if (restResponse?.hasSucceeded) { + this.notificationsService.success(this.translateService.get(this.labelPrefix + 'notification.deleted.success', { name: this.dsoNameService.getName(eperson) })); + } else { + this.notificationsService.error(`Error occurred when trying to delete EPerson with id: ${eperson?.id} with code: ${restResponse?.statusCode} and message: ${restResponse?.errorMessage}`); + } + this.cancelForm.emit(); }); } @@ -521,7 +534,6 @@ export class EPersonFormComponent implements OnInit, OnDestroy { * Cancel the current edit when component is destroyed & unsub all subscriptions */ ngOnDestroy(): void { - this.onCancel(); this.subs.filter((sub) => hasValue(sub)).forEach((sub) => sub.unsubscribe()); this.paginationService.clearPagination(this.config.id); if (hasValue(this.emailValueChangeSubscribe)) { @@ -554,7 +566,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy { .subscribe((list: PaginatedList) => { if (list.totalElements > 0) { this.notificationsService.error(this.translateService.get(this.labelPrefix + 'notification.' + notificationSection + '.failure.emailInUse', { - name: ePerson.name, + name: this.dsoNameService.getName(ePerson), email: ePerson.email })); } diff --git a/src/app/access-control/group-registry/group-form/group-form.component.html b/src/app/access-control/group-registry/group-form/group-form.component.html index d86adc674b..77a81a8daa 100644 --- a/src/app/access-control/group-registry/group-form/group-form.component.html +++ b/src/app/access-control/group-registry/group-form/group-form.component.html @@ -26,7 +26,7 @@ + [content]="(messagePrefix + '.alert.workflowGroup' | translate:{ name: dsoNameService.getName((getLinkedDSO(groupBeingEdited) | async)?.payload), comcol: (getLinkedDSO(groupBeingEdited) | async)?.payload?.type, comcolEditRolesRoute: (getLinkedEditRolesRoute(groupBeingEdited) | async) })"> { let component: GroupFormComponent; @@ -130,9 +132,9 @@ describe('GroupFormComponent', () => { const controlModel = model; const controlState = { value: controlModel.value, disabled: controlModel.disabled }; const controlOptions = this.createAbstractControlOptions(controlModel.validators, controlModel.asyncValidators, controlModel.updateOn); - controls[model.id] = new FormControl(controlState, controlOptions); + controls[model.id] = new UntypedFormControl(controlState, controlOptions); }); - return new FormGroup(controls, options); + return new UntypedFormGroup(controls, options); }, createAbstractControlOptions(validatorsConfig = null, asyncValidatorsConfig = null, updateOn = null) { return { @@ -188,7 +190,7 @@ describe('GroupFormComponent', () => { translateService = getMockTranslateService(); router = new RouterMock(); notificationService = new NotificationsServiceStub(); - TestBed.configureTestingModule({ + return TestBed.configureTestingModule({ imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule, TranslateModule.forRoot({ loader: { @@ -198,7 +200,8 @@ describe('GroupFormComponent', () => { }), ], declarations: [GroupFormComponent], - providers: [GroupFormComponent, + providers: [ + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: EPersonDataService, useValue: ePersonDataServiceStub }, { provide: GroupDataService, useValue: groupsDataServiceStub }, { provide: DSpaceObjectDataService, useValue: dsoDataServiceStub }, @@ -240,8 +243,8 @@ describe('GroupFormComponent', () => { fixture.detectChanges(); }); - it('should emit a new group using the correct values', waitForAsync(() => { - fixture.whenStable().then(() => { + it('should emit a new group using the correct values', (async () => { + await fixture.whenStable().then(() => { expect(component.submitForm.emit).toHaveBeenCalledWith(expected); }); })); @@ -303,8 +306,8 @@ describe('GroupFormComponent', () => { expect(groupsDataServiceStub.patch).toHaveBeenCalledWith(expected, operations); }); - it('should emit the existing group using the correct new values', waitForAsync(() => { - fixture.whenStable().then(() => { + it('should emit the existing group using the correct new values', (async () => { + await fixture.whenStable().then(() => { expect(component.submitForm.emit).toHaveBeenCalledWith(expected2); }); })); diff --git a/src/app/access-control/group-registry/group-form/group-form.component.ts b/src/app/access-control/group-registry/group-form/group-form.component.ts index 4302d126ea..3c0547cca5 100644 --- a/src/app/access-control/group-registry/group-form/group-form.component.ts +++ b/src/app/access-control/group-registry/group-form/group-form.component.ts @@ -1,5 +1,5 @@ import { Component, EventEmitter, HostListener, OnDestroy, OnInit, Output, ChangeDetectorRef } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { @@ -46,6 +46,7 @@ import { followLink } from '../../../shared/utils/follow-link-config.model'; import { NoContent } from '../../../core/shared/NoContent.model'; import { Operation } from 'fast-json-patch'; import { ValidateGroupExists } from './validators/group-exists.validator'; +import { DSONameService } from '../../../core/breadcrumbs/dso-name.service'; import { environment } from '../../../../environments/environment'; @Component({ @@ -95,7 +96,7 @@ export class GroupFormComponent implements OnInit, OnDestroy { /** * A FormGroup that combines all inputs */ - formGroup: FormGroup; + formGroup: UntypedFormGroup; /** * An EventEmitter that's fired whenever the form is being submitted @@ -134,7 +135,8 @@ export class GroupFormComponent implements OnInit, OnDestroy { groupNameValueChangeSubscribe: Subscription; - constructor(public groupDataService: GroupDataService, + constructor( + public groupDataService: GroupDataService, private ePersonDataService: EPersonDataService, private dSpaceObjectDataService: DSpaceObjectDataService, private formBuilderService: FormBuilderService, @@ -145,7 +147,9 @@ export class GroupFormComponent implements OnInit, OnDestroy { private authorizationService: AuthorizationDataService, private modalService: NgbModal, public requestService: RequestService, - protected changeDetectorRef: ChangeDetectorRef) { + protected changeDetectorRef: ChangeDetectorRef, + public dsoNameService: DSONameService, + ) { } ngOnInit() { @@ -331,7 +335,7 @@ export class GroupFormComponent implements OnInit, OnDestroy { .subscribe((list: PaginatedList) => { if (list.totalElements > 0) { this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.' + notificationSection + '.failure.groupNameInUse', { - name: group.name + name: this.dsoNameService.getName(group), })); } })); @@ -364,10 +368,10 @@ export class GroupFormComponent implements OnInit, OnDestroy { getFirstCompletedRemoteData() ).subscribe((rd: RemoteData) => { if (rd.hasSucceeded) { - this.notificationsService.success(this.translateService.get(this.messagePrefix + '.notification.edited.success', { name: rd.payload.name })); + this.notificationsService.success(this.translateService.get(this.messagePrefix + '.notification.edited.success', { name: this.dsoNameService.getName(rd.payload) })); this.submitForm.emit(rd.payload); } else { - this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.edited.failure', { name: group.name })); + this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.edited.failure', { name: this.dsoNameService.getName(group) })); this.cancelForm.emit(); } }); @@ -427,11 +431,11 @@ export class GroupFormComponent implements OnInit, OnDestroy { this.groupDataService.delete(group.id).pipe(getFirstCompletedRemoteData()) .subscribe((rd: RemoteData) => { if (rd.hasSucceeded) { - this.notificationsService.success(this.translateService.get(this.messagePrefix + '.notification.deleted.success', { name: group.name })); + this.notificationsService.success(this.translateService.get(this.messagePrefix + '.notification.deleted.success', { name: this.dsoNameService.getName(group) })); this.onCancel(); } else { this.notificationsService.error( - this.translateService.get(this.messagePrefix + '.notification.deleted.failure.title', { name: group.name }), + this.translateService.get(this.messagePrefix + '.notification.deleted.failure.title', { name: this.dsoNameService.getName(group) }), this.translateService.get(this.messagePrefix + '.notification.deleted.failure.content', { cause: rd.errorMessage })); } }); diff --git a/src/app/access-control/group-registry/group-form/members-list/members-list.component.html b/src/app/access-control/group-registry/group-form/members-list/members-list.component.html index 282ee89674..cc9bf34d64 100644 --- a/src/app/access-control/group-registry/group-form/members-list/members-list.component.html +++ b/src/app/access-control/group-registry/group-form/members-list/members-list.component.html @@ -57,8 +57,12 @@ {{ePerson.eperson.id}} - {{ePerson.eperson.name}} + + + {{ dsoNameService.getName(ePerson.eperson) }} + + {{messagePrefix + '.table.email' | translate}}: {{ ePerson.eperson.email ? ePerson.eperson.email : '-' }}
{{messagePrefix + '.table.netid' | translate}}: {{ ePerson.eperson.netid ? ePerson.eperson.netid : '-' }} @@ -69,7 +73,7 @@ (click)="deleteMemberFromGroup(ePerson)" [disabled]="actionConfig.remove.disabled" [ngClass]="['btn btn-sm', actionConfig.remove.css]" - title="{{messagePrefix + '.table.edit.buttons.remove' | translate: {name: ePerson.eperson.name} }}"> + title="{{messagePrefix + '.table.edit.buttons.remove' | translate: { name: dsoNameService.getName(ePerson.eperson) } }}"> @@ -77,7 +81,7 @@ (click)="addMemberToGroup(ePerson)" [disabled]="actionConfig.add.disabled" [ngClass]="['btn btn-sm', actionConfig.add.css]" - title="{{messagePrefix + '.table.edit.buttons.add' | translate: {name: ePerson.eperson.name} }}"> + title="{{messagePrefix + '.table.edit.buttons.add' | translate: { name: dsoNameService.getName(ePerson.eperson) } }}"> @@ -117,8 +121,12 @@ {{ePerson.eperson.id}} - {{ePerson.eperson.name}} + + + {{ dsoNameService.getName(ePerson.eperson) }} + + {{messagePrefix + '.table.email' | translate}}: {{ ePerson.eperson.email ? ePerson.eperson.email : '-' }}
{{messagePrefix + '.table.netid' | translate}}: {{ ePerson.eperson.netid ? ePerson.eperson.netid : '-' }} @@ -129,14 +137,14 @@ (click)="deleteMemberFromGroup(ePerson)" [disabled]="actionConfig.remove.disabled" [ngClass]="['btn btn-sm', actionConfig.remove.css]" - title="{{messagePrefix + '.table.edit.buttons.remove' | translate: {name: ePerson.eperson.name} }}"> + title="{{messagePrefix + '.table.edit.buttons.remove' | translate: { name: dsoNameService.getName(ePerson.eperson) } }}"> diff --git a/src/app/access-control/group-registry/group-form/members-list/members-list.component.spec.ts b/src/app/access-control/group-registry/group-form/members-list/members-list.component.spec.ts index 4b65535fce..7c8db399bc 100644 --- a/src/app/access-control/group-registry/group-form/members-list/members-list.component.spec.ts +++ b/src/app/access-control/group-registry/group-form/members-list/members-list.component.spec.ts @@ -28,6 +28,8 @@ import { NotificationsServiceStub } from '../../../../shared/testing/notificatio import { RouterMock } from '../../../../shared/mocks/router.mock'; import { PaginationService } from '../../../../core/pagination/pagination.service'; import { PaginationServiceStub } from '../../../../shared/testing/pagination-service.stub'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../../../shared/mocks/dso-name.service.mock'; describe('MembersListComponent', () => { let component: MembersListComponent; @@ -118,7 +120,7 @@ describe('MembersListComponent', () => { translateService = getMockTranslateService(); paginationService = new PaginationServiceStub(); - TestBed.configureTestingModule({ + return TestBed.configureTestingModule({ imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule, TranslateModule.forRoot({ loader: { @@ -135,6 +137,7 @@ describe('MembersListComponent', () => { { provide: FormBuilderService, useValue: builderService }, { provide: Router, useValue: new RouterMock() }, { provide: PaginationService, useValue: paginationService }, + { provide: DSONameService, useValue: new DSONameServiceMock() }, ], schemas: [NO_ERRORS_SCHEMA] }).compileComponents(); diff --git a/src/app/access-control/group-registry/group-form/members-list/members-list.component.ts b/src/app/access-control/group-registry/group-form/members-list/members-list.component.ts index d0fc046093..b3e686c012 100644 --- a/src/app/access-control/group-registry/group-form/members-list/members-list.component.ts +++ b/src/app/access-control/group-registry/group-form/members-list/members-list.component.ts @@ -1,5 +1,5 @@ import { Component, Input, OnDestroy, OnInit } from '@angular/core'; -import { FormBuilder } from '@angular/forms'; +import { UntypedFormBuilder } from '@angular/forms'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { @@ -27,6 +27,7 @@ import { NotificationsService } from '../../../../shared/notifications/notificat import { PaginationComponentOptions } from '../../../../shared/pagination/pagination-component-options.model'; import { EpersonDtoModel } from '../../../../core/eperson/models/eperson-dto.model'; import { PaginationService } from '../../../../core/pagination/pagination.service'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; /** * Keys to keep track of specific subscriptions @@ -141,9 +142,10 @@ export class MembersListComponent implements OnInit, OnDestroy { public ePersonDataService: EPersonDataService, protected translateService: TranslateService, protected notificationsService: NotificationsService, - protected formBuilder: FormBuilder, + protected formBuilder: UntypedFormBuilder, protected paginationService: PaginationService, - private router: Router + protected router: Router, + public dsoNameService: DSONameService, ) { this.currentSearchQuery = ''; this.currentSearchScope = 'metadata'; @@ -253,7 +255,7 @@ export class MembersListComponent implements OnInit, OnDestroy { this.groupDataService.getActiveGroup().pipe(take(1)).subscribe((activeGroup: Group) => { if (activeGroup != null) { const response = this.groupDataService.deleteMemberFromGroup(activeGroup, ePerson.eperson); - this.showNotifications('deleteMember', response, ePerson.eperson.name, activeGroup); + this.showNotifications('deleteMember', response, this.dsoNameService.getName(ePerson.eperson), activeGroup); } else { this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure.noActiveGroup')); } @@ -269,7 +271,7 @@ export class MembersListComponent implements OnInit, OnDestroy { this.groupDataService.getActiveGroup().pipe(take(1)).subscribe((activeGroup: Group) => { if (activeGroup != null) { const response = this.groupDataService.addMemberToGroup(activeGroup, ePerson.eperson); - this.showNotifications('addMember', response, ePerson.eperson.name, activeGroup); + this.showNotifications('addMember', response, this.dsoNameService.getName(ePerson.eperson), activeGroup); } else { this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure.noActiveGroup')); } diff --git a/src/app/access-control/group-registry/group-form/subgroup-list/subgroups-list.component.html b/src/app/access-control/group-registry/group-form/subgroup-list/subgroups-list.component.html index d1574b0dba..d009f0283e 100644 --- a/src/app/access-control/group-registry/group-form/subgroup-list/subgroups-list.component.html +++ b/src/app/access-control/group-registry/group-form/subgroup-list/subgroups-list.component.html @@ -53,15 +53,19 @@ {{group.id}} - {{group.name}} - {{(group.object | async)?.payload?.name}} + + + {{ dsoNameService.getName(group) }} + + + {{ dsoNameService.getName((group.object | async)?.payload) }}
@@ -70,7 +74,7 @@
@@ -108,14 +112,18 @@ {{group.id}} - {{group.name}} - {{(group.object | async)?.payload?.name}} + + + {{ dsoNameService.getName(group) }} + + + {{ dsoNameService.getName((group.object | async)?.payload)}}
diff --git a/src/app/access-control/group-registry/group-form/subgroup-list/subgroups-list.component.spec.ts b/src/app/access-control/group-registry/group-form/subgroup-list/subgroups-list.component.spec.ts index ff0fd121af..ac5750dcac 100644 --- a/src/app/access-control/group-registry/group-form/subgroup-list/subgroups-list.component.spec.ts +++ b/src/app/access-control/group-registry/group-form/subgroup-list/subgroups-list.component.spec.ts @@ -29,6 +29,8 @@ import { NotificationsServiceStub } from '../../../../shared/testing/notificatio import { map } from 'rxjs/operators'; import { PaginationService } from '../../../../core/pagination/pagination.service'; import { PaginationServiceStub } from '../../../../shared/testing/pagination-service.stub'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../../../shared/mocks/dso-name.service.mock'; describe('SubgroupsListComponent', () => { let component: SubgroupsListComponent; @@ -108,6 +110,7 @@ describe('SubgroupsListComponent', () => { ], declarations: [SubgroupsListComponent], providers: [SubgroupsListComponent, + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: GroupDataService, useValue: groupsDataServiceStub }, { provide: NotificationsService, useValue: new NotificationsServiceStub() }, { provide: FormBuilderService, useValue: builderService }, diff --git a/src/app/access-control/group-registry/group-form/subgroup-list/subgroups-list.component.ts b/src/app/access-control/group-registry/group-form/subgroup-list/subgroups-list.component.ts index 5f1700e07d..0cff730c62 100644 --- a/src/app/access-control/group-registry/group-form/subgroup-list/subgroups-list.component.ts +++ b/src/app/access-control/group-registry/group-form/subgroup-list/subgroups-list.component.ts @@ -1,5 +1,5 @@ import { Component, Input, OnDestroy, OnInit } from '@angular/core'; -import { FormBuilder } from '@angular/forms'; +import { UntypedFormBuilder } from '@angular/forms'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { BehaviorSubject, Observable, of as observableOf, Subscription } from 'rxjs'; @@ -18,6 +18,7 @@ import { PaginationComponentOptions } from '../../../../shared/pagination/pagina import { NoContent } from '../../../../core/shared/NoContent.model'; import { PaginationService } from '../../../../core/pagination/pagination.service'; import { followLink } from '../../../../shared/utils/follow-link-config.model'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; /** * Keys to keep track of specific subscriptions @@ -86,9 +87,11 @@ export class SubgroupsListComponent implements OnInit, OnDestroy { constructor(public groupDataService: GroupDataService, private translateService: TranslateService, private notificationsService: NotificationsService, - private formBuilder: FormBuilder, + private formBuilder: UntypedFormBuilder, private paginationService: PaginationService, - private router: Router) { + private router: Router, + public dsoNameService: DSONameService, + ) { this.currentSearchQuery = ''; } @@ -177,7 +180,7 @@ export class SubgroupsListComponent implements OnInit, OnDestroy { this.groupDataService.getActiveGroup().pipe(take(1)).subscribe((activeGroup: Group) => { if (activeGroup != null) { const response = this.groupDataService.deleteSubGroupFromGroup(activeGroup, subgroup); - this.showNotifications('deleteSubgroup', response, subgroup.name, activeGroup); + this.showNotifications('deleteSubgroup', response, this.dsoNameService.getName(subgroup), activeGroup); } else { this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure.noActiveGroup')); } @@ -193,7 +196,7 @@ export class SubgroupsListComponent implements OnInit, OnDestroy { if (activeGroup != null) { if (activeGroup.uuid !== subgroup.uuid) { const response = this.groupDataService.addSubGroupToGroup(activeGroup, subgroup); - this.showNotifications('addSubgroup', response, subgroup.name, activeGroup); + this.showNotifications('addSubgroup', response, this.dsoNameService.getName(subgroup), activeGroup); } else { this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure.subgroupToAddIsActiveGroup')); } diff --git a/src/app/access-control/group-registry/groups-registry.component.html b/src/app/access-control/group-registry/groups-registry.component.html index bf14034d4f..828aadc95a 100644 --- a/src/app/access-control/group-registry/groups-registry.component.html +++ b/src/app/access-control/group-registry/groups-registry.component.html @@ -56,8 +56,8 @@ {{groupDto.group.id}} - {{groupDto.group.name}} - {{(groupDto.group.object | async)?.payload?.name}} + {{ dsoNameService.getName(groupDto.group) }} + {{ dsoNameService.getName((groupDto.group.object | async)?.payload) }} {{groupDto.epersons?.totalElements + groupDto.subgroups?.totalElements}}
@@ -65,7 +65,7 @@ @@ -80,7 +80,7 @@
diff --git a/src/app/access-control/group-registry/groups-registry.component.spec.ts b/src/app/access-control/group-registry/groups-registry.component.spec.ts index 239939e70d..635ba727c2 100644 --- a/src/app/access-control/group-registry/groups-registry.component.spec.ts +++ b/src/app/access-control/group-registry/groups-registry.component.spec.ts @@ -32,8 +32,10 @@ import { PaginationService } from '../../core/pagination/pagination.service'; import { PaginationServiceStub } from '../../shared/testing/pagination-service.stub'; import { FeatureID } from '../../core/data/feature-authorization/feature-id'; import { NoContent } from '../../core/shared/NoContent.model'; +import { DSONameService } from '../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock, UNDEFINED_NAME } from '../../shared/mocks/dso-name.service.mock'; -describe('GroupRegistryComponent', () => { +describe('GroupsRegistryComponent', () => { let component: GroupsRegistryComponent; let fixture: ComponentFixture; let ePersonDataServiceStub: any; @@ -160,7 +162,7 @@ describe('GroupRegistryComponent', () => { authorizationService = jasmine.createSpyObj('authorizationService', ['isAuthorized']); setIsAuthorized(true, true); paginationService = new PaginationServiceStub(); - TestBed.configureTestingModule({ + return TestBed.configureTestingModule({ imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule, TranslateModule.forRoot({ loader: { @@ -171,6 +173,7 @@ describe('GroupRegistryComponent', () => { ], declarations: [GroupsRegistryComponent], providers: [GroupsRegistryComponent, + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: EPersonDataService, useValue: ePersonDataServiceStub }, { provide: GroupDataService, useValue: groupsDataServiceStub }, { provide: DSpaceObjectDataService, useValue: dsoDataServiceStub }, @@ -208,7 +211,7 @@ describe('GroupRegistryComponent', () => { it('should display community/collection name if present', () => { const collectionNamesFound = fixture.debugElement.queryAll(By.css('#groups tr td:nth-child(3)')); expect(collectionNamesFound.length).toEqual(2); - expect(collectionNamesFound[0].nativeElement.textContent).toEqual(''); + expect(collectionNamesFound[0].nativeElement.textContent).toEqual(UNDEFINED_NAME); expect(collectionNamesFound[1].nativeElement.textContent).toEqual('testgroupid2objectName'); }); diff --git a/src/app/access-control/group-registry/groups-registry.component.ts b/src/app/access-control/group-registry/groups-registry.component.ts index 70c9b22852..ccfd155e39 100644 --- a/src/app/access-control/group-registry/groups-registry.component.ts +++ b/src/app/access-control/group-registry/groups-registry.component.ts @@ -1,5 +1,5 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { FormBuilder } from '@angular/forms'; +import { UntypedFormBuilder } from '@angular/forms'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { @@ -37,6 +37,7 @@ import { PaginationComponentOptions } from '../../shared/pagination/pagination-c import { NoContent } from '../../core/shared/NoContent.model'; import { PaginationService } from '../../core/pagination/pagination.service'; import { followLink } from '../../shared/utils/follow-link-config.model'; +import { DSONameService } from '../../core/breadcrumbs/dso-name.service'; @Component({ selector: 'ds-groups-registry', @@ -99,12 +100,14 @@ export class GroupsRegistryComponent implements OnInit, OnDestroy { private dSpaceObjectDataService: DSpaceObjectDataService, private translateService: TranslateService, private notificationsService: NotificationsService, - private formBuilder: FormBuilder, + private formBuilder: UntypedFormBuilder, protected routeService: RouteService, private router: Router, private authorizationService: AuthorizationDataService, private paginationService: PaginationService, - public requestService: RequestService) { + public requestService: RequestService, + public dsoNameService: DSONameService, + ) { this.currentSearchQuery = ''; this.searchForm = this.formBuilder.group(({ query: this.currentSearchQuery, @@ -201,10 +204,10 @@ export class GroupsRegistryComponent implements OnInit, OnDestroy { .subscribe((rd: RemoteData) => { if (rd.hasSucceeded) { this.deletedGroupsIds = [...this.deletedGroupsIds, group.group.id]; - this.notificationsService.success(this.translateService.get(this.messagePrefix + 'notification.deleted.success', { name: group.group.name })); + this.notificationsService.success(this.translateService.get(this.messagePrefix + 'notification.deleted.success', { name: this.dsoNameService.getName(group.group) })); } else { this.notificationsService.error( - this.translateService.get(this.messagePrefix + 'notification.deleted.failure.title', { name: group.group.name }), + this.translateService.get(this.messagePrefix + 'notification.deleted.failure.title', { name: this.dsoNameService.getName(group.group) }), this.translateService.get(this.messagePrefix + 'notification.deleted.failure.content', { cause: rd.errorMessage })); } }); diff --git a/src/app/admin/admin-import-batch-page/batch-import-page.component.html b/src/app/admin/admin-import-batch-page/batch-import-page.component.html index dbc8c74437..1092443436 100644 --- a/src/app/admin/admin-import-batch-page/batch-import-page.component.html +++ b/src/app/admin/admin-import-batch-page/batch-import-page.component.html @@ -20,12 +20,29 @@ + + + {{'admin.batch-import.page.toggle.help' | translate}} + + + +
+ +
+
diff --git a/src/app/admin/admin-import-batch-page/batch-import-page.component.spec.ts b/src/app/admin/admin-import-batch-page/batch-import-page.component.spec.ts index 36ba1137c9..341aefb704 100644 --- a/src/app/admin/admin-import-batch-page/batch-import-page.component.spec.ts +++ b/src/app/admin/admin-import-batch-page/batch-import-page.component.spec.ts @@ -86,10 +86,18 @@ describe('BatchImportPageComponent', () => { let fileMock: File; beforeEach(() => { + component.isUpload = true; fileMock = new File([''], 'filename.zip', { type: 'application/zip' }); component.setFile(fileMock); }); + it('should show the file dropzone', () => { + const fileDropzone = fixture.debugElement.query(By.css('[data-test="file-dropzone"]')); + const fileUrlInput = fixture.debugElement.query(By.css('[data-test="file-url-input"]')); + expect(fileDropzone).toBeTruthy(); + expect(fileUrlInput).toBeFalsy(); + }); + describe('if proceed button is pressed without validate only', () => { beforeEach(fakeAsync(() => { component.validateOnly = false; @@ -99,9 +107,9 @@ describe('BatchImportPageComponent', () => { })); it('metadata-import script is invoked with --zip fileName and the mockFile', () => { const parameterValues: ProcessParameter[] = [ - Object.assign(new ProcessParameter(), { name: '--zip', value: 'filename.zip' }), + Object.assign(new ProcessParameter(), { name: '--add' }), + Object.assign(new ProcessParameter(), { name: '--zip', value: 'filename.zip' }) ]; - parameterValues.push(Object.assign(new ProcessParameter(), { name: '--add' })); expect(scriptService.invoke).toHaveBeenCalledWith(BATCH_IMPORT_SCRIPT_NAME, parameterValues, [fileMock]); }); it('success notification is shown', () => { @@ -121,8 +129,8 @@ describe('BatchImportPageComponent', () => { })); it('metadata-import script is invoked with --zip fileName and the mockFile and -v validate-only', () => { const parameterValues: ProcessParameter[] = [ - Object.assign(new ProcessParameter(), { name: '--zip', value: 'filename.zip' }), Object.assign(new ProcessParameter(), { name: '--add' }), + Object.assign(new ProcessParameter(), { name: '--zip', value: 'filename.zip' }), Object.assign(new ProcessParameter(), { name: '-v', value: true }), ]; expect(scriptService.invoke).toHaveBeenCalledWith(BATCH_IMPORT_SCRIPT_NAME, parameterValues, [fileMock]); @@ -148,4 +156,77 @@ describe('BatchImportPageComponent', () => { }); }); }); + + describe('if url is set', () => { + beforeEach(fakeAsync(() => { + component.isUpload = false; + component.fileURL = 'example.fileURL.com'; + fixture.detectChanges(); + })); + + it('should show the file url input', () => { + const fileDropzone = fixture.debugElement.query(By.css('[data-test="file-dropzone"]')); + const fileUrlInput = fixture.debugElement.query(By.css('[data-test="file-url-input"]')); + expect(fileDropzone).toBeFalsy(); + expect(fileUrlInput).toBeTruthy(); + }); + + describe('if proceed button is pressed without validate only', () => { + beforeEach(fakeAsync(() => { + component.validateOnly = false; + const proceed = fixture.debugElement.query(By.css('#proceedButton')).nativeElement; + proceed.click(); + fixture.detectChanges(); + })); + it('metadata-import script is invoked with --url and the file url', () => { + const parameterValues: ProcessParameter[] = [ + Object.assign(new ProcessParameter(), { name: '--add' }), + Object.assign(new ProcessParameter(), { name: '--url', value: 'example.fileURL.com' }) + ]; + expect(scriptService.invoke).toHaveBeenCalledWith(BATCH_IMPORT_SCRIPT_NAME, parameterValues, [null]); + }); + it('success notification is shown', () => { + expect(notificationService.success).toHaveBeenCalled(); + }); + it('redirected to process page', () => { + expect(router.navigateByUrl).toHaveBeenCalledWith('/processes/46'); + }); + }); + + describe('if proceed button is pressed with validate only', () => { + beforeEach(fakeAsync(() => { + component.validateOnly = true; + const proceed = fixture.debugElement.query(By.css('#proceedButton')).nativeElement; + proceed.click(); + fixture.detectChanges(); + })); + it('metadata-import script is invoked with --url and the file url and -v validate-only', () => { + const parameterValues: ProcessParameter[] = [ + Object.assign(new ProcessParameter(), { name: '--add' }), + Object.assign(new ProcessParameter(), { name: '--url', value: 'example.fileURL.com' }), + Object.assign(new ProcessParameter(), { name: '-v', value: true }), + ]; + expect(scriptService.invoke).toHaveBeenCalledWith(BATCH_IMPORT_SCRIPT_NAME, parameterValues, [null]); + }); + it('success notification is shown', () => { + expect(notificationService.success).toHaveBeenCalled(); + }); + it('redirected to process page', () => { + expect(router.navigateByUrl).toHaveBeenCalledWith('/processes/46'); + }); + }); + + describe('if proceed is pressed; but script invoke fails', () => { + beforeEach(fakeAsync(() => { + jasmine.getEnv().allowRespy(true); + spyOn(scriptService, 'invoke').and.returnValue(createFailedRemoteDataObject$('Error', 500)); + const proceed = fixture.debugElement.query(By.css('#proceedButton')).nativeElement; + proceed.click(); + fixture.detectChanges(); + })); + it('error notification is shown', () => { + expect(notificationService.error).toHaveBeenCalled(); + }); + }); + }); }); diff --git a/src/app/admin/admin-import-batch-page/batch-import-page.component.ts b/src/app/admin/admin-import-batch-page/batch-import-page.component.ts index 95e69277a8..673e1f23f5 100644 --- a/src/app/admin/admin-import-batch-page/batch-import-page.component.ts +++ b/src/app/admin/admin-import-batch-page/batch-import-page.component.ts @@ -8,7 +8,7 @@ import { ProcessParameter } from '../../process-page/processes/process-parameter import { getFirstCompletedRemoteData } from '../../core/shared/operators'; import { RemoteData } from '../../core/data/remote-data'; import { Process } from '../../process-page/processes/process.model'; -import { isNotEmpty } from '../../shared/empty.util'; +import { isEmpty, isNotEmpty } from '../../shared/empty.util'; import { getProcessDetailRoute } from '../../process-page/process-page-routing.paths'; import { ImportBatchSelectorComponent @@ -32,11 +32,22 @@ export class BatchImportPageComponent { * The validate only flag */ validateOnly = true; + /** * dso object for community or collection */ dso: DSpaceObject = null; + /** + * The flag between upload and url + */ + isUpload = true; + + /** + * File URL when flag is for url + */ + fileURL: string; + public constructor(private location: Location, protected translate: TranslateService, protected notificationsService: NotificationsService, @@ -72,13 +83,22 @@ export class BatchImportPageComponent { * Starts import-metadata script with --zip fileName (and the selected file) */ public importMetadata() { - if (this.fileObject == null) { - this.notificationsService.error(this.translate.get('admin.metadata-import.page.error.addFile')); + if (this.fileObject == null && isEmpty(this.fileURL)) { + if (this.isUpload) { + this.notificationsService.error(this.translate.get('admin.metadata-import.page.error.addFile')); + } else { + this.notificationsService.error(this.translate.get('admin.metadata-import.page.error.addFileUrl')); + } } else { const parameterValues: ProcessParameter[] = [ - Object.assign(new ProcessParameter(), { name: '--zip', value: this.fileObject.name }), Object.assign(new ProcessParameter(), { name: '--add' }) ]; + if (this.isUpload) { + parameterValues.push(Object.assign(new ProcessParameter(), { name: '--zip', value: this.fileObject.name })); + } else { + this.fileObject = null; + parameterValues.push(Object.assign(new ProcessParameter(), { name: '--url', value: this.fileURL })); + } if (this.dso) { parameterValues.push(Object.assign(new ProcessParameter(), { name: '--collection', value: this.dso.uuid })); } @@ -127,4 +147,11 @@ export class BatchImportPageComponent { removeDspaceObject(): void { this.dso = null; } + + /** + * toggle the flag between upload and url + */ + toggleUpload() { + this.isUpload = !this.isUpload; + } } diff --git a/src/app/admin/admin-notifications/admin-notifications-routing-paths.ts b/src/app/admin/admin-notifications/admin-notifications-routing-paths.ts new file mode 100644 index 0000000000..870458fa9f --- /dev/null +++ b/src/app/admin/admin-notifications/admin-notifications-routing-paths.ts @@ -0,0 +1,9 @@ +import { URLCombiner } from '../../core/url-combiner/url-combiner'; +import { getNotificationsModuleRoute } from '../admin-routing-paths'; + +export const QUALITY_ASSURANCE_EDIT_PATH = 'quality-assurance'; +export const NOTIFICATIONS_RECITER_SUGGESTION_PATH = 'suggestion-targets'; + +export function getQualityAssuranceRoute(id: string) { + return new URLCombiner(getNotificationsModuleRoute(), QUALITY_ASSURANCE_EDIT_PATH, id).toString(); +} diff --git a/src/app/admin/admin-notifications/admin-notifications-routing.module.ts b/src/app/admin/admin-notifications/admin-notifications-routing.module.ts new file mode 100644 index 0000000000..60fa679777 --- /dev/null +++ b/src/app/admin/admin-notifications/admin-notifications-routing.module.ts @@ -0,0 +1,100 @@ +import { NgModule } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { AuthenticatedGuard } from '../../core/auth/authenticated.guard'; +import { I18nBreadcrumbResolver } from '../../core/breadcrumbs/i18n-breadcrumb.resolver'; +import { I18nBreadcrumbsService } from '../../core/breadcrumbs/i18n-breadcrumbs.service'; +import { NOTIFICATIONS_RECITER_SUGGESTION_PATH } from './admin-notifications-routing-paths'; +import { AdminNotificationsSuggestionTargetsPageComponent } from './admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page.component'; +import { AdminNotificationsSuggestionTargetsPageResolver } from './admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page-resolver.service'; +import { QUALITY_ASSURANCE_EDIT_PATH } from './admin-notifications-routing-paths'; +import { AdminQualityAssuranceTopicsPageComponent } from './admin-quality-assurance-topics-page/admin-quality-assurance-topics-page.component'; +import { AdminQualityAssuranceEventsPageComponent } from './admin-quality-assurance-events-page/admin-quality-assurance-events-page.component'; +import { AdminQualityAssuranceTopicsPageResolver } from './admin-quality-assurance-topics-page/admin-quality-assurance-topics-page-resolver.service'; +import { AdminQualityAssuranceEventsPageResolver } from './admin-quality-assurance-events-page/admin-quality-assurance-events-page.resolver'; +import { AdminQualityAssuranceSourcePageComponent } from './admin-quality-assurance-source-page-component/admin-quality-assurance-source-page.component'; +import { AdminQualityAssuranceSourcePageResolver } from './admin-quality-assurance-source-page-component/admin-quality-assurance-source-page-resolver.service'; +import { SourceDataResolver } from './admin-quality-assurance-source-page-component/admin-quality-assurance-source-data.reslover'; + +@NgModule({ + imports: [ + RouterModule.forChild([ + { + canActivate: [ AuthenticatedGuard ], + path: `${NOTIFICATIONS_RECITER_SUGGESTION_PATH}`, + component: AdminNotificationsSuggestionTargetsPageComponent, + pathMatch: 'full', + resolve: { + breadcrumb: I18nBreadcrumbResolver, + reciterSuggestionTargetParams: AdminNotificationsSuggestionTargetsPageResolver + }, + data: { + title: 'admin.notifications.recitersuggestion.page.title', + breadcrumbKey: 'admin.notifications.recitersuggestion', + showBreadcrumbsFluid: false + } + }, + { + canActivate: [ AuthenticatedGuard ], + path: `${QUALITY_ASSURANCE_EDIT_PATH}/:sourceId`, + component: AdminQualityAssuranceTopicsPageComponent, + pathMatch: 'full', + resolve: { + breadcrumb: I18nBreadcrumbResolver, + openaireQualityAssuranceTopicsParams: AdminQualityAssuranceTopicsPageResolver + }, + data: { + title: 'admin.quality-assurance.page.title', + breadcrumbKey: 'admin.quality-assurance', + showBreadcrumbsFluid: false + } + }, + { + canActivate: [ AuthenticatedGuard ], + path: `${QUALITY_ASSURANCE_EDIT_PATH}`, + component: AdminQualityAssuranceSourcePageComponent, + pathMatch: 'full', + resolve: { + breadcrumb: I18nBreadcrumbResolver, + openaireQualityAssuranceSourceParams: AdminQualityAssuranceSourcePageResolver, + sourceData: SourceDataResolver + }, + data: { + title: 'admin.notifications.source.breadcrumbs', + breadcrumbKey: 'admin.notifications.source', + showBreadcrumbsFluid: false + } + }, + { + canActivate: [ AuthenticatedGuard ], + path: `${QUALITY_ASSURANCE_EDIT_PATH}/:sourceId/:topicId`, + component: AdminQualityAssuranceEventsPageComponent, + pathMatch: 'full', + resolve: { + breadcrumb: I18nBreadcrumbResolver, + openaireQualityAssuranceEventsParams: AdminQualityAssuranceEventsPageResolver + }, + data: { + title: 'admin.notifications.event.page.title', + breadcrumbKey: 'admin.notifications.event', + showBreadcrumbsFluid: false + } + } + ]) + ], + providers: [ + I18nBreadcrumbResolver, + I18nBreadcrumbsService, + AdminNotificationsSuggestionTargetsPageResolver, + SourceDataResolver, + AdminQualityAssuranceSourcePageResolver, + AdminQualityAssuranceTopicsPageResolver, + AdminQualityAssuranceEventsPageResolver, + ] +}) +/** + * Routing module for the Notifications section of the admin sidebar + */ +export class AdminNotificationsRoutingModule { + +} diff --git a/src/app/admin/admin-notifications/admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page-resolver.service.ts b/src/app/admin/admin-notifications/admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page-resolver.service.ts new file mode 100644 index 0000000000..df1f4b81e6 --- /dev/null +++ b/src/app/admin/admin-notifications/admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page-resolver.service.ts @@ -0,0 +1,32 @@ +import { Injectable } from '@angular/core'; +import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router'; + +/** + * Interface for the route parameters. + */ +export interface AdminNotificationsSuggestionTargetsPageParams { + pageId?: string; + pageSize?: number; + currentPage?: number; +} + +/** + * This class represents a resolver that retrieve the route data before the route is activated. + */ +@Injectable() +export class AdminNotificationsSuggestionTargetsPageResolver implements Resolve { + + /** + * Method for resolving the parameters in the current route. + * @param {ActivatedRouteSnapshot} route The current ActivatedRouteSnapshot + * @param {RouterStateSnapshot} state The current RouterStateSnapshot + * @returns AdminNotificationsSuggestionTargetsPageParams Emits the route parameters + */ + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): AdminNotificationsSuggestionTargetsPageParams { + return { + pageId: route.queryParams.pageId, + pageSize: parseInt(route.queryParams.pageSize, 10), + currentPage: parseInt(route.queryParams.page, 10) + }; + } +} diff --git a/src/app/admin/admin-notifications/admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page.component.html b/src/app/admin/admin-notifications/admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page.component.html new file mode 100644 index 0000000000..5d06a1a6bd --- /dev/null +++ b/src/app/admin/admin-notifications/admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page.component.html @@ -0,0 +1 @@ + diff --git a/src/app/admin/admin-notifications/admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page.component.scss b/src/app/admin/admin-notifications/admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/admin/admin-notifications/admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page.component.spec.ts b/src/app/admin/admin-notifications/admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page.component.spec.ts new file mode 100644 index 0000000000..f9e407f402 --- /dev/null +++ b/src/app/admin/admin-notifications/admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page.component.spec.ts @@ -0,0 +1,38 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; + +import { AdminNotificationsSuggestionTargetsPageComponent } from './admin-notifications-suggestion-targets-page.component'; +import { NO_ERRORS_SCHEMA } from '@angular/core'; +import { CommonModule } from '@angular/common'; +import { TranslateModule } from '@ngx-translate/core'; + +describe('AdminNotificationsSuggestionTargetsPageComponent', () => { + let component: AdminNotificationsSuggestionTargetsPageComponent; + let fixture: ComponentFixture; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + CommonModule, + TranslateModule.forRoot() + ], + declarations: [ + AdminNotificationsSuggestionTargetsPageComponent + ], + providers: [ + AdminNotificationsSuggestionTargetsPageComponent + ], + schemas: [NO_ERRORS_SCHEMA] + }) + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(AdminNotificationsSuggestionTargetsPageComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/src/app/admin/admin-notifications/admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page.component.ts b/src/app/admin/admin-notifications/admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page.component.ts new file mode 100644 index 0000000000..a9a77f5089 --- /dev/null +++ b/src/app/admin/admin-notifications/admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page.component.ts @@ -0,0 +1,10 @@ +import { Component } from '@angular/core'; + +@Component({ + selector: 'ds-admin-notifications-reciter-page', + templateUrl: './admin-notifications-suggestion-targets-page.component.html', + styleUrls: ['./admin-notifications-suggestion-targets-page.component.scss'] +}) +export class AdminNotificationsSuggestionTargetsPageComponent { + +} diff --git a/src/app/admin/admin-notifications/admin-notifications.module.ts b/src/app/admin/admin-notifications/admin-notifications.module.ts new file mode 100644 index 0000000000..53b3aada6e --- /dev/null +++ b/src/app/admin/admin-notifications/admin-notifications.module.ts @@ -0,0 +1,33 @@ +import { CommonModule } from '@angular/common'; +import { NgModule } from '@angular/core'; +import { CoreModule } from '../../core/core.module'; +import { SharedModule } from '../../shared/shared.module'; +import { AdminNotificationsRoutingModule } from './admin-notifications-routing.module'; +import { AdminNotificationsSuggestionTargetsPageComponent } from './admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page.component'; +import { AdminQualityAssuranceTopicsPageComponent } from './admin-quality-assurance-topics-page/admin-quality-assurance-topics-page.component'; +import { AdminQualityAssuranceEventsPageComponent } from './admin-quality-assurance-events-page/admin-quality-assurance-events-page.component'; +import { AdminQualityAssuranceSourcePageComponent } from './admin-quality-assurance-source-page-component/admin-quality-assurance-source-page.component'; +import {SuggestionNotificationsModule} from '../../suggestion-notifications/suggestion-notifications.module'; + +@NgModule({ + imports: [ + CommonModule, + SharedModule, + CoreModule.forRoot(), + AdminNotificationsRoutingModule, + SuggestionNotificationsModule + ], + declarations: [ + AdminNotificationsSuggestionTargetsPageComponent, + AdminQualityAssuranceTopicsPageComponent, + AdminQualityAssuranceEventsPageComponent, + AdminQualityAssuranceSourcePageComponent + ], + entryComponents: [] +}) +/** + * This module handles all components related to the notifications pages + */ +export class AdminNotificationsModule { + +} diff --git a/src/app/admin/admin-notifications/admin-quality-assurance-events-page/admin-quality-assurance-events-page.component.html b/src/app/admin/admin-notifications/admin-quality-assurance-events-page/admin-quality-assurance-events-page.component.html new file mode 100644 index 0000000000..315209d342 --- /dev/null +++ b/src/app/admin/admin-notifications/admin-quality-assurance-events-page/admin-quality-assurance-events-page.component.html @@ -0,0 +1 @@ + diff --git a/src/app/admin/admin-notifications/admin-quality-assurance-events-page/admin-quality-assurance-events-page.component.spec.ts b/src/app/admin/admin-notifications/admin-quality-assurance-events-page/admin-quality-assurance-events-page.component.spec.ts new file mode 100644 index 0000000000..b952078215 --- /dev/null +++ b/src/app/admin/admin-notifications/admin-quality-assurance-events-page/admin-quality-assurance-events-page.component.spec.ts @@ -0,0 +1,26 @@ +import { NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { AdminQualityAssuranceEventsPageComponent } from './admin-quality-assurance-events-page.component'; + +describe('AdminQualityAssuranceEventsPageComponent', () => { + let component: AdminQualityAssuranceEventsPageComponent; + let fixture: ComponentFixture; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [ AdminQualityAssuranceEventsPageComponent ], + schemas: [NO_ERRORS_SCHEMA] + }) + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(AdminQualityAssuranceEventsPageComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create AdminQualityAssuranceEventsPageComponent', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/src/app/admin/admin-notifications/admin-quality-assurance-events-page/admin-quality-assurance-events-page.component.ts b/src/app/admin/admin-notifications/admin-quality-assurance-events-page/admin-quality-assurance-events-page.component.ts new file mode 100644 index 0000000000..bd3470f301 --- /dev/null +++ b/src/app/admin/admin-notifications/admin-quality-assurance-events-page/admin-quality-assurance-events-page.component.ts @@ -0,0 +1,12 @@ +import { Component } from '@angular/core'; + +/** + * Component for the page that show the QA events related to a specific topic. + */ +@Component({ + selector: 'ds-quality-assurance-events-page', + templateUrl: './admin-quality-assurance-events-page.component.html' +}) +export class AdminQualityAssuranceEventsPageComponent { + +} diff --git a/src/app/admin/admin-notifications/admin-quality-assurance-events-page/admin-quality-assurance-events-page.resolver.ts b/src/app/admin/admin-notifications/admin-quality-assurance-events-page/admin-quality-assurance-events-page.resolver.ts new file mode 100644 index 0000000000..3139355629 --- /dev/null +++ b/src/app/admin/admin-notifications/admin-quality-assurance-events-page/admin-quality-assurance-events-page.resolver.ts @@ -0,0 +1,32 @@ +import { Injectable } from '@angular/core'; +import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; + +/** + * Interface for the route parameters. + */ +export interface AdminQualityAssuranceEventsPageParams { + pageId?: string; + pageSize?: number; + currentPage?: number; +} + +/** + * This class represents a resolver that retrieve the route data before the route is activated. + */ +@Injectable() +export class AdminQualityAssuranceEventsPageResolver implements Resolve { + + /** + * Method for resolving the parameters in the current route. + * @param {ActivatedRouteSnapshot} route The current ActivatedRouteSnapshot + * @param {RouterStateSnapshot} state The current RouterStateSnapshot + * @returns AdminQualityAssuranceEventsPageParams Emits the route parameters + */ + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): AdminQualityAssuranceEventsPageParams { + return { + pageId: route.queryParams.pageId, + pageSize: parseInt(route.queryParams.pageSize, 10), + currentPage: parseInt(route.queryParams.page, 10) + }; + } +} diff --git a/src/app/admin/admin-notifications/admin-quality-assurance-source-page-component/admin-quality-assurance-source-data.reslover.ts b/src/app/admin/admin-notifications/admin-quality-assurance-source-page-component/admin-quality-assurance-source-data.reslover.ts new file mode 100644 index 0000000000..8475732aed --- /dev/null +++ b/src/app/admin/admin-notifications/admin-quality-assurance-source-page-component/admin-quality-assurance-source-data.reslover.ts @@ -0,0 +1,45 @@ +import { Injectable } from '@angular/core'; +import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot, Router } from '@angular/router'; +import { Observable } from 'rxjs'; +import { map } from 'rxjs/operators'; +import { PaginatedList } from '../../../core/data/paginated-list.model'; +import { QualityAssuranceSourceObject } from '../../../core/suggestion-notifications/qa/models/quality-assurance-source.model'; +import { QualityAssuranceSourceService } from '../../../suggestion-notifications/qa/source/quality-assurance-source.service'; +/** + * This class represents a resolver that retrieve the route data before the route is activated. + */ +@Injectable() +export class SourceDataResolver implements Resolve> { + /** + * Initialize the effect class variables. + * @param {QualityAssuranceSourceService} qualityAssuranceSourceService + */ + constructor( + private qualityAssuranceSourceService: QualityAssuranceSourceService, + private router: Router + ) { } + /** + * Method for resolving the parameters in the current route. + * @param {ActivatedRouteSnapshot} route The current ActivatedRouteSnapshot + * @param {RouterStateSnapshot} state The current RouterStateSnapshot + * @returns Observable + */ + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + return this.qualityAssuranceSourceService.getSources(5,0).pipe( + map((sources: PaginatedList) => { + if (sources.page.length === 1) { + this.router.navigate([this.getResolvedUrl(route) + '/' + sources.page[0].id]); + } + return sources.page; + })); + } + + /** + * + * @param route url path + * @returns url path + */ + getResolvedUrl(route: ActivatedRouteSnapshot): string { + return route.pathFromRoot.map(v => v.url.map(segment => segment.toString()).join('/')).join('/'); + } +} diff --git a/src/app/admin/admin-notifications/admin-quality-assurance-source-page-component/admin-quality-assurance-source-page-resolver.service.ts b/src/app/admin/admin-notifications/admin-quality-assurance-source-page-component/admin-quality-assurance-source-page-resolver.service.ts new file mode 100644 index 0000000000..ac9bdb48d6 --- /dev/null +++ b/src/app/admin/admin-notifications/admin-quality-assurance-source-page-component/admin-quality-assurance-source-page-resolver.service.ts @@ -0,0 +1,32 @@ +import { Injectable } from '@angular/core'; +import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router'; + +/** + * Interface for the route parameters. + */ +export interface AdminQualityAssuranceSourcePageParams { + pageId?: string; + pageSize?: number; + currentPage?: number; +} + +/** + * This class represents a resolver that retrieve the route data before the route is activated. + */ +@Injectable() +export class AdminQualityAssuranceSourcePageResolver implements Resolve { + + /** + * Method for resolving the parameters in the current route. + * @param {ActivatedRouteSnapshot} route The current ActivatedRouteSnapshot + * @param {RouterStateSnapshot} state The current RouterStateSnapshot + * @returns AdminQualityAssuranceSourcePageParams Emits the route parameters + */ + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): AdminQualityAssuranceSourcePageParams { + return { + pageId: route.queryParams.pageId, + pageSize: parseInt(route.queryParams.pageSize, 10), + currentPage: parseInt(route.queryParams.page, 10) + }; + } +} diff --git a/src/app/admin/admin-notifications/admin-quality-assurance-source-page-component/admin-quality-assurance-source-page.component.html b/src/app/admin/admin-notifications/admin-quality-assurance-source-page-component/admin-quality-assurance-source-page.component.html new file mode 100644 index 0000000000..709103cf3d --- /dev/null +++ b/src/app/admin/admin-notifications/admin-quality-assurance-source-page-component/admin-quality-assurance-source-page.component.html @@ -0,0 +1 @@ + diff --git a/src/app/admin/admin-notifications/admin-quality-assurance-source-page-component/admin-quality-assurance-source-page.component.spec.ts b/src/app/admin/admin-notifications/admin-quality-assurance-source-page-component/admin-quality-assurance-source-page.component.spec.ts new file mode 100644 index 0000000000..451c911c4c --- /dev/null +++ b/src/app/admin/admin-notifications/admin-quality-assurance-source-page-component/admin-quality-assurance-source-page.component.spec.ts @@ -0,0 +1,27 @@ +import { NO_ERRORS_SCHEMA } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { AdminQualityAssuranceSourcePageComponent } from './admin-quality-assurance-source-page.component'; + +describe('AdminQualityAssuranceSourcePageComponent', () => { + let component: AdminQualityAssuranceSourcePageComponent; + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + declarations: [ AdminQualityAssuranceSourcePageComponent ], + schemas: [NO_ERRORS_SCHEMA] + }) + .compileComponents(); + }); + + beforeEach(() => { + fixture = TestBed.createComponent(AdminQualityAssuranceSourcePageComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create AdminQualityAssuranceSourcePageComponent', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/src/app/admin/admin-notifications/admin-quality-assurance-source-page-component/admin-quality-assurance-source-page.component.ts b/src/app/admin/admin-notifications/admin-quality-assurance-source-page-component/admin-quality-assurance-source-page.component.ts new file mode 100644 index 0000000000..447e5a2e55 --- /dev/null +++ b/src/app/admin/admin-notifications/admin-quality-assurance-source-page-component/admin-quality-assurance-source-page.component.ts @@ -0,0 +1,10 @@ +import { Component } from '@angular/core'; + +/** + * Component for the page that show the QA sources. + */ +@Component({ + selector: 'ds-admin-quality-assurance-source-page-component', + templateUrl: './admin-quality-assurance-source-page.component.html', +}) +export class AdminQualityAssuranceSourcePageComponent {} diff --git a/src/app/admin/admin-notifications/admin-quality-assurance-topics-page/admin-quality-assurance-topics-page-resolver.service.ts b/src/app/admin/admin-notifications/admin-quality-assurance-topics-page/admin-quality-assurance-topics-page-resolver.service.ts new file mode 100644 index 0000000000..47500d1878 --- /dev/null +++ b/src/app/admin/admin-notifications/admin-quality-assurance-topics-page/admin-quality-assurance-topics-page-resolver.service.ts @@ -0,0 +1,32 @@ +import { Injectable } from '@angular/core'; +import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router'; + +/** + * Interface for the route parameters. + */ +export interface AdminQualityAssuranceTopicsPageParams { + pageId?: string; + pageSize?: number; + currentPage?: number; +} + +/** + * This class represents a resolver that retrieve the route data before the route is activated. + */ +@Injectable() +export class AdminQualityAssuranceTopicsPageResolver implements Resolve { + + /** + * Method for resolving the parameters in the current route. + * @param {ActivatedRouteSnapshot} route The current ActivatedRouteSnapshot + * @param {RouterStateSnapshot} state The current RouterStateSnapshot + * @returns AdminQualityAssuranceTopicsPageParams Emits the route parameters + */ + resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): AdminQualityAssuranceTopicsPageParams { + return { + pageId: route.queryParams.pageId, + pageSize: parseInt(route.queryParams.pageSize, 10), + currentPage: parseInt(route.queryParams.page, 10) + }; + } +} diff --git a/src/app/admin/admin-notifications/admin-quality-assurance-topics-page/admin-quality-assurance-topics-page.component.html b/src/app/admin/admin-notifications/admin-quality-assurance-topics-page/admin-quality-assurance-topics-page.component.html new file mode 100644 index 0000000000..fc905ad724 --- /dev/null +++ b/src/app/admin/admin-notifications/admin-quality-assurance-topics-page/admin-quality-assurance-topics-page.component.html @@ -0,0 +1 @@ + diff --git a/src/app/admin/admin-notifications/admin-quality-assurance-topics-page/admin-quality-assurance-topics-page.component.spec.ts b/src/app/admin/admin-notifications/admin-quality-assurance-topics-page/admin-quality-assurance-topics-page.component.spec.ts new file mode 100644 index 0000000000..a32f60f017 --- /dev/null +++ b/src/app/admin/admin-notifications/admin-quality-assurance-topics-page/admin-quality-assurance-topics-page.component.spec.ts @@ -0,0 +1,26 @@ +import { NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { AdminQualityAssuranceTopicsPageComponent } from './admin-quality-assurance-topics-page.component'; + +describe('AdminQualityAssuranceTopicsPageComponent', () => { + let component: AdminQualityAssuranceTopicsPageComponent; + let fixture: ComponentFixture; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [ AdminQualityAssuranceTopicsPageComponent ], + schemas: [NO_ERRORS_SCHEMA] + }) + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(AdminQualityAssuranceTopicsPageComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create AdminQualityAssuranceTopicsPageComponent', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/src/app/admin/admin-notifications/admin-quality-assurance-topics-page/admin-quality-assurance-topics-page.component.ts b/src/app/admin/admin-notifications/admin-quality-assurance-topics-page/admin-quality-assurance-topics-page.component.ts new file mode 100644 index 0000000000..f17d3448d5 --- /dev/null +++ b/src/app/admin/admin-notifications/admin-quality-assurance-topics-page/admin-quality-assurance-topics-page.component.ts @@ -0,0 +1,12 @@ +import { Component } from '@angular/core'; + +/** + * Component for the page that show the QA topics related to a specific source. + */ +@Component({ + selector: 'ds-notification-qa-page', + templateUrl: './admin-quality-assurance-topics-page.component.html' +}) +export class AdminQualityAssuranceTopicsPageComponent { + +} diff --git a/src/app/admin/admin-registries/metadata-registry/metadata-schema-form/metadata-schema-form.component.spec.ts b/src/app/admin/admin-registries/metadata-registry/metadata-schema-form/metadata-schema-form.component.spec.ts index 8d416c2df8..b758767ddb 100644 --- a/src/app/admin/admin-registries/metadata-registry/metadata-schema-form/metadata-schema-form.component.spec.ts +++ b/src/app/admin/admin-registries/metadata-registry/metadata-schema-form/metadata-schema-form.component.spec.ts @@ -1,5 +1,4 @@ import { ComponentFixture, inject, TestBed, waitForAsync } from '@angular/core/testing'; - import { MetadataSchemaFormComponent } from './metadata-schema-form.component'; import { NO_ERRORS_SCHEMA } from '@angular/core'; import { CommonModule } from '@angular/common'; @@ -29,14 +28,16 @@ describe('MetadataSchemaFormComponent', () => { createFormGroup: () => { return { patchValue: () => { - } + }, + reset(_value?: any, _options?: { onlySelf?: boolean; emitEvent?: boolean; }): void { + }, }; } }; /* eslint-enable no-empty, @typescript-eslint/no-empty-function */ beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ + return TestBed.configureTestingModule({ imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], declarations: [MetadataSchemaFormComponent, EnumKeysPipe], providers: [ @@ -64,7 +65,7 @@ describe('MetadataSchemaFormComponent', () => { const expected = Object.assign(new MetadataSchema(), { namespace: namespace, prefix: prefix - }); + } as MetadataSchema); beforeEach(() => { spyOn(component.submitForm, 'emit'); @@ -79,11 +80,10 @@ describe('MetadataSchemaFormComponent', () => { fixture.detectChanges(); }); - it('should emit a new schema using the correct values', waitForAsync(() => { - fixture.whenStable().then(() => { - expect(component.submitForm.emit).toHaveBeenCalledWith(expected); - }); - })); + it('should emit a new schema using the correct values', async () => { + await fixture.whenStable(); + expect(component.submitForm.emit).toHaveBeenCalledWith(expected); + }); }); describe('with an active schema', () => { @@ -91,7 +91,7 @@ describe('MetadataSchemaFormComponent', () => { id: 1, namespace: namespace, prefix: prefix - }); + } as MetadataSchema); beforeEach(() => { spyOn(registryService, 'getActiveMetadataSchema').and.returnValue(observableOf(expectedWithId)); @@ -99,11 +99,10 @@ describe('MetadataSchemaFormComponent', () => { fixture.detectChanges(); }); - it('should edit the existing schema using the correct values', waitForAsync(() => { - fixture.whenStable().then(() => { - expect(component.submitForm.emit).toHaveBeenCalledWith(expectedWithId); - }); - })); + it('should edit the existing schema using the correct values', async () => { + await fixture.whenStable(); + expect(component.submitForm.emit).toHaveBeenCalledWith(expectedWithId); + }); }); }); }); diff --git a/src/app/admin/admin-registries/metadata-registry/metadata-schema-form/metadata-schema-form.component.ts b/src/app/admin/admin-registries/metadata-registry/metadata-schema-form/metadata-schema-form.component.ts index 5c6885ae72..1992289ff7 100644 --- a/src/app/admin/admin-registries/metadata-registry/metadata-schema-form/metadata-schema-form.component.ts +++ b/src/app/admin/admin-registries/metadata-registry/metadata-schema-form/metadata-schema-form.component.ts @@ -5,7 +5,7 @@ import { DynamicFormLayout, DynamicInputModel } from '@ng-dynamic-forms/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { RegistryService } from '../../../../core/registry/registry.service'; import { FormBuilderService } from '../../../../shared/form/builder/form-builder.service'; import { take } from 'rxjs/operators'; @@ -66,7 +66,7 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy { /** * A FormGroup that combines all inputs */ - formGroup: FormGroup; + formGroup: UntypedFormGroup; /** * An EventEmitter that's fired whenever the form is being submitted @@ -77,19 +77,24 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy { } ngOnInit() { - combineLatest( + combineLatest([ this.translateService.get(`${this.messagePrefix}.name`), this.translateService.get(`${this.messagePrefix}.namespace`) - ).subscribe(([name, namespace]) => { + ]).subscribe(([name, namespace]) => { this.name = new DynamicInputModel({ id: 'name', label: name, name: 'name', validators: { required: null, - pattern: '^[^ ,_]{1,32}$' + pattern: '^[^. ,]*$', + maxLength: 32, }, required: true, + errorMessages: { + pattern: 'error.validation.metadata.name.invalid-pattern', + maxLength: 'error.validation.metadata.name.max-length', + }, }); this.namespace = new DynamicInputModel({ id: 'namespace', @@ -97,8 +102,12 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy { name: 'namespace', validators: { required: null, + maxLength: 256, }, required: true, + errorMessages: { + maxLength: 'error.validation.metadata.namespace.max-length', + }, }); this.formModel = [ new DynamicFormGroupModel( @@ -108,13 +117,18 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy { }) ]; this.formGroup = this.formBuilderService.createFormGroup(this.formModel); - this.registryService.getActiveMetadataSchema().subscribe((schema) => { - this.formGroup.patchValue({ - metadatadataschemagroup:{ - name: schema != null ? schema.prefix : '', - namespace: schema != null ? schema.namespace : '' - } - }); + this.registryService.getActiveMetadataSchema().subscribe((schema: MetadataSchema) => { + if (schema == null) { + this.clearFields(); + } else { + this.formGroup.patchValue({ + metadatadataschemagroup: { + name: schema.prefix, + namespace: schema.namespace, + }, + }); + this.name.disabled = true; + } }); }); } @@ -132,10 +146,10 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy { * When the schema has no id attached -> Create new schema * Emit the updated/created schema using the EventEmitter submitForm */ - onSubmit() { + onSubmit(): void { this.registryService.clearMetadataSchemaRequests().subscribe(); this.registryService.getActiveMetadataSchema().pipe(take(1)).subscribe( - (schema) => { + (schema: MetadataSchema) => { const values = { prefix: this.name.value, namespace: this.namespace.value @@ -147,9 +161,9 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy { } else { this.registryService.createOrUpdateMetadataSchema(Object.assign(new MetadataSchema(), schema, { id: schema.id, - prefix: (values.prefix ? values.prefix : schema.prefix), - namespace: (values.namespace ? values.namespace : schema.namespace) - })).subscribe((updatedSchema) => { + prefix: schema.prefix, + namespace: values.namespace, + })).subscribe((updatedSchema: MetadataSchema) => { this.submitForm.emit(updatedSchema); }); } @@ -162,13 +176,9 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy { /** * Reset all input-fields to be empty */ - clearFields() { - this.formGroup.patchValue({ - metadatadataschemagroup:{ - prefix: '', - namespace: '' - } - }); + clearFields(): void { + this.formGroup.reset('metadatadataschemagroup'); + this.name.disabled = false; } /** diff --git a/src/app/admin/admin-registries/metadata-schema/metadata-field-form/metadata-field-form.component.spec.ts b/src/app/admin/admin-registries/metadata-schema/metadata-field-form/metadata-field-form.component.spec.ts index e13180d633..ad7b54945d 100644 --- a/src/app/admin/admin-registries/metadata-schema/metadata-field-form/metadata-field-form.component.spec.ts +++ b/src/app/admin/admin-registries/metadata-schema/metadata-field-form/metadata-field-form.component.spec.ts @@ -39,14 +39,16 @@ describe('MetadataFieldFormComponent', () => { createFormGroup: () => { return { patchValue: () => { - } + }, + reset(_value?: any, _options?: { onlySelf?: boolean; emitEvent?: boolean; }): void { + }, }; } }; /* eslint-enable no-empty, @typescript-eslint/no-empty-function */ beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ + return TestBed.configureTestingModule({ imports: [CommonModule, RouterTestingModule.withRoutes([]), TranslateModule.forRoot(), NgbModule], declarations: [MetadataFieldFormComponent, EnumKeysPipe], providers: [ @@ -98,11 +100,10 @@ describe('MetadataFieldFormComponent', () => { fixture.detectChanges(); }); - it('should emit a new field using the correct values', waitForAsync(() => { - fixture.whenStable().then(() => { - expect(component.submitForm.emit).toHaveBeenCalledWith(expected); - }); - })); + it('should emit a new field using the correct values', async () => { + await fixture.whenStable(); + expect(component.submitForm.emit).toHaveBeenCalledWith(expected); + }); }); describe('with an active field', () => { @@ -120,11 +121,10 @@ describe('MetadataFieldFormComponent', () => { fixture.detectChanges(); }); - it('should edit the existing field using the correct values', waitForAsync(() => { - fixture.whenStable().then(() => { - expect(component.submitForm.emit).toHaveBeenCalledWith(expectedWithId); - }); - })); + it('should edit the existing field using the correct values', async () => { + await fixture.whenStable(); + expect(component.submitForm.emit).toHaveBeenCalledWith(expectedWithId); + }); }); }); }); diff --git a/src/app/admin/admin-registries/metadata-schema/metadata-field-form/metadata-field-form.component.ts b/src/app/admin/admin-registries/metadata-schema/metadata-field-form/metadata-field-form.component.ts index 1c000c3c76..773e0600fb 100644 --- a/src/app/admin/admin-registries/metadata-schema/metadata-field-form/metadata-field-form.component.ts +++ b/src/app/admin/admin-registries/metadata-schema/metadata-field-form/metadata-field-form.component.ts @@ -5,7 +5,7 @@ import { DynamicFormLayout, DynamicInputModel } from '@ng-dynamic-forms/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { RegistryService } from '../../../../core/registry/registry.service'; import { FormBuilderService } from '../../../../shared/form/builder/form-builder.service'; import { take } from 'rxjs/operators'; @@ -82,7 +82,7 @@ export class MetadataFieldFormComponent implements OnInit, OnDestroy { /** * A FormGroup that combines all inputs */ - formGroup: FormGroup; + formGroup: UntypedFormGroup; /** * An EventEmitter that's fired whenever the form is being submitted @@ -98,25 +98,39 @@ export class MetadataFieldFormComponent implements OnInit, OnDestroy { * Initialize the component, setting up the necessary Models for the dynamic form */ ngOnInit() { - combineLatest( + combineLatest([ this.translateService.get(`${this.messagePrefix}.element`), this.translateService.get(`${this.messagePrefix}.qualifier`), this.translateService.get(`${this.messagePrefix}.scopenote`) - ).subscribe(([element, qualifier, scopenote]) => { + ]).subscribe(([element, qualifier, scopenote]) => { this.element = new DynamicInputModel({ id: 'element', label: element, name: 'element', validators: { required: null, + pattern: '^[^. ,]*$', + maxLength: 64, }, required: true, + errorMessages: { + pattern: 'error.validation.metadata.element.invalid-pattern', + maxLength: 'error.validation.metadata.element.max-length', + }, }); this.qualifier = new DynamicInputModel({ id: 'qualifier', label: qualifier, name: 'qualifier', + validators: { + pattern: '^[^. ,]*$', + maxLength: 64, + }, required: false, + errorMessages: { + pattern: 'error.validation.metadata.qualifier.invalid-pattern', + maxLength: 'error.validation.metadata.qualifier.max-length', + }, }); this.scopeNote = new DynamicInputModel({ id: 'scopeNote', @@ -132,14 +146,20 @@ export class MetadataFieldFormComponent implements OnInit, OnDestroy { }) ]; this.formGroup = this.formBuilderService.createFormGroup(this.formModel); - this.registryService.getActiveMetadataField().subscribe((field) => { - this.formGroup.patchValue({ - metadatadatafieldgroup: { - element: field != null ? field.element : '', - qualifier: field != null ? field.qualifier : '', - scopeNote: field != null ? field.scopeNote : '' - } - }); + this.registryService.getActiveMetadataField().subscribe((field: MetadataField): void => { + if (field == null) { + this.clearFields(); + } else { + this.formGroup.patchValue({ + metadatadatafieldgroup: { + element: field.element, + qualifier: field.qualifier, + scopeNote: field.scopeNote, + }, + }); + this.element.disabled = true; + this.qualifier.disabled = true; + } }); }); } @@ -157,25 +177,24 @@ export class MetadataFieldFormComponent implements OnInit, OnDestroy { * When the field has no id attached -> Create new field * Emit the updated/created field using the EventEmitter submitForm */ - onSubmit() { + onSubmit(): void { this.registryService.getActiveMetadataField().pipe(take(1)).subscribe( - (field) => { - const values = { - element: this.element.value, - qualifier: this.qualifier.value, - scopeNote: this.scopeNote.value - }; + (field: MetadataField) => { if (field == null) { - this.registryService.createMetadataField(Object.assign(new MetadataField(), values), this.metadataSchema).subscribe((newField) => { + this.registryService.createMetadataField(Object.assign(new MetadataField(), { + element: this.element.value, + qualifier: this.qualifier.value, + scopeNote: this.scopeNote.value, + }), this.metadataSchema).subscribe((newField: MetadataField) => { this.submitForm.emit(newField); }); } else { this.registryService.updateMetadataField(Object.assign(new MetadataField(), field, { id: field.id, - element: (values.element ? values.element : field.element), - qualifier: (values.qualifier ? values.qualifier : field.qualifier), - scopeNote: (values.scopeNote ? values.scopeNote : field.scopeNote) - })).subscribe((updatedField) => { + element: field.element, + qualifier: field.qualifier, + scopeNote: this.scopeNote.value, + })).subscribe((updatedField: MetadataField) => { this.submitForm.emit(updatedField); }); } @@ -188,14 +207,10 @@ export class MetadataFieldFormComponent implements OnInit, OnDestroy { /** * Reset all input-fields to be empty */ - clearFields() { - this.formGroup.patchValue({ - metadatadatafieldgroup: { - element: '', - qualifier: '', - scopeNote: '' - } - }); + clearFields(): void { + this.formGroup.reset('metadatadatafieldgroup'); + this.element.disabled = false; + this.qualifier.disabled = false; } /** diff --git a/src/app/admin/admin-routing-paths.ts b/src/app/admin/admin-routing-paths.ts index 3168ea93c9..30f801cecb 100644 --- a/src/app/admin/admin-routing-paths.ts +++ b/src/app/admin/admin-routing-paths.ts @@ -2,7 +2,12 @@ import { URLCombiner } from '../core/url-combiner/url-combiner'; import { getAdminModuleRoute } from '../app-routing-paths'; export const REGISTRIES_MODULE_PATH = 'registries'; +export const NOTIFICATIONS_MODULE_PATH = 'notifications'; export function getRegistriesModuleRoute() { return new URLCombiner(getAdminModuleRoute(), REGISTRIES_MODULE_PATH).toString(); } + +export function getNotificationsModuleRoute() { + return new URLCombiner(getAdminModuleRoute(), NOTIFICATIONS_MODULE_PATH).toString(); +} diff --git a/src/app/admin/admin-routing.module.ts b/src/app/admin/admin-routing.module.ts index 8e4f13b164..a7d19a6935 100644 --- a/src/app/admin/admin-routing.module.ts +++ b/src/app/admin/admin-routing.module.ts @@ -6,12 +6,17 @@ import { I18nBreadcrumbResolver } from '../core/breadcrumbs/i18n-breadcrumb.reso import { AdminWorkflowPageComponent } from './admin-workflow-page/admin-workflow-page.component'; import { I18nBreadcrumbsService } from '../core/breadcrumbs/i18n-breadcrumbs.service'; import { AdminCurationTasksComponent } from './admin-curation-tasks/admin-curation-tasks.component'; -import { REGISTRIES_MODULE_PATH } from './admin-routing-paths'; +import { REGISTRIES_MODULE_PATH, NOTIFICATIONS_MODULE_PATH } from './admin-routing-paths'; import { BatchImportPageComponent } from './admin-import-batch-page/batch-import-page.component'; @NgModule({ imports: [ RouterModule.forChild([ + { + path: NOTIFICATIONS_MODULE_PATH, + loadChildren: () => import('./admin-notifications/admin-notifications.module') + .then((m) => m.AdminNotificationsModule), + }, { path: REGISTRIES_MODULE_PATH, loadChildren: () => import('./admin-registries/admin-registries.module') diff --git a/src/app/admin/admin-search-page/admin-search-results/admin-search-result-grid-element/item-search-result/item-admin-search-result-grid-element.component.spec.ts b/src/app/admin/admin-search-page/admin-search-results/admin-search-result-grid-element/item-search-result/item-admin-search-result-grid-element.component.spec.ts index e478aa3ef3..ee3de42131 100644 --- a/src/app/admin/admin-search-page/admin-search-results/admin-search-result-grid-element/item-search-result/item-admin-search-result-grid-element.component.spec.ts +++ b/src/app/admin/admin-search-page/admin-search-results/admin-search-result-grid-element/item-search-result/item-admin-search-result-grid-element.component.spec.ts @@ -19,7 +19,7 @@ import { createSuccessfulRemoteDataObject$ } from '../../../../../shared/remote- import { getMockThemeService } from '../../../../../shared/mocks/theme-service.mock'; import { ThemeService } from '../../../../../shared/theme-support/theme.service'; import { AccessStatusDataService } from '../../../../../core/data/access-status-data.service'; -import { AccessStatusObject } from '../../../../../shared/object-list/access-status-badge/access-status.model'; +import { AccessStatusObject } from '../../../../../shared/object-collection/shared/badges/access-status-badge/access-status.model'; import { AuthService } from '../../../../../core/auth/auth.service'; import { AuthServiceStub } from '../../../../../shared/testing/auth-service.stub'; import { FileService } from '../../../../../core/shared/file.service'; diff --git a/src/app/admin/admin-search-page/admin-search-results/admin-search-result-grid-element/item-search-result/item-admin-search-result-grid-element.component.ts b/src/app/admin/admin-search-page/admin-search-results/admin-search-result-grid-element/item-search-result/item-admin-search-result-grid-element.component.ts index 1ab8fee8c2..dab6694f36 100644 --- a/src/app/admin/admin-search-page/admin-search-results/admin-search-result-grid-element/item-search-result/item-admin-search-result-grid-element.component.ts +++ b/src/app/admin/admin-search-page/admin-search-results/admin-search-result-grid-element/item-search-result/item-admin-search-result-grid-element.component.ts @@ -13,6 +13,7 @@ import { BitstreamDataService } from '../../../../../core/data/bitstream-data.se import { GenericConstructor } from '../../../../../core/shared/generic-constructor'; import { ListableObjectDirective } from '../../../../../shared/object-collection/shared/listable-object/listable-object.directive'; import { ThemeService } from '../../../../../shared/theme-support/theme.service'; +import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service'; @listableObjectComponent(ItemSearchResult, ViewMode.GridElement, Context.AdminSearch) @Component({ @@ -28,12 +29,14 @@ export class ItemAdminSearchResultGridElementComponent extends SearchResultGridE @ViewChild('badges', { static: true }) badges: ElementRef; @ViewChild('buttons', { static: true }) buttons: ElementRef; - constructor(protected truncatableService: TruncatableService, - protected bitstreamDataService: BitstreamDataService, - private themeService: ThemeService, - private componentFactoryResolver: ComponentFactoryResolver + constructor( + public dsoNameService: DSONameService, + protected truncatableService: TruncatableService, + protected bitstreamDataService: BitstreamDataService, + private themeService: ThemeService, + private componentFactoryResolver: ComponentFactoryResolver, ) { - super(truncatableService, bitstreamDataService); + super(dsoNameService, truncatableService, bitstreamDataService); } /** diff --git a/src/app/admin/admin-search-page/admin-search-results/admin-search-result-list-element/item-search-result/item-admin-search-result-list-element.component.html b/src/app/admin/admin-search-page/admin-search-results/admin-search-result-list-element/item-search-result/item-admin-search-result-list-element.component.html index 259512552c..991508335f 100644 --- a/src/app/admin/admin-search-page/admin-search-results/admin-search-result-list-element/item-search-result/item-admin-search-result-list-element.component.html +++ b/src/app/admin/admin-search-page/admin-search-results/admin-search-result-list-element/item-search-result/item-admin-search-result-list-element.component.html @@ -2,6 +2,5 @@ [viewMode]="viewModes.ListElement" [index]="index" [linkType]="linkType" - [listID]="listID" - [hideBadges]="true"> + [listID]="listID"> diff --git a/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/supervision-order-group-selector/supervision-order-group-selector.component.ts b/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/supervision-order-group-selector/supervision-order-group-selector.component.ts index bbb1df3c49..2eec0cfd0c 100644 --- a/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/supervision-order-group-selector/supervision-order-group-selector.component.ts +++ b/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/supervision-order-group-selector/supervision-order-group-selector.component.ts @@ -82,7 +82,7 @@ export class SupervisionOrderGroupSelectorComponent { getFirstCompletedRemoteData(), ).subscribe((rd: RemoteData) => { if (rd.state === 'Success') { - this.notificationsService.success(this.translateService.get('supervision-group-selector.notification.create.success.title', { name: this.selectedGroup.name })); + this.notificationsService.success(this.translateService.get('supervision-group-selector.notification.create.success.title', { name: this.dsoNameService.getName(this.selectedGroup) })); this.create.emit(rd.payload); this.close(); } else { diff --git a/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/supervision-order-status/supervision-order-status.component.html b/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/supervision-order-status/supervision-order-status.component.html index fa6a2eafff..84d8c052cd 100644 --- a/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/supervision-order-status/supervision-order-status.component.html +++ b/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/supervision-order-status/supervision-order-status.component.html @@ -7,7 +7,7 @@ - {{supervisionOrder.group.name}} + {{ dsoNameService.getName(supervisionOrder.group) }}
diff --git a/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/supervision-order-status/supervision-order-status.component.ts b/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/supervision-order-status/supervision-order-status.component.ts index 11b6400ffd..93c6441e92 100644 --- a/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/supervision-order-status/supervision-order-status.component.ts +++ b/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/supervision-order-status/supervision-order-status.component.ts @@ -8,6 +8,7 @@ import { Group } from '../../../../../../core/eperson/models/group.model'; import { getFirstCompletedRemoteData } from '../../../../../../core/shared/operators'; import { isNotEmpty } from '../../../../../../shared/empty.util'; import { RemoteData } from '../../../../../../core/data/remote-data'; +import { DSONameService } from '../../../../../../core/breadcrumbs/dso-name.service'; export interface SupervisionOrderListEntry { supervisionOrder: SupervisionOrder; @@ -33,6 +34,11 @@ export class SupervisionOrderStatusComponent implements OnChanges { @Output() delete: EventEmitter = new EventEmitter(); + constructor( + public dsoNameService: DSONameService, + ) { + } + ngOnChanges(changes: SimpleChanges): void { if (changes && changes.supervisionOrderList) { this.getSupervisionOrderEntries(changes.supervisionOrderList.currentValue) diff --git a/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/workspace-item-admin-workflow-actions.component.spec.ts b/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/workspace-item-admin-workflow-actions.component.spec.ts index 628fc3f89c..a8f0581ec0 100644 --- a/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/workspace-item-admin-workflow-actions.component.spec.ts +++ b/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/workspace-item-admin-workflow-actions.component.spec.ts @@ -11,7 +11,7 @@ import { URLCombiner } from '../../../../../core/url-combiner/url-combiner'; import { WorkspaceItemAdminWorkflowActionsComponent } from './workspace-item-admin-workflow-actions.component'; import { WorkspaceItem } from '../../../../../core/submission/models/workspaceitem.model'; import { - getWorkflowItemDeleteRoute, + getWorkspaceItemDeleteRoute, } from '../../../../../workflowitems-edit-page/workflowitems-edit-page-routing-paths'; import { Item } from '../../../../../core/shared/item.model'; import { RemoteData } from '../../../../../core/data/remote-data'; @@ -83,7 +83,7 @@ describe('WorkspaceItemAdminWorkflowActionsComponent', () => { it('should render a delete button with the correct link', () => { const button = fixture.debugElement.query(By.css('a.delete-link')); const link = button.nativeElement.href; - expect(link).toContain(new URLCombiner(getWorkflowItemDeleteRoute(wsi.id)).toString()); + expect(link).toContain(new URLCombiner(getWorkspaceItemDeleteRoute(wsi.id)).toString()); }); it('should render a policies button with the correct link', () => { diff --git a/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/workspace-item-admin-workflow-actions.component.ts b/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/workspace-item-admin-workflow-actions.component.ts index adbd421628..36678460da 100644 --- a/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/workspace-item-admin-workflow-actions.component.ts +++ b/src/app/admin/admin-workflow-page/admin-workflow-search-results/actions/workspace-item/workspace-item-admin-workflow-actions.component.ts @@ -11,7 +11,7 @@ import { SupervisionOrderGroupSelectorComponent } from './supervision-order-group-selector/supervision-order-group-selector.component'; import { - getWorkflowItemDeleteRoute + getWorkspaceItemDeleteRoute } from '../../../../../workflowitems-edit-page/workflowitems-edit-page-routing-paths'; import { ITEM_EDIT_AUTHORIZATIONS_PATH } from '../../../../../item-page/edit-item-page/edit-item-page.routing-paths'; import { WorkspaceItem } from '../../../../../core/submission/models/workspaceitem.model'; @@ -105,10 +105,10 @@ export class WorkspaceItemAdminWorkflowActionsComponent implements OnInit { } /** - * Returns the path to the delete page of this workflow item + * Returns the path to the delete page of this workspace item */ getDeleteRoute(): string { - return getWorkflowItemDeleteRoute(this.wsi.id); + return getWorkspaceItemDeleteRoute(this.wsi.id); } /** diff --git a/src/app/admin/admin-workflow-page/admin-workflow-search-results/admin-workflow-search-result-grid-element/workflow-item/workflow-item-search-result-admin-workflow-grid-element.component.ts b/src/app/admin/admin-workflow-page/admin-workflow-search-results/admin-workflow-search-result-grid-element/workflow-item/workflow-item-search-result-admin-workflow-grid-element.component.ts index 68f10916d5..fd9d21e227 100644 --- a/src/app/admin/admin-workflow-page/admin-workflow-search-results/admin-workflow-search-result-grid-element/workflow-item/workflow-item-search-result-admin-workflow-grid-element.component.ts +++ b/src/app/admin/admin-workflow-page/admin-workflow-search-results/admin-workflow-search-result-grid-element/workflow-item/workflow-item-search-result-admin-workflow-grid-element.component.ts @@ -23,6 +23,7 @@ import { import { take } from 'rxjs/operators'; import { WorkflowItemSearchResult } from '../../../../../shared/object-collection/shared/workflow-item-search-result.model'; import { ThemeService } from '../../../../../shared/theme-support/theme.service'; +import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service'; @listableObjectComponent(WorkflowItemSearchResult, ViewMode.GridElement, Context.AdminWorkflowSearch) @Component({ @@ -55,13 +56,14 @@ export class WorkflowItemSearchResultAdminWorkflowGridElementComponent extends S public item$: Observable; constructor( + public dsoNameService: DSONameService, private componentFactoryResolver: ComponentFactoryResolver, private linkService: LinkService, protected truncatableService: TruncatableService, private themeService: ThemeService, protected bitstreamDataService: BitstreamDataService ) { - super(truncatableService, bitstreamDataService); + super(dsoNameService, truncatableService, bitstreamDataService); } /** diff --git a/src/app/admin/admin-workflow-page/admin-workflow-search-results/admin-workflow-search-result-grid-element/workspace-item/workspace-item-search-result-admin-workflow-grid-element.component.ts b/src/app/admin/admin-workflow-page/admin-workflow-search-results/admin-workflow-search-result-grid-element/workspace-item/workspace-item-search-result-admin-workflow-grid-element.component.ts index f18c18ca1c..d6f39e79fe 100644 --- a/src/app/admin/admin-workflow-page/admin-workflow-search-results/admin-workflow-search-result-grid-element/workspace-item/workspace-item-search-result-admin-workflow-grid-element.component.ts +++ b/src/app/admin/admin-workflow-page/admin-workflow-search-results/admin-workflow-search-result-grid-element/workspace-item/workspace-item-search-result-admin-workflow-grid-element.component.ts @@ -1,4 +1,4 @@ -import { Component, ComponentFactoryResolver, ElementRef, ViewChild } from '@angular/core'; +import { Component, ComponentFactoryResolver, ElementRef, ViewChild, OnInit } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { map, mergeMap, take, tap } from 'rxjs/operators'; @@ -36,6 +36,7 @@ import { DSpaceObject } from '../../../../../core/shared/dspace-object.model'; import { SupervisionOrder } from '../../../../../core/supervision-order/models/supervision-order.model'; import { PaginatedList } from '../../../../../core/data/paginated-list.model'; import { SupervisionOrderDataService } from '../../../../../core/supervision-order/supervision-order-data.service'; +import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service'; @listableObjectComponent(WorkspaceItemSearchResult, ViewMode.GridElement, Context.AdminWorkflowSearch) @Component({ @@ -46,7 +47,7 @@ import { SupervisionOrderDataService } from '../../../../../core/supervision-ord /** * The component for displaying a grid element for an workflow item on the admin workflow search page */ -export class WorkspaceItemSearchResultAdminWorkflowGridElementComponent extends SearchResultGridElementComponent { +export class WorkspaceItemSearchResultAdminWorkflowGridElementComponent extends SearchResultGridElementComponent implements OnInit { /** * The item linked to the workspace item @@ -79,6 +80,7 @@ export class WorkspaceItemSearchResultAdminWorkflowGridElementComponent extends @ViewChild('buttons', { static: true }) buttons: ElementRef; constructor( + public dsoNameService: DSONameService, private componentFactoryResolver: ComponentFactoryResolver, private linkService: LinkService, protected truncatableService: TruncatableService, @@ -86,7 +88,7 @@ export class WorkspaceItemSearchResultAdminWorkflowGridElementComponent extends protected bitstreamDataService: BitstreamDataService, protected supervisionOrderDataService: SupervisionOrderDataService, ) { - super(truncatableService, bitstreamDataService); + super(dsoNameService, truncatableService, bitstreamDataService); } /** diff --git a/src/app/admin/admin-workflow-page/admin-workflow-search-results/admin-workflow-search-result-list-element/workflow-item/workflow-item-search-result-admin-workflow-list-element.component.ts b/src/app/admin/admin-workflow-page/admin-workflow-search-results/admin-workflow-search-result-list-element/workflow-item/workflow-item-search-result-admin-workflow-list-element.component.ts index b1db3f99ce..d0e773d696 100644 --- a/src/app/admin/admin-workflow-page/admin-workflow-search-results/admin-workflow-search-result-list-element/workflow-item/workflow-item-search-result-admin-workflow-list-element.component.ts +++ b/src/app/admin/admin-workflow-page/admin-workflow-search-results/admin-workflow-search-result-list-element/workflow-item/workflow-item-search-result-admin-workflow-list-element.component.ts @@ -39,7 +39,7 @@ export class WorkflowItemSearchResultAdminWorkflowListElementComponent extends S constructor(private linkService: LinkService, protected truncatableService: TruncatableService, - protected dsoNameService: DSONameService, + public dsoNameService: DSONameService, @Inject(APP_CONFIG) protected appConfig: AppConfig ) { super(truncatableService, dsoNameService, appConfig); diff --git a/src/app/admin/admin-workflow-page/admin-workflow-search-results/admin-workflow-search-result-list-element/workspace-item/workspace-item-search-result-admin-workflow-list-element.component.ts b/src/app/admin/admin-workflow-page/admin-workflow-search-results/admin-workflow-search-result-list-element/workspace-item/workspace-item-search-result-admin-workflow-list-element.component.ts index 597ed8bbe7..3d6d1c8e44 100644 --- a/src/app/admin/admin-workflow-page/admin-workflow-search-results/admin-workflow-search-result-list-element/workspace-item/workspace-item-search-result-admin-workflow-list-element.component.ts +++ b/src/app/admin/admin-workflow-page/admin-workflow-search-results/admin-workflow-search-result-list-element/workspace-item/workspace-item-search-result-admin-workflow-list-element.component.ts @@ -59,7 +59,7 @@ export class WorkspaceItemSearchResultAdminWorkflowListElementComponent extends public supervisionOrder$: BehaviorSubject = new BehaviorSubject([]); constructor(private linkService: LinkService, - protected dsoNameService: DSONameService, + public dsoNameService: DSONameService, protected supervisionOrderDataService: SupervisionOrderDataService, protected truncatableService: TruncatableService, @Inject(APP_CONFIG) protected appConfig: AppConfig diff --git a/src/app/admin/admin.module.ts b/src/app/admin/admin.module.ts index dff2e506c3..3dc0036854 100644 --- a/src/app/admin/admin.module.ts +++ b/src/app/admin/admin.module.ts @@ -10,6 +10,7 @@ import { AdminSearchModule } from './admin-search-page/admin-search.module'; import { AdminSidebarSectionComponent } from './admin-sidebar/admin-sidebar-section/admin-sidebar-section.component'; import { ExpandableAdminSidebarSectionComponent } from './admin-sidebar/expandable-admin-sidebar-section/expandable-admin-sidebar-section.component'; import { BatchImportPageComponent } from './admin-import-batch-page/batch-import-page.component'; +import { UiSwitchModule } from 'ngx-ui-switch'; import { UploadModule } from '../shared/upload/upload.module'; const ENTRY_COMPONENTS = [ @@ -27,6 +28,7 @@ const ENTRY_COMPONENTS = [ AdminSearchModule.withEntryComponents(), AdminWorkflowModuleModule.withEntryComponents(), SharedModule, + UiSwitchModule, UploadModule, ], declarations: [ diff --git a/src/app/app-routing.module.ts b/src/app/app-routing.module.ts index b69e47c82c..9cbd246f0b 100644 --- a/src/app/app-routing.module.ts +++ b/src/app/app-routing.module.ts @@ -38,6 +38,7 @@ import { ThemedPageInternalServerErrorComponent } from './page-internal-server-error/themed-page-internal-server-error.component'; import { ServerCheckGuard } from './core/server-check/server-check.guard'; +import { SUGGESTION_MODULE_PATH } from './suggestions-page/suggestions-page-routing-paths'; import { MenuResolver } from './menu.resolver'; import { ThemedPageErrorComponent } from './page-error/themed-page-error.component'; @@ -202,6 +203,11 @@ import { ThemedPageErrorComponent } from './page-error/themed-page-error.compone .then((m) => m.ProcessPageModule), canActivate: [AuthenticatedGuard, EndUserAgreementCurrentUserGuard] }, + { path: SUGGESTION_MODULE_PATH, + loadChildren: () => import('./suggestions-page/suggestions-page.module') + .then((m) => m.SuggestionsPageModule), + canActivate: [AuthenticatedGuard, EndUserAgreementCurrentUserGuard] + }, { path: INFO_MODULE_PATH, loadChildren: () => import('./info/info.module').then((m) => m.InfoModule) @@ -209,7 +215,7 @@ import { ThemedPageErrorComponent } from './page-error/themed-page-error.compone { path: REQUEST_COPY_MODULE_PATH, loadChildren: () => import('./request-copy/request-copy.module').then((m) => m.RequestCopyModule), - canActivate: [AuthenticatedGuard, EndUserAgreementCurrentUserGuard] + canActivate: [EndUserAgreementCurrentUserGuard] }, { path: FORBIDDEN_PATH, diff --git a/src/app/bitstream-page/bitstream-download-page/bitstream-download-page.component.html b/src/app/bitstream-page/bitstream-download-page/bitstream-download-page.component.html index eddc5e345a..af3afe98f8 100644 --- a/src/app/bitstream-page/bitstream-download-page/bitstream-download-page.component.html +++ b/src/app/bitstream-page/bitstream-download-page/bitstream-download-page.component.html @@ -1,5 +1,5 @@
-

{{'bitstream.download.page' | translate:{bitstream: (bitstream$ | async)?.name} }}

+

{{'bitstream.download.page' | translate:{ bitstream: dsoNameService.getName((bitstream$ | async)) } }}

diff --git a/src/app/collection-page/edit-item-template-page/edit-item-template-page.component.ts b/src/app/collection-page/edit-item-template-page/edit-item-template-page.component.ts index 5d29eb7f73..6425996fd2 100644 --- a/src/app/collection-page/edit-item-template-page/edit-item-template-page.component.ts +++ b/src/app/collection-page/edit-item-template-page/edit-item-template-page.component.ts @@ -9,6 +9,7 @@ import { getCollectionEditRoute } from '../collection-page-routing-paths'; import { Item } from '../../core/shared/item.model'; import { getFirstSucceededRemoteDataPayload } from '../../core/shared/operators'; import { AlertType } from '../../shared/alert/aletr-type'; +import { DSONameService } from '../../core/breadcrumbs/dso-name.service'; @Component({ selector: 'ds-edit-item-template-page', @@ -35,8 +36,11 @@ export class EditItemTemplatePageComponent implements OnInit { */ AlertTypeEnum = AlertType; - constructor(protected route: ActivatedRoute, - public itemTemplateService: ItemTemplateDataService) { + constructor( + protected route: ActivatedRoute, + public itemTemplateService: ItemTemplateDataService, + public dsoNameService: DSONameService, + ) { } ngOnInit(): void { diff --git a/src/app/collection-page/edit-item-template-page/item-template-page.resolver.spec.ts b/src/app/collection-page/edit-item-template-page/item-template-page.resolver.spec.ts index 2712a194c0..95f0d888e4 100644 --- a/src/app/collection-page/edit-item-template-page/item-template-page.resolver.spec.ts +++ b/src/app/collection-page/edit-item-template-page/item-template-page.resolver.spec.ts @@ -2,18 +2,22 @@ import { first } from 'rxjs/operators'; import { ItemTemplatePageResolver } from './item-template-page.resolver'; import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils'; +import { DSONameService } from '../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../shared/mocks/dso-name.service.mock'; describe('ItemTemplatePageResolver', () => { describe('resolve', () => { let resolver: ItemTemplatePageResolver; let itemTemplateService: any; + let dsoNameService: DSONameServiceMock; const uuid = '1234-65487-12354-1235'; beforeEach(() => { itemTemplateService = { findByCollectionID: (id: string) => createSuccessfulRemoteDataObject$({ id }) }; - resolver = new ItemTemplatePageResolver(itemTemplateService); + dsoNameService = new DSONameServiceMock(); + resolver = new ItemTemplatePageResolver(dsoNameService as DSONameService, itemTemplateService); }); it('should resolve an item template with the correct id', (done) => { diff --git a/src/app/collection-page/edit-item-template-page/item-template-page.resolver.ts b/src/app/collection-page/edit-item-template-page/item-template-page.resolver.ts index 719a04196f..586617c44c 100644 --- a/src/app/collection-page/edit-item-template-page/item-template-page.resolver.ts +++ b/src/app/collection-page/edit-item-template-page/item-template-page.resolver.ts @@ -6,13 +6,17 @@ import { ItemTemplateDataService } from '../../core/data/item-template-data.serv import { Observable } from 'rxjs'; import { followLink } from '../../shared/utils/follow-link-config.model'; import { getFirstCompletedRemoteData } from '../../core/shared/operators'; +import { DSONameService } from '../../core/breadcrumbs/dso-name.service'; /** * This class represents a resolver that requests a specific collection's item template before the route is activated */ @Injectable() export class ItemTemplatePageResolver implements Resolve> { - constructor(private itemTemplateService: ItemTemplateDataService) { + constructor( + public dsoNameService: DSONameService, + private itemTemplateService: ItemTemplateDataService, + ) { } /** diff --git a/src/app/community-list-page/community-list/community-list.component.html b/src/app/community-list-page/community-list/community-list.component.html index ea772bb891..d6fd77e79b 100644 --- a/src/app/community-list-page/community-list/community-list.component.html +++ b/src/app/community-list-page/community-list/community-list.component.html @@ -8,10 +8,10 @@
@@ -25,19 +25,23 @@ class="example-tree-node expandable-node">
-
- - {{node.name}} - -
+
+
+ + {{ dsoNameService.getName(node.payload) }} + +   + {{node.payload.archivedItemsCount}} +
+
@@ -66,12 +70,11 @@ class="example-tree-node childless-node"> diff --git a/src/app/community-list-page/community-list/community-list.component.spec.ts b/src/app/community-list-page/community-list/community-list.component.spec.ts index 575edf14e8..ce6b27dbeb 100644 --- a/src/app/community-list-page/community-list/community-list.component.spec.ts +++ b/src/app/community-list-page/community-list/community-list.component.spec.ts @@ -16,6 +16,7 @@ import { of as observableOf } from 'rxjs'; import { By } from '@angular/platform-browser'; import { isEmpty, isNotEmpty } from '../../shared/empty.util'; import { FlatNode } from '../flat-node.model'; +import { RouterLinkWithHref } from '@angular/router'; describe('CommunityListComponent', () => { let component: CommunityListComponent; @@ -193,7 +194,8 @@ describe('CommunityListComponent', () => { }, }), CdkTreeModule, - RouterTestingModule], + RouterTestingModule, + RouterLinkWithHref], declarations: [CommunityListComponent], providers: [CommunityListComponent, { provide: CommunityListService, useValue: communityListServiceStub },], @@ -230,9 +232,14 @@ describe('CommunityListComponent', () => { expect(showMoreEl).toBeTruthy(); }); + it('should not render the show more button as an empty link', () => { + const debugElements = fixture.debugElement.queryAll(By.directive(RouterLinkWithHref)); + expect(debugElements).toBeTruthy(); + }); + describe('when show more of top communities is clicked', () => { beforeEach(fakeAsync(() => { - const showMoreLink = fixture.debugElement.query(By.css('.show-more-node a')); + const showMoreLink = fixture.debugElement.query(By.css('.show-more-node .btn-outline-primary')); showMoreLink.triggerEventHandler('click', { preventDefault: () => {/**/ } @@ -240,6 +247,7 @@ describe('CommunityListComponent', () => { tick(); fixture.detectChanges(); })); + it('tree contains maximum of currentPage (2) * (2) elementsPerPage of first top communities, or less if there are less communities (3)', () => { const expandableNodesFound = fixture.debugElement.queryAll(By.css('.expandable-node a')); const childlessNodesFound = fixture.debugElement.queryAll(By.css('.childless-node a')); diff --git a/src/app/community-list-page/community-list/community-list.component.ts b/src/app/community-list-page/community-list/community-list.component.ts index 556387da25..5b2f930813 100644 --- a/src/app/community-list-page/community-list/community-list.component.ts +++ b/src/app/community-list-page/community-list/community-list.component.ts @@ -7,6 +7,7 @@ import { FlatTreeControl } from '@angular/cdk/tree'; import { isEmpty } from '../../shared/empty.util'; import { FlatNode } from '../flat-node.model'; import { FindListOptions } from '../../core/data/find-list-options.model'; +import { DSONameService } from '../../core/breadcrumbs/dso-name.service'; /** * A tree-structured list of nodes representing the communities, their subCommunities and collections. @@ -32,7 +33,10 @@ export class CommunityListComponent implements OnInit, OnDestroy { paginationConfig: FindListOptions; - constructor(private communityListService: CommunityListService) { + constructor( + protected communityListService: CommunityListService, + public dsoNameService: DSONameService, + ) { this.paginationConfig = new FindListOptions(); this.paginationConfig.elementsPerPage = 2; this.paginationConfig.currentPage = 1; diff --git a/src/app/community-page/community-form/community-form.component.ts b/src/app/community-page/community-form/community-form.component.ts index c6dd1147c3..fa4809738d 100644 --- a/src/app/community-page/community-form/community-form.component.ts +++ b/src/app/community-page/community-form/community-form.component.ts @@ -1,4 +1,4 @@ -import { Component, Input } from '@angular/core'; +import { Component, Input, OnChanges, SimpleChange, SimpleChanges } from '@angular/core'; import { DynamicFormControlModel, DynamicFormService, @@ -23,7 +23,7 @@ import { environment } from '../../../environments/environment'; styleUrls: ['../../shared/comcol/comcol-forms/comcol-form/comcol-form.component.scss'], templateUrl: '../../shared/comcol/comcol-forms/comcol-form/comcol-form.component.html' }) -export class CommunityFormComponent extends ComColFormComponent { +export class CommunityFormComponent extends ComColFormComponent implements OnChanges { /** * @type {Community} A new community when a community is being created, an existing Input community when a community is being edited */ @@ -81,4 +81,11 @@ export class CommunityFormComponent extends ComColFormComponent { protected objectCache: ObjectCacheService) { super(formService, translate, notificationsService, authService, requestService, objectCache); } + + ngOnChanges(changes: SimpleChanges) { + const dsoChange: SimpleChange = changes.dso; + if (this.dso && dsoChange && !dsoChange.isFirstChange()) { + super.ngOnInit(); + } + } } diff --git a/src/app/community-page/community-page.component.html b/src/app/community-page/community-page.component.html index 8e06fd2db3..6d5262d933 100644 --- a/src/app/community-page/community-page.component.html +++ b/src/app/community-page/community-page.component.html @@ -5,7 +5,7 @@
- + diff --git a/src/app/community-page/community-page.component.ts b/src/app/community-page/community-page.component.ts index b1a0cfc946..a5bbff3cee 100644 --- a/src/app/community-page/community-page.component.ts +++ b/src/app/community-page/community-page.component.ts @@ -19,6 +19,7 @@ import { AuthorizationDataService } from '../core/data/feature-authorization/aut import { FeatureID } from '../core/data/feature-authorization/feature-id'; import { getCommunityPageRoute } from './community-page-routing-paths'; import { redirectOn4xx } from '../core/shared/authorized.operators'; +import { DSONameService } from '../core/breadcrumbs/dso-name.service'; @Component({ selector: 'ds-community-page', @@ -57,7 +58,8 @@ export class CommunityPageComponent implements OnInit { private route: ActivatedRoute, private router: Router, private authService: AuthService, - private authorizationDataService: AuthorizationDataService + private authorizationDataService: AuthorizationDataService, + public dsoNameService: DSONameService, ) { } diff --git a/src/app/community-page/create-community-page/create-community-page.component.html b/src/app/community-page/create-community-page/create-community-page.component.html index 71a580b0aa..57039040c2 100644 --- a/src/app/community-page/create-community-page/create-community-page.component.html +++ b/src/app/community-page/create-community-page/create-community-page.component.html @@ -3,7 +3,7 @@
-

{{ 'community.create.sub-head' | translate:{ parent: parent.name } }}

+

{{ 'community.create.sub-head' | translate:{ parent: dsoNameService.getName(parent) } }}

diff --git a/src/app/community-page/create-community-page/create-community-page.component.ts b/src/app/community-page/create-community-page/create-community-page.component.ts index b332fad100..eea0908388 100644 --- a/src/app/community-page/create-community-page/create-community-page.component.ts +++ b/src/app/community-page/create-community-page/create-community-page.component.ts @@ -7,6 +7,7 @@ import { CreateComColPageComponent } from '../../shared/comcol/comcol-forms/crea import { NotificationsService } from '../../shared/notifications/notifications.service'; import { TranslateService } from '@ngx-translate/core'; import { RequestService } from '../../core/data/request.service'; +import { DSONameService } from '../../core/breadcrumbs/dso-name.service'; /** * Component that represents the page where a user can create a new Community @@ -22,12 +23,13 @@ export class CreateCommunityPageComponent extends CreateComColPageComponent
-

{{ 'community.delete.text' | translate:{ dso: dso.name } }}

+

{{ 'community.delete.text' | translate:{ dso: dsoNameService.getName(dso) } }}

diff --git a/src/app/dso-shared/dso-edit-metadata/dso-edit-metadata-value/dso-edit-metadata-value.component.spec.ts b/src/app/dso-shared/dso-edit-metadata/dso-edit-metadata-value/dso-edit-metadata-value.component.spec.ts index 10b3016a52..67a6f98ac0 100644 --- a/src/app/dso-shared/dso-edit-metadata/dso-edit-metadata-value/dso-edit-metadata-value.component.spec.ts +++ b/src/app/dso-shared/dso-edit-metadata/dso-edit-metadata-value/dso-edit-metadata-value.component.spec.ts @@ -68,7 +68,7 @@ describe('DsoEditMetadataValueComponent', () => { }); it('should not show a badge', () => { - expect(fixture.debugElement.query(By.css('ds-type-badge'))).toBeNull(); + expect(fixture.debugElement.query(By.css('ds-themed-type-badge'))).toBeNull(); }); describe('when no changes have been made', () => { @@ -134,7 +134,7 @@ describe('DsoEditMetadataValueComponent', () => { }); it('should show a badge', () => { - expect(fixture.debugElement.query(By.css('ds-type-badge'))).toBeTruthy(); + expect(fixture.debugElement.query(By.css('ds-themed-type-badge'))).toBeTruthy(); }); assertButton(EDIT_BTN, true, true); diff --git a/src/app/dso-shared/dso-edit-metadata/metadata-field-selector/metadata-field-selector.component.spec.ts b/src/app/dso-shared/dso-edit-metadata/metadata-field-selector/metadata-field-selector.component.spec.ts index e0fde0e8f2..de8736df94 100644 --- a/src/app/dso-shared/dso-edit-metadata/metadata-field-selector/metadata-field-selector.component.spec.ts +++ b/src/app/dso-shared/dso-edit-metadata/metadata-field-selector/metadata-field-selector.component.spec.ts @@ -12,6 +12,7 @@ import { createPaginatedList } from '../../../shared/testing/utils.test'; import { followLink } from '../../../shared/utils/follow-link-config.model'; import { By } from '@angular/platform-browser'; import { NotificationsService } from '../../../shared/notifications/notifications.service'; +import { SortDirection, SortOptions } from '../../../core/cache/models/sort-options.model'; describe('MetadataFieldSelectorComponent', () => { let component: MetadataFieldSelectorComponent; @@ -79,7 +80,7 @@ describe('MetadataFieldSelectorComponent', () => { }); it('should query the registry service for metadata fields and include the schema', () => { - expect(registryService.queryMetadataFields).toHaveBeenCalledWith(query, null, true, false, followLink('schema')); + expect(registryService.queryMetadataFields).toHaveBeenCalledWith(query, { elementsPerPage: 10, sort: new SortOptions('fieldName', SortDirection.ASC) }, true, false, followLink('schema')); }); }); diff --git a/src/app/dso-shared/dso-edit-metadata/metadata-field-selector/metadata-field-selector.component.ts b/src/app/dso-shared/dso-edit-metadata/metadata-field-selector/metadata-field-selector.component.ts index 5053a4b83d..fc0d57046d 100644 --- a/src/app/dso-shared/dso-edit-metadata/metadata-field-selector/metadata-field-selector.component.ts +++ b/src/app/dso-shared/dso-edit-metadata/metadata-field-selector/metadata-field-selector.component.ts @@ -9,21 +9,23 @@ import { Output, ViewChild } from '@angular/core'; -import { switchMap, debounceTime, distinctUntilChanged, map, tap, take } from 'rxjs/operators'; +import { debounceTime, distinctUntilChanged, map, switchMap, take, tap } from 'rxjs/operators'; import { followLink } from '../../../shared/utils/follow-link-config.model'; import { - getAllSucceededRemoteData, getFirstCompletedRemoteData, + getAllSucceededRemoteData, + getFirstCompletedRemoteData, metadataFieldsToString } from '../../../core/shared/operators'; import { Observable } from 'rxjs/internal/Observable'; import { RegistryService } from '../../../core/registry/registry.service'; -import { FormControl } from '@angular/forms'; +import { UntypedFormControl } from '@angular/forms'; import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject'; import { hasValue } from '../../../shared/empty.util'; import { Subscription } from 'rxjs/internal/Subscription'; import { of } from 'rxjs/internal/observable/of'; import { NotificationsService } from '../../../shared/notifications/notifications.service'; import { TranslateService } from '@ngx-translate/core'; +import { SortDirection, SortOptions } from '../../../core/cache/models/sort-options.model'; @Component({ selector: 'ds-metadata-field-selector', @@ -70,7 +72,7 @@ export class MetadataFieldSelectorComponent implements OnInit, OnDestroy, AfterV /** * FormControl for the input */ - public input: FormControl = new FormControl(); + public input: UntypedFormControl = new UntypedFormControl(); /** * The current query to update mdFieldOptions$ for @@ -127,7 +129,7 @@ export class MetadataFieldSelectorComponent implements OnInit, OnDestroy, AfterV switchMap((query: string) => { this.showInvalid = false; if (query !== null) { - return this.registryService.queryMetadataFields(query, null, true, false, followLink('schema')).pipe( + return this.registryService.queryMetadataFields(query, { elementsPerPage: 10, sort: new SortOptions('fieldName', SortDirection.ASC) }, true, false, followLink('schema')).pipe( getAllSucceededRemoteData(), metadataFieldsToString(), ); diff --git a/src/app/entity-groups/journal-entities/item-grid-elements/journal-issue/journal-issue-grid-element.component.spec.ts b/src/app/entity-groups/journal-entities/item-grid-elements/journal-issue/journal-issue-grid-element.component.spec.ts index df9e8ea7fd..6c55616760 100644 --- a/src/app/entity-groups/journal-entities/item-grid-elements/journal-issue/journal-issue-grid-element.component.spec.ts +++ b/src/app/entity-groups/journal-entities/item-grid-elements/journal-issue/journal-issue-grid-element.component.spec.ts @@ -10,6 +10,8 @@ import { TruncatePipe } from '../../../../shared/utils/truncate.pipe'; import { TruncatableService } from '../../../../shared/truncatable/truncatable.service'; import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; import { By } from '@angular/platform-browser'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../../../shared/mocks/dso-name.service.mock'; const mockItem = Object.assign(new Item(), { bundles: createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), [])), @@ -48,6 +50,7 @@ describe('JournalIssueGridElementComponent', () => { imports: [NoopAnimationsModule], declarations: [JournalIssueGridElementComponent, TruncatePipe], providers: [ + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: TruncatableService, useValue: truncatableServiceStub }, ], schemas: [NO_ERRORS_SCHEMA] diff --git a/src/app/entity-groups/journal-entities/item-grid-elements/journal-volume/journal-volume-grid-element.component.spec.ts b/src/app/entity-groups/journal-entities/item-grid-elements/journal-volume/journal-volume-grid-element.component.spec.ts index ac082e7f1b..14f63d5781 100644 --- a/src/app/entity-groups/journal-entities/item-grid-elements/journal-volume/journal-volume-grid-element.component.spec.ts +++ b/src/app/entity-groups/journal-entities/item-grid-elements/journal-volume/journal-volume-grid-element.component.spec.ts @@ -10,6 +10,8 @@ import { TruncatePipe } from '../../../../shared/utils/truncate.pipe'; import { TruncatableService } from '../../../../shared/truncatable/truncatable.service'; import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; import { By } from '@angular/platform-browser'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../../../shared/mocks/dso-name.service.mock'; const mockItem = Object.assign(new Item(), { bundles: createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), [])), @@ -48,6 +50,7 @@ describe('JournalVolumeGridElementComponent', () => { imports: [NoopAnimationsModule], declarations: [JournalVolumeGridElementComponent, TruncatePipe], providers: [ + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: TruncatableService, useValue: truncatableServiceStub }, ], schemas: [NO_ERRORS_SCHEMA] diff --git a/src/app/entity-groups/journal-entities/item-grid-elements/journal/journal-grid-element.component.spec.ts b/src/app/entity-groups/journal-entities/item-grid-elements/journal/journal-grid-element.component.spec.ts index 93287313aa..e4a2375441 100644 --- a/src/app/entity-groups/journal-entities/item-grid-elements/journal/journal-grid-element.component.spec.ts +++ b/src/app/entity-groups/journal-entities/item-grid-elements/journal/journal-grid-element.component.spec.ts @@ -10,6 +10,8 @@ import { TruncatePipe } from '../../../../shared/utils/truncate.pipe'; import { TruncatableService } from '../../../../shared/truncatable/truncatable.service'; import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; import { By } from '@angular/platform-browser'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../../../shared/mocks/dso-name.service.mock'; const mockItem = Object.assign(new Item(), { bundles: createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), [])), @@ -54,6 +56,7 @@ describe('JournalGridElementComponent', () => { imports: [NoopAnimationsModule], declarations: [JournalGridElementComponent, TruncatePipe], providers: [ + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: TruncatableService, useValue: truncatableServiceStub }, ], schemas: [NO_ERRORS_SCHEMA] diff --git a/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal-issue/journal-issue-search-result-grid-element.component.html b/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal-issue/journal-issue-search-result-grid-element.component.html index c6c29c2f1a..13c5286e71 100644 --- a/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal-issue/journal-issue-search-result-grid-element.component.html +++ b/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal-issue/journal-issue-search-result-grid-element.component.html @@ -5,21 +5,21 @@
- - + +
- - + +
diff --git a/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal-volume/journal-volume-search-result-grid-element.component.html b/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal-volume/journal-volume-search-result-grid-element.component.html index 5849105f96..c64da0b632 100644 --- a/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal-volume/journal-volume-search-result-grid-element.component.html +++ b/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal-volume/journal-volume-search-result-grid-element.component.html @@ -5,21 +5,21 @@
- - + +
- - + +
diff --git a/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal/journal-search-result-grid-element.component.html b/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal/journal-search-result-grid-element.component.html index 9a3ea95c07..9037e364d8 100644 --- a/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal/journal-search-result-grid-element.component.html +++ b/src/app/entity-groups/journal-entities/item-grid-elements/search-result-grid-elements/journal/journal-search-result-grid-element.component.html @@ -5,21 +5,21 @@
- - + +
- - + +
diff --git a/src/app/entity-groups/journal-entities/item-list-elements/journal-issue/journal-issue-list-element.component.spec.ts b/src/app/entity-groups/journal-entities/item-list-elements/journal-issue/journal-issue-list-element.component.spec.ts index 8c33ffdc1e..59af3b9e7b 100644 --- a/src/app/entity-groups/journal-entities/item-list-elements/journal-issue/journal-issue-list-element.component.spec.ts +++ b/src/app/entity-groups/journal-entities/item-list-elements/journal-issue/journal-issue-list-element.component.spec.ts @@ -6,6 +6,8 @@ import { of as observableOf } from 'rxjs'; import { Item } from '../../../../core/shared/item.model'; import { TruncatePipe } from '../../../../shared/utils/truncate.pipe'; import { TruncatableService } from '../../../../shared/truncatable/truncatable.service'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../../../shared/mocks/dso-name.service.mock'; const mockItem: Item = Object.assign(new Item(), { bundles: observableOf({}), @@ -43,6 +45,7 @@ describe('JournalIssueListElementComponent', () => { TestBed.configureTestingModule({ declarations: [JournalIssueListElementComponent, TruncatePipe], providers: [ + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: TruncatableService, useValue: truncatableServiceStub }, ], schemas: [NO_ERRORS_SCHEMA] diff --git a/src/app/entity-groups/journal-entities/item-list-elements/journal-volume/journal-volume-list-element.component.spec.ts b/src/app/entity-groups/journal-entities/item-list-elements/journal-volume/journal-volume-list-element.component.spec.ts index f4bf0d250b..663c1e477e 100644 --- a/src/app/entity-groups/journal-entities/item-list-elements/journal-volume/journal-volume-list-element.component.spec.ts +++ b/src/app/entity-groups/journal-entities/item-list-elements/journal-volume/journal-volume-list-element.component.spec.ts @@ -6,6 +6,8 @@ import { of as observableOf } from 'rxjs'; import { Item } from '../../../../core/shared/item.model'; import { TruncatePipe } from '../../../../shared/utils/truncate.pipe'; import { TruncatableService } from '../../../../shared/truncatable/truncatable.service'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../../../shared/mocks/dso-name.service.mock'; const mockItem: Item = Object.assign(new Item(), { bundles: observableOf({}), @@ -43,6 +45,7 @@ describe('JournalVolumeListElementComponent', () => { TestBed.configureTestingModule({ declarations: [JournalVolumeListElementComponent, TruncatePipe], providers: [ + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: TruncatableService, useValue: truncatableServiceStub }, ], schemas: [NO_ERRORS_SCHEMA] diff --git a/src/app/entity-groups/journal-entities/item-list-elements/journal/journal-list-element.component.spec.ts b/src/app/entity-groups/journal-entities/item-list-elements/journal/journal-list-element.component.spec.ts index b82876e364..e5dd55772b 100644 --- a/src/app/entity-groups/journal-entities/item-list-elements/journal/journal-list-element.component.spec.ts +++ b/src/app/entity-groups/journal-entities/item-list-elements/journal/journal-list-element.component.spec.ts @@ -6,6 +6,8 @@ import { of as observableOf } from 'rxjs'; import { Item } from '../../../../core/shared/item.model'; import { TruncatePipe } from '../../../../shared/utils/truncate.pipe'; import { TruncatableService } from '../../../../shared/truncatable/truncatable.service'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../../../shared/mocks/dso-name.service.mock'; const mockItem: Item = Object.assign(new Item(), { bundles: observableOf({}), @@ -34,9 +36,10 @@ describe('JournalListElementComponent', () => { }; beforeEach(waitForAsync(() => { - TestBed.configureTestingModule({ + return TestBed.configureTestingModule({ declarations: [JournalListElementComponent, TruncatePipe], providers: [ + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: TruncatableService, useValue: truncatableServiceStub }, ], schemas: [NO_ERRORS_SCHEMA] diff --git a/src/app/entity-groups/journal-entities/item-list-elements/search-result-list-elements/journal-issue/journal-issue-search-result-list-element.component.html b/src/app/entity-groups/journal-entities/item-list-elements/search-result-list-elements/journal-issue/journal-issue-search-result-list-element.component.html index 36b7e98c51..e3293be3a0 100644 --- a/src/app/entity-groups/journal-entities/item-list-elements/search-result-list-elements/journal-issue/journal-issue-search-result-list-element.component.html +++ b/src/app/entity-groups/journal-entities/item-list-elements/search-result-list-elements/journal-issue/journal-issue-search-result-list-element.component.html @@ -1,7 +1,7 @@
- +
- +
- + -
- +
- +
- + { imports: [NoopAnimationsModule], declarations: [OrgUnitGridElementComponent, TruncatePipe], providers: [ + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: TruncatableService, useValue: truncatableServiceStub }, ], schemas: [NO_ERRORS_SCHEMA] diff --git a/src/app/entity-groups/research-entities/item-grid-elements/person/person-grid-element.component.spec.ts b/src/app/entity-groups/research-entities/item-grid-elements/person/person-grid-element.component.spec.ts index b4d563b0d5..ca0784e997 100644 --- a/src/app/entity-groups/research-entities/item-grid-elements/person/person-grid-element.component.spec.ts +++ b/src/app/entity-groups/research-entities/item-grid-elements/person/person-grid-element.component.spec.ts @@ -10,6 +10,8 @@ import { TruncatePipe } from '../../../../shared/utils/truncate.pipe'; import { TruncatableService } from '../../../../shared/truncatable/truncatable.service'; import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; import { By } from '@angular/platform-browser'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../../../shared/mocks/dso-name.service.mock'; const mockItem = Object.assign(new Item(), { bundles: createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), [])), @@ -48,6 +50,7 @@ describe('PersonGridElementComponent', () => { imports: [NoopAnimationsModule], declarations: [PersonGridElementComponent, TruncatePipe], providers: [ + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: TruncatableService, useValue: truncatableServiceStub }, ], schemas: [NO_ERRORS_SCHEMA] diff --git a/src/app/entity-groups/research-entities/item-grid-elements/project/project-grid-element.component.spec.ts b/src/app/entity-groups/research-entities/item-grid-elements/project/project-grid-element.component.spec.ts index 5f4808bd2a..3f92bfe410 100644 --- a/src/app/entity-groups/research-entities/item-grid-elements/project/project-grid-element.component.spec.ts +++ b/src/app/entity-groups/research-entities/item-grid-elements/project/project-grid-element.component.spec.ts @@ -10,6 +10,8 @@ import { TruncatePipe } from '../../../../shared/utils/truncate.pipe'; import { TruncatableService } from '../../../../shared/truncatable/truncatable.service'; import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; import { By } from '@angular/platform-browser'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../../../shared/mocks/dso-name.service.mock'; const mockItem = Object.assign(new Item(), { bundles: createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), [])), @@ -42,6 +44,7 @@ describe('ProjectGridElementComponent', () => { imports: [NoopAnimationsModule], declarations: [ProjectGridElementComponent, TruncatePipe], providers: [ + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: TruncatableService, useValue: truncatableServiceStub }, ], schemas: [NO_ERRORS_SCHEMA] diff --git a/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/org-unit/org-unit-search-result-grid-element.component.html b/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/org-unit/org-unit-search-result-grid-element.component.html index 2dbccd4346..502365e60a 100644 --- a/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/org-unit/org-unit-search-result-grid-element.component.html +++ b/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/org-unit/org-unit-search-result-grid-element.component.html @@ -5,21 +5,21 @@
- - + +
- - + +
diff --git a/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/person/person-search-result-grid-element.component.html b/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/person/person-search-result-grid-element.component.html index 853a717965..0cbe19c1e0 100644 --- a/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/person/person-search-result-grid-element.component.html +++ b/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/person/person-search-result-grid-element.component.html @@ -5,21 +5,21 @@
- - + +
- - + +
diff --git a/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/project/project-search-result-grid-element.component.html b/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/project/project-search-result-grid-element.component.html index a54d136de2..97d4016ec4 100644 --- a/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/project/project-search-result-grid-element.component.html +++ b/src/app/entity-groups/research-entities/item-grid-elements/search-result-grid-elements/project/project-search-result-grid-element.component.html @@ -5,21 +5,21 @@
- - + +
- - + +
diff --git a/src/app/entity-groups/research-entities/item-list-elements/org-unit/org-unit-list-element.component.spec.ts b/src/app/entity-groups/research-entities/item-list-elements/org-unit/org-unit-list-element.component.spec.ts index 1cca1d3314..275accc956 100644 --- a/src/app/entity-groups/research-entities/item-list-elements/org-unit/org-unit-list-element.component.spec.ts +++ b/src/app/entity-groups/research-entities/item-list-elements/org-unit/org-unit-list-element.component.spec.ts @@ -6,6 +6,8 @@ import { of as observableOf } from 'rxjs'; import { Item } from '../../../../core/shared/item.model'; import { TruncatePipe } from '../../../../shared/utils/truncate.pipe'; import { TruncatableService } from '../../../../shared/truncatable/truncatable.service'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../../../shared/mocks/dso-name.service.mock'; const mockItem: Item = Object.assign(new Item(), { bundles: observableOf({}), @@ -37,6 +39,7 @@ describe('OrgUnitListElementComponent', () => { TestBed.configureTestingModule({ declarations: [OrgUnitListElementComponent, TruncatePipe], providers: [ + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: TruncatableService, useValue: truncatableServiceStub }, ], schemas: [NO_ERRORS_SCHEMA] diff --git a/src/app/entity-groups/research-entities/item-list-elements/person/person-list-element.component.spec.ts b/src/app/entity-groups/research-entities/item-list-elements/person/person-list-element.component.spec.ts index 8e86a129ce..dc874b8ec8 100644 --- a/src/app/entity-groups/research-entities/item-list-elements/person/person-list-element.component.spec.ts +++ b/src/app/entity-groups/research-entities/item-list-elements/person/person-list-element.component.spec.ts @@ -6,6 +6,8 @@ import { of as observableOf } from 'rxjs'; import { Item } from '../../../../core/shared/item.model'; import { TruncatePipe } from '../../../../shared/utils/truncate.pipe'; import { TruncatableService } from '../../../../shared/truncatable/truncatable.service'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../../../shared/mocks/dso-name.service.mock'; const mockItem: Item = Object.assign(new Item(), { bundles: observableOf({}), @@ -37,6 +39,7 @@ describe('PersonListElementComponent', () => { TestBed.configureTestingModule({ declarations: [PersonListElementComponent, TruncatePipe], providers: [ + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: TruncatableService, useValue: truncatableServiceStub }, ], schemas: [NO_ERRORS_SCHEMA] diff --git a/src/app/entity-groups/research-entities/item-list-elements/project/project-list-element.component.spec.ts b/src/app/entity-groups/research-entities/item-list-elements/project/project-list-element.component.spec.ts index 0c08d7eaaa..02241e3060 100644 --- a/src/app/entity-groups/research-entities/item-list-elements/project/project-list-element.component.spec.ts +++ b/src/app/entity-groups/research-entities/item-list-elements/project/project-list-element.component.spec.ts @@ -6,6 +6,8 @@ import { Item } from '../../../../core/shared/item.model'; import { TruncatePipe } from '../../../../shared/utils/truncate.pipe'; import { TruncatableService } from '../../../../shared/truncatable/truncatable.service'; import { ProjectListElementComponent } from './project-list-element.component'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../../../shared/mocks/dso-name.service.mock'; const mockItem: Item = Object.assign(new Item(), { bundles: observableOf({}), @@ -37,6 +39,7 @@ describe('ProjectListElementComponent', () => { TestBed.configureTestingModule({ declarations: [ProjectListElementComponent, TruncatePipe], providers: [ + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: TruncatableService, useValue: truncatableServiceStub }, ], schemas: [NO_ERRORS_SCHEMA] diff --git a/src/app/entity-groups/research-entities/item-list-elements/search-result-list-elements/org-unit/org-unit-search-result-list-element.component.html b/src/app/entity-groups/research-entities/item-list-elements/search-result-list-elements/org-unit/org-unit-search-result-list-element.component.html index 0bba83a209..07c7c5bb89 100644 --- a/src/app/entity-groups/research-entities/item-list-elements/search-result-list-elements/org-unit/org-unit-search-result-list-element.component.html +++ b/src/app/entity-groups/research-entities/item-list-elements/search-result-list-elements/org-unit/org-unit-search-result-list-element.component.html @@ -1,7 +1,7 @@
- +
- +
- +
- - +
- - +
- - + diff --git a/src/app/entity-groups/research-entities/metadata-representations/org-unit/org-unit-item-metadata-list-element.component.html b/src/app/entity-groups/research-entities/metadata-representations/org-unit/org-unit-item-metadata-list-element.component.html index 1771f3d2bc..ec4dbd4323 100644 --- a/src/app/entity-groups/research-entities/metadata-representations/org-unit/org-unit-item-metadata-list-element.component.html +++ b/src/app/entity-groups/research-entities/metadata-representations/org-unit/org-unit-item-metadata-list-element.component.html @@ -1,12 +1,12 @@ - + - + + [innerHTML]="mdRepresentation.getValue()" + [ngbTooltip]="mdRepresentation.allMetadata(['dc.description']).length > 0 ? descTemplate : null"> diff --git a/src/app/entity-groups/research-entities/metadata-representations/org-unit/org-unit-item-metadata-list-element.component.spec.ts b/src/app/entity-groups/research-entities/metadata-representations/org-unit/org-unit-item-metadata-list-element.component.spec.ts index eff6fd0b31..429f2986b9 100644 --- a/src/app/entity-groups/research-entities/metadata-representations/org-unit/org-unit-item-metadata-list-element.component.spec.ts +++ b/src/app/entity-groups/research-entities/metadata-representations/org-unit/org-unit-item-metadata-list-element.component.spec.ts @@ -34,7 +34,7 @@ describe('OrgUnitItemMetadataListElementComponent', () => { beforeEach(() => { fixture = TestBed.createComponent(OrgUnitItemMetadataListElementComponent); comp = fixture.componentInstance; - comp.metadataRepresentation = mockItemMetadataRepresentation; + comp.mdRepresentation = mockItemMetadataRepresentation; fixture.detectChanges(); }); diff --git a/src/app/entity-groups/research-entities/metadata-representations/person/person-item-metadata-list-element.component.html b/src/app/entity-groups/research-entities/metadata-representations/person/person-item-metadata-list-element.component.html index 97632117f4..6f56056781 100644 --- a/src/app/entity-groups/research-entities/metadata-representations/person/person-item-metadata-list-element.component.html +++ b/src/app/entity-groups/research-entities/metadata-representations/person/person-item-metadata-list-element.component.html @@ -1,15 +1,15 @@ - - + - + + [innerHTML]="mdRepresentation.getValue()" + [ngbTooltip]="mdRepresentation.allMetadata(['person.jobTitle']).length > 0 ? descTemplate : null"> diff --git a/src/app/entity-groups/research-entities/metadata-representations/person/person-item-metadata-list-element.component.spec.ts b/src/app/entity-groups/research-entities/metadata-representations/person/person-item-metadata-list-element.component.spec.ts index 895cf52223..b9ebf19b67 100644 --- a/src/app/entity-groups/research-entities/metadata-representations/person/person-item-metadata-list-element.component.spec.ts +++ b/src/app/entity-groups/research-entities/metadata-representations/person/person-item-metadata-list-element.component.spec.ts @@ -36,7 +36,7 @@ describe('PersonItemMetadataListElementComponent', () => { beforeEach(() => { fixture = TestBed.createComponent(PersonItemMetadataListElementComponent); comp = fixture.componentInstance; - comp.metadataRepresentation = mockItemMetadataRepresentation; + comp.mdRepresentation = mockItemMetadataRepresentation; fixture.detectChanges(); }); diff --git a/src/app/entity-groups/research-entities/metadata-representations/project/project-item-metadata-list-element.component.html b/src/app/entity-groups/research-entities/metadata-representations/project/project-item-metadata-list-element.component.html new file mode 100644 index 0000000000..acc9173bf7 --- /dev/null +++ b/src/app/entity-groups/research-entities/metadata-representations/project/project-item-metadata-list-element.component.html @@ -0,0 +1,12 @@ + + + + + + + + + + \ No newline at end of file diff --git a/src/app/entity-groups/research-entities/metadata-representations/project/project-item-metadata-list-element.component.spec.ts b/src/app/entity-groups/research-entities/metadata-representations/project/project-item-metadata-list-element.component.spec.ts new file mode 100644 index 0000000000..afa565ce40 --- /dev/null +++ b/src/app/entity-groups/research-entities/metadata-representations/project/project-item-metadata-list-element.component.spec.ts @@ -0,0 +1,51 @@ +import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { By } from '@angular/platform-browser'; + +import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; + +import { ItemMetadataRepresentation } from '../../../../core/shared/metadata-representation/item/item-metadata-representation.model'; +import { Item } from '../../../../core/shared/item.model'; +import { ProjectItemMetadataListElementComponent } from './project-item-metadata-list-element.component'; +import { MetadataValue } from '../../../../core/shared/metadata.models'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../../../shared/mocks/dso-name.service.mock'; + +const projectTitle = 'Lorem ipsum dolor sit amet'; +const mockItem = Object.assign(new Item(), { metadata: { 'dc.title': [{ value: projectTitle }] } }); +const virtMD = Object.assign(new MetadataValue(), { value: projectTitle }); + +const mockItemMetadataRepresentation = Object.assign(new ItemMetadataRepresentation(virtMD), mockItem); + +describe('ProjectItemMetadataListElementComponent', () => { + let comp: ProjectItemMetadataListElementComponent; + let fixture: ComponentFixture; + + beforeEach(waitForAsync(() => { + TestBed.configureTestingModule({ + imports:[ + NgbModule + ], + declarations: [ProjectItemMetadataListElementComponent], + providers: [ + { provide: DSONameService, useValue: new DSONameServiceMock() } + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(ProjectItemMetadataListElementComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(ProjectItemMetadataListElementComponent); + comp = fixture.componentInstance; + comp.mdRepresentation = mockItemMetadataRepresentation; + fixture.detectChanges(); + }); + + it('should show the project\'s name as a link', () => { + const linkText = fixture.debugElement.query(By.css('a')).nativeElement.textContent; + expect(linkText).toBe(projectTitle); + }); + +}); diff --git a/src/app/entity-groups/research-entities/metadata-representations/project/project-item-metadata-list-element.component.ts b/src/app/entity-groups/research-entities/metadata-representations/project/project-item-metadata-list-element.component.ts new file mode 100644 index 0000000000..a38a1f5cff --- /dev/null +++ b/src/app/entity-groups/research-entities/metadata-representations/project/project-item-metadata-list-element.component.ts @@ -0,0 +1,26 @@ +import { Component } from '@angular/core'; +import { metadataRepresentationComponent } from '../../../../shared/metadata-representation/metadata-representation.decorator'; +import { MetadataRepresentationType } from '../../../../core/shared/metadata-representation/metadata-representation.model'; +import { ItemMetadataRepresentationListElementComponent } from '../../../../shared/object-list/metadata-representation-list-element/item/item-metadata-representation-list-element.component'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; + +@metadataRepresentationComponent('Project', MetadataRepresentationType.Item) +@Component({ + selector: 'ds-project-item-metadata-list-element', + templateUrl: './project-item-metadata-list-element.component.html' +}) +/** + * The component for displaying an item of the type Project as a metadata field + */ +export class ProjectItemMetadataListElementComponent extends ItemMetadataRepresentationListElementComponent { + /** + * Initialize instance variables + * + * @param dsoNameService + */ + constructor( + public dsoNameService: DSONameService + ) { + super(); + } +} diff --git a/src/app/entity-groups/research-entities/research-entities.module.ts b/src/app/entity-groups/research-entities/research-entities.module.ts index 680e1bd79f..95b183f630 100644 --- a/src/app/entity-groups/research-entities/research-entities.module.ts +++ b/src/app/entity-groups/research-entities/research-entities.module.ts @@ -19,6 +19,7 @@ import { OrgUnitSearchResultGridElementComponent } from './item-grid-elements/se import { ProjectSearchResultGridElementComponent } from './item-grid-elements/search-result-grid-elements/project/project-search-result-grid-element.component'; import { PersonItemMetadataListElementComponent } from './metadata-representations/person/person-item-metadata-list-element.component'; import { OrgUnitItemMetadataListElementComponent } from './metadata-representations/org-unit/org-unit-item-metadata-list-element.component'; +import { ProjectItemMetadataListElementComponent } from './metadata-representations/project/project-item-metadata-list-element.component'; import { PersonSearchResultListSubmissionElementComponent } from './submission/item-list-elements/person/person-search-result-list-submission-element.component'; import { PersonInputSuggestionsComponent } from './submission/item-list-elements/person/person-suggestions/person-input-suggestions.component'; import { NameVariantModalComponent } from './submission/name-variant-modal/name-variant-modal.component'; @@ -36,6 +37,7 @@ const ENTRY_COMPONENTS = [ // put only entry components that use custom decorator OrgUnitComponent, PersonComponent, + ProjectItemMetadataListElementComponent, ProjectComponent, OrgUnitListElementComponent, OrgUnitItemMetadataListElementComponent, diff --git a/src/app/entity-groups/research-entities/submission/item-list-elements/org-unit/org-unit-search-result-list-submission-element.component.html b/src/app/entity-groups/research-entities/submission/item-list-elements/org-unit/org-unit-search-result-list-submission-element.component.html index 6123dc3dc8..e264958738 100644 --- a/src/app/entity-groups/research-entities/submission/item-list-elements/org-unit/org-unit-search-result-list-submission-element.component.html +++ b/src/app/entity-groups/research-entities/submission/item-list-elements/org-unit/org-unit-search-result-list-submission-element.component.html @@ -1,6 +1,6 @@
- +
+ [attr.rel]="(linkType == linkTypes.ExternalLink) ? 'noopener noreferrer' : null" class="dont-break-out"> {{ 'footer.link.end-user-agreement' | translate}} -
  • +
  • {{ 'footer.link.feedback' | translate}}
  • diff --git a/src/app/footer/footer.component.spec.ts b/src/app/footer/footer.component.spec.ts index 15b289d5fb..9f0250edc4 100644 --- a/src/app/footer/footer.component.spec.ts +++ b/src/app/footer/footer.component.spec.ts @@ -15,6 +15,8 @@ import { FooterComponent } from './footer.component'; import { TranslateLoaderMock } from '../shared/mocks/translate-loader.mock'; import { storeModuleConfig } from '../app.reducer'; +import { AuthorizationDataService } from '../core/data/feature-authorization/authorization-data.service'; +import { AuthorizationDataServiceStub } from '../shared/testing/authorization-service.stub'; let comp: FooterComponent; let fixture: ComponentFixture; @@ -34,7 +36,8 @@ describe('Footer component', () => { })], declarations: [FooterComponent], // declare the test component providers: [ - FooterComponent + FooterComponent, + { provide: AuthorizationDataService, useClass: AuthorizationDataServiceStub }, ], schemas: [CUSTOM_ELEMENTS_SCHEMA] }); diff --git a/src/app/footer/footer.component.ts b/src/app/footer/footer.component.ts index 1759dd1623..86186c6b12 100644 --- a/src/app/footer/footer.component.ts +++ b/src/app/footer/footer.component.ts @@ -3,6 +3,9 @@ import { hasValue } from '../shared/empty.util'; import { KlaroService } from '../shared/cookies/klaro.service'; import { environment } from '../../environments/environment'; import { NotifyInfoService } from '../core/coar-notify/notify-info/notify-info.service'; +import { Observable } from 'rxjs'; +import { AuthorizationDataService } from '../core/data/feature-authorization/authorization-data.service'; +import { FeatureID } from '../core/data/feature-authorization/feature-id'; @Component({ selector: 'ds-footer', @@ -18,12 +21,15 @@ export class FooterComponent { showTopFooter = false; showPrivacyPolicy = environment.info.enablePrivacyStatement; showEndUserAgreement = environment.info.enableEndUserAgreement; + showSendFeedback$: Observable; coarLdnEnabled: boolean; - constructor(@Optional() - private cookies: KlaroService, - private notifyInfoService: NotifyInfoService + constructor( + @Optional() private cookies: KlaroService, + private authorizationService: AuthorizationDataService, + private notifyInfoService: NotifyInfoService ) { + this.showSendFeedback$ = this.authorizationService.isAuthorized(FeatureID.CanSendFeedback); this.notifyInfoService.isCoarConfigEnabled().subscribe(coarLdnEnabled => { this.coarLdnEnabled = coarLdnEnabled; }); diff --git a/src/app/forgot-password/forgot-password-form/forgot-password-form.component.spec.ts b/src/app/forgot-password/forgot-password-form/forgot-password-form.component.spec.ts index 68566efaec..92d72d83df 100644 --- a/src/app/forgot-password/forgot-password-form/forgot-password-form.component.spec.ts +++ b/src/app/forgot-password/forgot-password-form/forgot-password-form.component.spec.ts @@ -5,7 +5,7 @@ import { NotificationsServiceStub } from '../../shared/testing/notifications-ser import { CommonModule } from '@angular/common'; import { RouterTestingModule } from '@angular/router/testing'; import { TranslateModule } from '@ngx-translate/core'; -import { FormBuilder, ReactiveFormsModule } from '@angular/forms'; +import { UntypedFormBuilder, ReactiveFormsModule } from '@angular/forms'; import { ActivatedRoute, Router } from '@angular/router'; import { Store } from '@ngrx/store'; import { EPersonDataService } from '../../core/eperson/eperson-data.service'; @@ -60,7 +60,7 @@ describe('ForgotPasswordFormComponent', () => { {provide: ActivatedRoute, useValue: route}, {provide: Store, useValue: store}, {provide: EPersonDataService, useValue: ePersonDataService}, - {provide: FormBuilder, useValue: new FormBuilder()}, + {provide: UntypedFormBuilder, useValue: new UntypedFormBuilder()}, {provide: NotificationsService, useValue: notificationsService}, ], schemas: [CUSTOM_ELEMENTS_SCHEMA] diff --git a/src/app/header-nav-wrapper/header-navbar-wrapper.component.scss b/src/app/header-nav-wrapper/header-navbar-wrapper.component.scss index b297979fd0..b02b3c378c 100644 --- a/src/app/header-nav-wrapper/header-navbar-wrapper.component.scss +++ b/src/app/header-nav-wrapper/header-navbar-wrapper.component.scss @@ -1,7 +1,4 @@ -@media screen and (max-width: map-get($grid-breakpoints, md)) { - :host.open { - background-color: var(--bs-white); - top: 0; - position: sticky; - } +:host { + position: relative; + z-index: var(--ds-nav-z-index); } diff --git a/src/app/header-nav-wrapper/themed-header-navbar-wrapper.component.scss b/src/app/header-nav-wrapper/themed-header-navbar-wrapper.component.scss deleted file mode 100644 index db392096aa..0000000000 --- a/src/app/header-nav-wrapper/themed-header-navbar-wrapper.component.scss +++ /dev/null @@ -1,3 +0,0 @@ -:host { - z-index: var(--ds-nav-z-index); -} diff --git a/src/app/header/header.component.scss b/src/app/header/header.component.scss index 546f6a06fa..cca3ed2abb 100644 --- a/src/app/header/header.component.scss +++ b/src/app/header/header.component.scss @@ -11,13 +11,12 @@ line-height: 1.5; } -.navbar ::ng-deep { - a { - color: var(--ds-header-icon-color); +.navbar-toggler { + border: none; + color: var(--ds-header-icon-color); - &:hover, &:focus { - color: var(--ds-header-icon-color-hover); - } + &:hover, &:focus { + color: var(--ds-header-icon-color-hover); } } diff --git a/src/app/home-page/home-page.component.html b/src/app/home-page/home-page.component.html index 87613b56d0..49329b3f04 100644 --- a/src/app/home-page/home-page.component.html +++ b/src/app/home-page/home-page.component.html @@ -4,6 +4,7 @@ - +
    + diff --git a/src/app/home-page/home-page.module.ts b/src/app/home-page/home-page.module.ts index 3418437d3c..00f9dbd8f9 100644 --- a/src/app/home-page/home-page.module.ts +++ b/src/app/home-page/home-page.module.ts @@ -12,25 +12,29 @@ import { ThemedHomePageComponent } from './themed-home-page.component'; import { RecentItemListComponent } from './recent-item-list/recent-item-list.component'; import { JournalEntitiesModule } from '../entity-groups/journal-entities/journal-entities.module'; import { ResearchEntitiesModule } from '../entity-groups/research-entities/research-entities.module'; +import { ThemedTopLevelCommunityListComponent } from './top-level-community-list/themed-top-level-community-list.component'; +import { SuggestionNotificationsModule } from '../suggestion-notifications/suggestion-notifications.module'; const DECLARATIONS = [ HomePageComponent, ThemedHomePageComponent, TopLevelCommunityListComponent, + ThemedTopLevelCommunityListComponent, ThemedHomeNewsComponent, HomeNewsComponent, RecentItemListComponent ]; @NgModule({ - imports: [ - CommonModule, - SharedModule.withEntryComponents(), - JournalEntitiesModule.withEntryComponents(), - ResearchEntitiesModule.withEntryComponents(), - HomePageRoutingModule, - StatisticsModule.forRoot() - ], + imports: [ + CommonModule, + SharedModule.withEntryComponents(), + JournalEntitiesModule.withEntryComponents(), + ResearchEntitiesModule.withEntryComponents(), + HomePageRoutingModule, + StatisticsModule.forRoot(), + SuggestionNotificationsModule + ], declarations: [ ...DECLARATIONS, ], diff --git a/src/app/home-page/top-level-community-list/themed-top-level-community-list.component.ts b/src/app/home-page/top-level-community-list/themed-top-level-community-list.component.ts new file mode 100644 index 0000000000..6eb74cc0a9 --- /dev/null +++ b/src/app/home-page/top-level-community-list/themed-top-level-community-list.component.ts @@ -0,0 +1,25 @@ +import { Component } from '@angular/core'; +import { TopLevelCommunityListComponent } from './top-level-community-list.component'; +import { ThemedComponent } from '../../shared/theme-support/themed.component'; + +@Component({ + selector: 'ds-themed-top-level-community-list', + styleUrls: [], + templateUrl: '../../shared/theme-support/themed.component.html', +}) +export class ThemedTopLevelCommunityListComponent extends ThemedComponent { + protected inAndOutputNames: (keyof TopLevelCommunityListComponent & keyof this)[]; + + protected getComponentName(): string { + return 'TopLevelCommunityListComponent'; + } + + protected importThemedComponent(themeName: string): Promise { + return import(`../../../themes/${themeName}/app/home-page/top-level-community-list/top-level-community-list.component`); + } + + protected importUnthemedComponent(): Promise { + return import(`./top-level-community-list.component`); + } + +} diff --git a/src/app/import-external-page/import-external-page.component.html b/src/app/import-external-page/import-external-page.component.html index 5edccd55cb..5b0c7e3ed6 100644 --- a/src/app/import-external-page/import-external-page.component.html +++ b/src/app/import-external-page/import-external-page.component.html @@ -1 +1 @@ - + diff --git a/src/app/info/end-user-agreement/end-user-agreement-content/end-user-agreement-content.component.html b/src/app/info/end-user-agreement/end-user-agreement-content/end-user-agreement-content.component.html index 1ee8712444..d5e6de85d4 100644 --- a/src/app/info/end-user-agreement/end-user-agreement-content/end-user-agreement-content.component.html +++ b/src/app/info/end-user-agreement/end-user-agreement-content/end-user-agreement-content.component.html @@ -1,37 +1,95 @@ -

    {{ 'info.end-user-agreement.head' | translate }}

    -

    - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nunc sed velit dignissim sodales ut eu. In ante metus dictum at tempor. Diam phasellus vestibulum lorem sed risus. Sed cras ornare arcu dui vivamus. Sit amet consectetur adipiscing elit pellentesque. Id velit ut tortor pretium viverra suspendisse potenti. Sed euismod nisi porta lorem mollis aliquam ut. Justo laoreet sit amet cursus sit amet dictum sit. Ullamcorper morbi tincidunt ornare massa eget egestas. -

    -

    - In iaculis nunc sed augue lacus. Curabitur vitae nunc sed velit dignissim sodales ut eu sem. Tellus id interdum velit laoreet id donec ultrices tincidunt arcu. Quis vel eros donec ac odio tempor. Viverra accumsan in nisl nisi scelerisque eu ultrices vitae. Varius quam quisque id diam vel quam. Nisl tincidunt eget nullam non nisi est sit. Nunc aliquet bibendum enim facilisis. Aenean sed adipiscing diam donec adipiscing. Convallis tellus id interdum velit laoreet. Massa placerat duis ultricies lacus sed turpis tincidunt. Sed cras ornare arcu dui vivamus arcu. Egestas integer eget aliquet nibh praesent tristique. Sit amet purus gravida quis blandit turpis cursus in hac. Porta non pulvinar neque laoreet suspendisse. Quis risus sed vulputate odio ut. Dignissim enim sit amet venenatis urna cursus. -

    -

    - Interdum velit laoreet id donec ultrices tincidunt arcu non sodales. Massa sapien faucibus et molestie. Dictumst vestibulum rhoncus est pellentesque elit ullamcorper. Metus dictum at tempor commodo ullamcorper. Tincidunt lobortis feugiat vivamus at augue eget. Non diam phasellus vestibulum lorem sed risus ultricies. Neque aliquam vestibulum morbi blandit cursus risus at ultrices mi. Euismod lacinia at quis risus sed. Lorem mollis aliquam ut porttitor leo a diam. Ipsum dolor sit amet consectetur. Ante in nibh mauris cursus mattis molestie a iaculis at. Commodo ullamcorper a lacus vestibulum. Pellentesque elit eget gravida cum sociis. Sit amet commodo nulla facilisi nullam vehicula. Vehicula ipsum a arcu cursus vitae congue mauris rhoncus aenean. -

    -

    - Ac turpis egestas maecenas pharetra convallis. Lacus sed viverra tellus in. Nullam eget felis eget nunc lobortis mattis aliquam faucibus purus. Id aliquet risus feugiat in ante metus dictum at. Quis enim lobortis scelerisque fermentum dui faucibus. Eu volutpat odio facilisis mauris sit amet massa vitae tortor. Tellus elementum sagittis vitae et leo. Cras sed felis eget velit aliquet sagittis. Proin fermentum leo vel orci porta non pulvinar neque laoreet. Dui sapien eget mi proin sed libero enim. Ultrices mi tempus imperdiet nulla malesuada. Mattis molestie a iaculis at. Turpis massa sed elementum tempus egestas. -

    -

    - Dui faucibus in ornare quam viverra orci sagittis eu volutpat. Cras adipiscing enim eu turpis. Ac felis donec et odio pellentesque. Iaculis nunc sed augue lacus viverra vitae congue eu consequat. Posuere lorem ipsum dolor sit amet consectetur adipiscing elit duis. Elit eget gravida cum sociis natoque penatibus. Id faucibus nisl tincidunt eget nullam non. Sagittis aliquam malesuada bibendum arcu vitae. Fermentum leo vel orci porta. Aliquam ultrices sagittis orci a scelerisque purus semper. Diam maecenas sed enim ut sem viverra aliquet eget sit. Et ultrices neque ornare aenean euismod. Eu mi bibendum neque egestas congue quisque egestas diam. Eget lorem dolor sed viverra. Ut lectus arcu bibendum at. Rutrum tellus pellentesque eu tincidunt tortor. Vitae congue eu consequat ac. Elit ullamcorper dignissim cras tincidunt. Sit amet volutpat consequat mauris nunc congue nisi. -

    -

    - Cursus in hac habitasse platea dictumst quisque sagittis purus. Placerat duis ultricies lacus sed turpis tincidunt. In egestas erat imperdiet sed euismod nisi porta lorem mollis. Non nisi est sit amet facilisis magna. In massa tempor nec feugiat nisl pretium fusce. Pulvinar neque laoreet suspendisse interdum consectetur. Ullamcorper morbi tincidunt ornare massa eget egestas purus viverra accumsan. Fringilla urna porttitor rhoncus dolor purus non enim. Mauris nunc congue nisi vitae suscipit. Commodo elit at imperdiet dui accumsan sit amet nulla. Tempor id eu nisl nunc mi ipsum faucibus. Porta non pulvinar neque laoreet suspendisse. Nec nam aliquam sem et tortor consequat. -

    -

    - Eget nunc lobortis mattis aliquam faucibus purus. Odio tempor orci dapibus ultrices. Sed nisi lacus sed viverra tellus. Elit ullamcorper dignissim cras tincidunt. Porttitor rhoncus dolor purus non enim praesent elementum facilisis. Viverra orci sagittis eu volutpat odio. Pharetra massa massa ultricies mi quis. Lectus vestibulum mattis ullamcorper velit sed ullamcorper. Pulvinar neque laoreet suspendisse interdum consectetur. Vitae auctor eu augue ut. Arcu dictum varius duis at consectetur lorem donec. Massa sed elementum tempus egestas sed sed. Risus viverra adipiscing at in tellus integer. Vulputate enim nulla aliquet porttitor lacus luctus accumsan. Pharetra massa massa ultricies mi. Elementum eu facilisis sed odio morbi quis commodo odio. Tincidunt lobortis feugiat vivamus at. Felis donec et odio pellentesque diam volutpat commodo sed. Risus feugiat in ante metus dictum at tempor commodo ullamcorper. Fringilla phasellus faucibus scelerisque eleifend donec pretium vulputate. -

    -

    - Lectus proin nibh nisl condimentum id venenatis a condimentum. Id consectetur purus ut faucibus pulvinar elementum integer enim. Non pulvinar neque laoreet suspendisse interdum consectetur. Est pellentesque elit ullamcorper dignissim cras tincidunt lobortis feugiat vivamus. Suscipit tellus mauris a diam maecenas sed enim ut sem. Dolor purus non enim praesent elementum facilisis. Non enim praesent elementum facilisis leo vel. Ultricies leo integer malesuada nunc vel risus commodo viverra maecenas. Nulla porttitor massa id neque aliquam vestibulum. Erat velit scelerisque in dictum non consectetur. Amet cursus sit amet dictum. Nec tincidunt praesent semper feugiat nibh. Rutrum quisque non tellus orci ac auctor. Sagittis aliquam malesuada bibendum arcu vitae elementum. Massa tincidunt dui ut ornare lectus sit amet est. Aliquet porttitor lacus luctus accumsan tortor posuere ac. Quis hendrerit dolor magna eget est lorem ipsum dolor sit. Lectus mauris ultrices eros in. -

    -

    - Massa massa ultricies mi quis hendrerit dolor magna. Est ullamcorper eget nulla facilisi etiam dignissim diam. Vulputate sapien nec sagittis aliquam malesuada. Nisi porta lorem mollis aliquam ut porttitor leo a diam. Tempus quam pellentesque nec nam. Faucibus vitae aliquet nec ullamcorper sit amet risus nullam eget. Gravida arcu ac tortor dignissim convallis aenean et tortor. A scelerisque purus semper eget duis at tellus at. Viverra ipsum nunc aliquet bibendum enim. Semper feugiat nibh sed pulvinar proin gravida hendrerit. Et ultrices neque ornare aenean euismod. Consequat semper viverra nam libero justo laoreet. Nunc mattis enim ut tellus elementum sagittis. Consectetur lorem donec massa sapien faucibus et. Vel risus commodo viverra maecenas accumsan lacus vel facilisis. Diam sollicitudin tempor id eu nisl nunc. Dolor magna eget est lorem ipsum dolor. Adipiscing elit pellentesque habitant morbi tristique. -

    -

    - Nec sagittis aliquam malesuada bibendum arcu vitae elementum curabitur. Egestas fringilla phasellus faucibus scelerisque eleifend donec pretium vulputate sapien. Porttitor leo a diam sollicitudin tempor. Pellentesque dignissim enim sit amet venenatis urna cursus eget nunc. Posuere sollicitudin aliquam ultrices sagittis orci a scelerisque. Vehicula ipsum a arcu cursus vitae congue mauris rhoncus. Leo urna molestie at elementum. Duis tristique sollicitudin nibh sit amet commodo nulla facilisi. Libero id faucibus nisl tincidunt eget nullam. Tellus elementum sagittis vitae et leo duis ut diam. Sodales ut etiam sit amet nisl purus in mollis. Ipsum faucibus vitae aliquet nec ullamcorper sit amet risus. Lacus laoreet non curabitur gravida arcu ac tortor dignissim convallis. Aliquam malesuada bibendum arcu vitae elementum. Leo vel orci porta non pulvinar neque laoreet. Ipsum suspendisse ultrices gravida dictum fusce. -

    -

    - Egestas erat imperdiet sed euismod nisi porta lorem. Venenatis a condimentum vitae sapien pellentesque habitant. Sit amet luctus venenatis lectus magna fringilla urna porttitor. Orci sagittis eu volutpat odio facilisis mauris sit amet massa. Ut enim blandit volutpat maecenas volutpat blandit aliquam. Libero volutpat sed cras ornare. Molestie ac feugiat sed lectus vestibulum mattis ullamcorper velit sed. Diam quis enim lobortis scelerisque fermentum dui. Pellentesque habitant morbi tristique senectus et netus. Auctor urna nunc id cursus metus aliquam eleifend. Elit scelerisque mauris pellentesque pulvinar pellentesque habitant morbi tristique. Sed risus ultricies tristique nulla aliquet enim tortor. Tincidunt arcu non sodales neque sodales ut. Sed lectus vestibulum mattis ullamcorper velit sed ullamcorper morbi tincidunt. -

    -

    - Pulvinar etiam non quam lacus suspendisse faucibus. Eu mi bibendum neque egestas congue. Egestas purus viverra accumsan in nisl nisi scelerisque eu. Vulputate enim nulla aliquet porttitor lacus luctus accumsan. Eu non diam phasellus vestibulum. Semper feugiat nibh sed pulvinar. Ante in nibh mauris cursus mattis molestie a. Maecenas accumsan lacus vel facilisis volutpat. Non quam lacus suspendisse faucibus. Quis commodo odio aenean sed adipiscing. Vel elit scelerisque mauris pellentesque pulvinar pellentesque habitant morbi. Sed cras ornare arcu dui vivamus arcu felis. Tortor vitae purus faucibus ornare suspendisse sed. Morbi tincidunt ornare massa eget egestas purus viverra. Nibh cras pulvinar mattis nunc. Luctus venenatis lectus magna fringilla urna porttitor. Enim blandit volutpat maecenas volutpat blandit aliquam etiam erat. Malesuada pellentesque elit eget gravida cum sociis natoque penatibus et. Felis eget nunc lobortis mattis aliquam faucibus purus in. Vivamus arcu felis bibendum ut. -

    +

    {{ 'info.end-user-agreement.head' | translate }}

    +

    Last updated May 4, 2023

    + +

    Agreement to terms

    +

    These Terms of Use constitute a legally binding agreement made between you, whether personally or on behalf of an entity ("you") and {{ 'repository.title' | translate }} ("Company", "we", "us", or "our"), concerning your access to and use of this website as well as any other media form, media channel, mobile website or mobile application related, linked, or otherwise connected thereto (collectively, the "Site"). You agree that by accessing the Site, you have read, understood, and agreed to be bound by all of these Terms of Use and any future amendments thereof.

    +

    Supplemental terms and conditions or documents that may be posted on the Site from time to time are hereby expressly incorporated herein by reference. We reserve the right, in our sole discretion, to make changes or modifications to these Terms of Use at any time and for any reason. We will alert you about any changes by updating the "Last updated" date of these Terms of Use, and you waive any right to receive specific notice of each such change. Please ensure that you check the applicable Terms every time you use our Site so that you understand which Terms apply. You will be subject to, and will be deemed to have been made aware of and to have accepted, the changes in any revised Terms of Use by your continued use of the Site after the date such revised Terms of Use are posted.

    +

    The information provided on the Site is not intended for distribution to or use by any person or entity in any jurisdiction or country where such distribution or use would be contrary to law or regulation or which would subject us to any registration requirement within such jurisdiction or country. Accordingly, those persons who choose to access the Site from other locations do so on their own initiative and are solely responsible for compliance with local laws, if and to the extent local laws are applicable.

    + +

    Intellectual property rights

    +

    Unless otherwise indicated, the Site is our proprietary property and all source code, databases, functionality, software, website designs, audio, video, text, photographs, and graphics on the Site (collectively, the "Content") and the trademarks, service marks, and logos contained therein (the "Marks") are owned or controlled by us or licensed to us, and are protected by copyright and trademark laws and various other intellectual property rights and unfair competition laws of {{ 'info.end-user-agreement.hosting-country' | translate }}, international copyright laws, and international conventions. The Content and the Marks are provided on the Site "AS IS" for your information and personal use only. Except as expressly provided in these Terms of Use, no part of the Site and no Content[a] or Marks may be copied, reproduced, aggregated, republished, uploaded, posted, publicly displayed, encoded, translated, transmitted, distributed, sold, licensed, or otherwise exploited for any commercial purpose whatsoever, without our express prior written permission.

    +

    Provided that you are eligible to use the Site, you are granted a limited license to access and use the Site and to download or print a copy of any portion of the Content to which you have properly gained access solely for your personal, non-commercial use. We reserve all rights not expressly granted to you in and to the Site, the Content and the Marks.

    + +

    User representations

    +

    By using the Site, you represent and warrant that: (1) all registration information you submit will be true, accurate, current, and complete; (2) you will maintain the accuracy of such information and promptly update such registration information as necessary; (3) you have the legal capacity and you agree to comply with these Terms of Use; (4) you will not use the Site for any illegal or unauthorized purpose; and (5) your use of the Site will not violate any applicable law or regulation.

    +

    If you provide any information that is untrue, inaccurate, not current, or incomplete, we have the right to suspend or terminate your account and refuse any and all current or future use of the Site (or any portion thereof).

    + +

    User registration

    +

    You may be required to register with the Site. You agree to keep your password confidential and will be responsible for all use of your account and password. We reserve the right to remove, reclaim, or change a username you select if we determine, in our sole discretion, that such username is inappropriate, obscene, or otherwise objectionable.

    + +

    Prohibited activities

    +

    You may not access or use the Site for any purpose other than that for which we make the Site available. The Site may not be used in connection with any commercial endeavors except those that are specifically endorsed or approved by us.

    +

    As a user of the Site, you agree not to:

    +
      +
    • Systematically retrieve data or other content from the Site to create or compile, directly or indirectly, a collection, compilation, database, or directory without written permission from us.
    • +
    • Trick, defraud, or mislead us and other users, especially in any attempt to learn sensitive account information such as user passwords.
    • +
    • Circumvent, disable, or otherwise interfere with security-related features of the Site, including features that prevent or restrict the use or copying of any Content or enforce limitations on the use of the Site and/or the Content contained therein.
    • +
    • Disparage, tarnish, or otherwise harm, in our opinion, us and/or the Site.
    • +
    • Use any information obtained from the Site in order to harass, abuse, or harm another person.
    • +
    • Make improper use of our support services or submit false reports of abuse or misconduct.
    • +
    • Use the Site in a manner inconsistent with any applicable laws or regulations.
    • +
    • Engage in unauthorized framing of or linking to the Site.
    • +
    • Upload or transmit (or attempt to upload or to transmit) viruses, Trojan horses, or other material, including excessive use of capital letters and spamming (continuous posting of repetitive text), that interferes with any party's uninterrupted use and enjoyment of the Site or modifies, impairs, disrupts, alters, or interferes with the use, features, functions, operation, or maintenance of the Site.
    • +
    • Delete the copyright or other proprietary rights notice from any Content.
    • +
    • Attempt to impersonate another user or person or use the username and password of another user.
    • +
    • Upload or transmit (or attempt to upload or to transmit) any material that acts as a passive or active information collection or transmission mechanism, including without limitation, clear graphics interchange formats ("gifs"), 1x1 pixels, web bugs, cookies, or other similar devices (sometimes referred to as "spyware" or "passive collection mechanisms" or "pcms").
    • +
    • Interfere with, disrupt, or create an undue burden on the Site or the networks or services connected to the Site.
    • +
    • Harass, annoy, intimidate, or threaten any of our employees or agents engaged in providing any portion of the Site to you.
    • +
    • Attempt to bypass any measures of the Site designed to prevent or restrict access to the Site, or any portion of the Site.
    • +
    • Make any unauthorized use of the Site, including collecting usernames and/or email addresses of users by electronic or other means for the purpose of sending unsolicited email or other forms of electronic communication, or creating user accounts by automated means or under false pretenses.
    • +
    • Use the Site as part of any effort to compete with us or otherwise use the Site and/or the Content for any revenue-generating endeavor or commercial enterprise.
    • +
    + +

    User generated contributions

    +

    The Site may provide you with the opportunity to create, submit, post, display, transmit, perform, publish, distribute, or broadcast content and materials to us or on the Site, including but not limited to text, writings, video, audio, photographs, graphics, comments, suggestions, or personal information or other material (collectively, "Contributions"). Contributions may be viewable by other users of the Site and through third-party websites. As such, any Contributions you transmit may be treated as non-confidential and non-proprietary. When you create or make available any Contributions, you thereby represent and warrant that:

    +
      +
    • The creation, distribution, transmission, public display, or performance, and the accessing, downloading, or copying of your Contributions do not and will not infringe the proprietary rights, including but not limited to the copyright, patent, trademark, trade secret, or moral rights of any third party.
    • +
    • You are the creator and owner of or have the necessary licenses, rights, consents, releases, and permissions to use and to authorize us, the Site, and other users of the Site to use your Contributions in any manner contemplated by the Site and these Terms of Use.
    • +
    • You have the written consent, release, and/or permission of each and every identifiable individual person in your Contributions to use the name or likeness of each and every such identifiable individual person to enable inclusion and use of your Contributions in any manner contemplated by the Site and these Terms of Use.
    • +
    • Your Contributions are not false, inaccurate, or misleading.
    • +
    • Your Contributions are not unsolicited or unauthorized advertising, promotional materials, pyramid schemes, chain letters, spam, mass mailings, or other forms of solicitation.
    • +
    • Your Contributions are not obscene, lewd, lascivious, filthy, violent, harassing, libelous, slanderous, or otherwise objectionable (as determined by us).
    • +
    • Your Contributions do not ridicule, mock, disparage, intimidate, or abuse anyone.
    • +
    • Your Contributions are not used to harass or threaten (in the legal sense of those terms) any other person, do not create and are not used to promote violence against a specific person or class of people.
    • +
    • Your Contributions do not violate any applicable law, regulation, or rule.
    • +
    • Your Contributions do not violate the privacy or publicity rights of any third party.
    • +
    • Your Contributions do not violate any applicable law concerning child pornography, or otherwise intended to protect the health or well-being of minors.
    • +
    • Your Contributions do not include any offensive comments that are connected to race, national origin, gender, sexual preference, colour, religion, creed or physical handicap.
    • +
    • Your Contributions do not otherwise violate, or link to material that violates, any provision of these Terms of Use, or any applicable law or regulation.
    • +
    +

    Any use of the Site in violation of the foregoing violates these Terms of Use and may result in, among other things, termination or suspension of your rights to use the Site.

    + +

    Site management

    +

    We reserve the right, but not the obligation, to: (1) monitor the Site for violations of these Terms of Use; (2) take appropriate legal action against anyone who, in our sole discretion, violates the law or these Terms of Use, including without limitation, reporting such user to law enforcement authorities; (3) in our sole discretion and without limitation, refuse, restrict access to, limit the availability of, or disable (to the extent technologically feasible) any of your Contributions or any portion thereof; (4) in our sole discretion and without limitation, notice, or liability, to remove from the Site or otherwise disable all files and content that are excessive in size or are in any way burdensome to our systems; and (5) otherwise manage the Site in a manner designed to protect our rights and property and to facilitate the proper functioning of the Site.

    + +

    Privacy policy

    +

    We care about data privacy and security. Please review our Privacy Policy. By using the Site, you agree to be bound by our Privacy Policy, which is incorporated into these Terms of Use.

    +

    Please be advised the Site is hosted in {{ 'info.end-user-agreement.hosting-country' | translate }}. If you access the Site from any other region of the world with laws or other requirements governing personal data collection, use, or disclosure that differ from applicable laws in {{ 'info.end-user-agreement.hosting-country' | translate }}, then through your continued use of the Site, you are transferring your data to {{ 'info.end-user-agreement.hosting-country' | translate }}, and you agree to have your data transferred to and processed in {{ 'info.end-user-agreement.hosting-country' | translate }}.

    + +

    Term and termination

    +

    These Terms of Use shall remain in full force and effect while you use the Site. WITHOUT LIMITING ANY OTHER PROVISION OF THESE TERMS OF USE, WE RESERVE THE RIGHT TO, IN OUR SOLE DISCRETION AND WITHOUT NOTICE OR LIABILITY, DENY ACCESS TO AND USE OF THE SITE (INCLUDING BLOCKING CERTAIN IP ADDRESSES), TO ANY PERSON FOR ANY REASON OR FOR NO REASON, INCLUDING WITHOUT LIMITATION FOR BREACH OF ANY REPRESENTATION, WARRANTY, OR COVENANT CONTAINED IN THESE TERMS OF USE OR OF ANY APPLICABLE LAW OR REGULATION. WE MAY TERMINATE YOUR USE OR PARTICIPATION IN THE SITE OR DELETE YOUR ACCOUNT AND ANY CONTENT OR INFORMATION THAT YOU POSTED AT ANY TIME, WITHOUT WARNING, IN OUR SOLE DISCRETION.

    +

    If we terminate or suspend your account for any reason, you are prohibited from registering and creating a new account under your name, a fake or borrowed name, or the name of any third party, even if you may be acting on behalf of the third party. In addition to terminating or suspending your account, we reserve the right to take appropriate legal action, including without limitation pursuing civil, criminal, and injunctive redress.

    + +

    Modifications and interruptions

    +

    We reserve the right to change, modify, or remove the contents of the Site at any time or for any reason at our sole discretion without notice. However, we have no obligation to update any information on our Site. We also reserve the right to modify or discontinue all or part of the Site without notice at any time. We will not be liable to you or any third party for any modification, change, suspension, or discontinuance of the Site.

    +

    We cannot guarantee the Site will be available at all times. We may experience hardware, software, or other problems or need to perform maintenance related to the Site, resulting in interruptions, delays, or errors. We reserve the right to change, revise, update, suspend, discontinue, or otherwise modify the Site at any time or for any reason without notice to you. You agree that we have no liability whatsoever for any loss, damage, or inconvenience caused by your inability to access or use the Site during any downtime or discontinuance of the Site. Nothing in these Terms of Use will be construed to obligate us to maintain and support the Site or to supply any corrections, updates, or releases in connection therewith.

    + +

    Corrections

    +

    There may be information on the Site that contains typographical errors, inaccuracies, or omissions. We reserve the right to correct any errors, inaccuracies, or omissions and to change or update the information on the Site at any time, without prior notice.

    + +

    Disclaimer

    +

    THE SITE IS PROVIDED ON AN AS-IS AND AS-AVAILABLE BASIS. YOU AGREE THAT YOUR USE OF THE SITE AND OUR SERVICES WILL BE AT YOUR SOLE RISK. TO THE FULLEST EXTENT PERMITTED BY LAW, WE DISCLAIM ALL WARRANTIES, EXPRESS OR IMPLIED, IN CONNECTION WITH THE SITE AND YOUR USE THEREOF, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. WE MAKE NO WARRANTIES OR REPRESENTATIONS ABOUT THE ACCURACY OR COMPLETENESS OF THE SITE'S CONTENT OR THE CONTENT OF ANY WEBSITES LINKED TO THE SITE AND WE WILL ASSUME NO LIABILITY OR RESPONSIBILITY FOR ANY (1) ERRORS, MISTAKES, OR INACCURACIES OF CONTENT AND MATERIALS, (2) PERSONAL INJURY OR PROPERTY DAMAGE, OF ANY NATURE WHATSOEVER, RESULTING FROM YOUR ACCESS TO AND USE OF THE SITE, (3) ANY UNAUTHORIZED ACCESS TO OR USE OF OUR SECURE SERVERS AND/OR ANY AND ALL PERSONAL INFORMATION AND/OR FINANCIAL INFORMATION STORED THEREIN, (4) ANY INTERRUPTION OR CESSATION OF TRANSMISSION TO OR FROM THE SITE, (5) ANY BUGS, VIRUSES, TROJAN HORSES, OR THE LIKE WHICH MAY BE TRANSMITTED TO OR THROUGH THE SITE BY ANY THIRD PARTY, AND/OR (6) ANY ERRORS OR OMISSIONS IN ANY CONTENT AND MATERIALS OR FOR ANY LOSS OR DAMAGE OF ANY KIND INCURRED AS A RESULT OF THE USE OF ANY CONTENT POSTED, TRANSMITTED, OR OTHERWISE MADE AVAILABLE VIA THE SITE. WE DO NOT WARRANT, ENDORSE, GUARANTEE, OR ASSUME RESPONSIBILITY FOR ANY PRODUCT OR SERVICE ADVERTISED OR OFFERED BY A THIRD PARTY THROUGH THE SITE, ANY HYPERLINKED WEBSITE, OR ANY WEBSITE OR MOBILE APPLICATION FEATURED IN ANY BANNER OR OTHER ADVERTISING, AND WE WILL NOT BE A PARTY TO OR IN ANY WAY BE RESPONSIBLE FOR MONITORING ANY TRANSACTION BETWEEN YOU AND ANY THIRD-PARTY PROVIDERS OF PRODUCTS OR SERVICES. AS WITH THE PURCHASE OF A PRODUCT OR SERVICE THROUGH ANY MEDIUM OR IN ANY ENVIRONMENT, YOU SHOULD USE YOUR BEST JUDGMENT AND EXERCISE CAUTION WHERE APPROPRIATE.

    + +

    Limitations of liability

    +

    IN NO EVENT WILL WE OR OUR DIRECTORS, EMPLOYEES, OR AGENTS BE LIABLE TO YOU OR ANY THIRD PARTY FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, EXEMPLARY, INCIDENTAL, SPECIAL, OR PUNITIVE DAMAGES, INCLUDING LOST PROFIT, LOST REVENUE, LOSS OF DATA, OR OTHER DAMAGES ARISING FROM YOUR USE OF THE SITE, EVEN IF WE HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

    + +

    Indemnification

    +

    You agree to defend, indemnify, and hold us harmless, including our subsidiaries, affiliates, and all of our respective officers, agents, partners, and employees, from and against any loss, damage, liability, claim, or demand, including reasonable attorneys' fees and expenses, made by any third party due to or arising out of: (1) your Contributions; (2) use of the Site; (3) breach of these Terms of Use; (4) any breach of your representations and warranties set forth in these Terms of Use; (5) your violation of the rights of a third party, including but not limited to intellectual property rights; or (6) any overt harmful act toward any other user of the Site with whom you connected via the Site. Notwithstanding the foregoing, we reserve the right, at your expense, to assume the exclusive defense and control of any matter for which you are required to indemnify us, and you agree to cooperate, at your expense, with our defense of such claims. We will use reasonable efforts to notify you of any such claim, action, or proceeding which is subject to this indemnification upon becoming aware of it.

    + +

    User Data

    +

    We will maintain certain data that you transmit to the Site for the purpose of managing the performance of the Site, as well as data relating to your use of the Site. Although we perform regular routine backups of data, you are solely responsible for all data that you transmit or that relates to any activity you have undertaken using the Site. You agree that we shall have no liability to you for any loss or corruption of any such data, and you hereby waive any right of action against us arising from any such loss or corruption of such data.

    + +

    Miscellaneous

    +

    These Terms of Use and any policies or operating rules posted by us on the Site or in respect to the Site constitute the entire agreement and understanding between you and us. Our failure to exercise or enforce any right or provision of these Terms of Use shall not operate as a waiver of such right or provision. These Terms of Use operate to the fullest extent permissible by law. We may assign any or all of our rights and obligations to others at any time. We shall not be responsible or liable for any loss, damage, delay, or failure to act caused by any cause beyond our reasonable control. If any provision or part of a provision of these Terms of Use is determined to be unlawful, void, or unenforceable, that provision or part of the provision is deemed severable from these Terms of Use and does not affect the validity and enforceability of any remaining provisions. There is no joint venture, partnership, employment or agency relationship created between you and us as a result of these Terms of Use or use of the Site. You agree that these Terms of Use will not be construed against us by virtue of having drafted them. You hereby waive any and all defenses you may have based on the electronic form of these Terms of Use and the lack of signing by the parties hereto to execute these Terms of Use.

    + +

    [a] The DSpace software used to run this site is open source. Options for reuse and reproduction of the DSpace software is governed by its open source license: https://github.com/DSpace/DSpace/blob/main/LICENSE

    \ No newline at end of file diff --git a/src/app/info/feedback/feedback-form/feedback-form.component.spec.ts b/src/app/info/feedback/feedback-form/feedback-form.component.spec.ts index d6bedc46cf..c3d38a2876 100644 --- a/src/app/info/feedback/feedback-form/feedback-form.component.spec.ts +++ b/src/app/info/feedback/feedback-form/feedback-form.component.spec.ts @@ -7,7 +7,7 @@ import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core'; import { By } from '@angular/platform-browser'; import { RouteService } from '../../../core/services/route.service'; import { routeServiceStub } from '../../../shared/testing/route-service.stub'; -import { FormBuilder } from '@angular/forms'; +import { UntypedFormBuilder } from '@angular/forms'; import { NotificationsService } from '../../../shared/notifications/notifications.service'; import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub'; import { AuthService } from '../../../core/auth/auth.service'; @@ -41,7 +41,7 @@ describe('FeedbackFormComponent', () => { declarations: [FeedbackFormComponent], providers: [ { provide: RouteService, useValue: routeServiceStub }, - { provide: FormBuilder, useValue: new FormBuilder() }, + { provide: UntypedFormBuilder, useValue: new UntypedFormBuilder() }, { provide: NotificationsService, useValue: notificationService }, { provide: FeedbackDataService, useValue: feedbackDataServiceStub }, { provide: AuthService, useValue: authService }, diff --git a/src/app/info/feedback/feedback-form/feedback-form.component.ts b/src/app/info/feedback/feedback-form/feedback-form.component.ts index 35cdd69cfc..684f974701 100644 --- a/src/app/info/feedback/feedback-form/feedback-form.component.ts +++ b/src/app/info/feedback/feedback-form/feedback-form.component.ts @@ -3,7 +3,7 @@ import { NoContent } from '../../../core/shared/NoContent.model'; import { FeedbackDataService } from '../../../core/feedback/feedback-data.service'; import { Component, Inject, OnInit } from '@angular/core'; import { RouteService } from '../../../core/services/route.service'; -import { FormBuilder, Validators } from '@angular/forms'; +import { UntypedFormBuilder, Validators } from '@angular/forms'; import { NotificationsService } from '../../../shared/notifications/notifications.service'; import { TranslateService } from '@ngx-translate/core'; import { AuthService } from '../../../core/auth/auth.service'; @@ -37,7 +37,7 @@ export class FeedbackFormComponent implements OnInit { constructor( @Inject(NativeWindowService) protected _window: NativeWindowRef, public routeService: RouteService, - private fb: FormBuilder, + private fb: UntypedFormBuilder, protected notificationsService: NotificationsService, protected translate: TranslateService, private feedbackDataService: FeedbackDataService, diff --git a/src/app/info/privacy/privacy-content/privacy-content.component.html b/src/app/info/privacy/privacy-content/privacy-content.component.html index a5bbb3fe10..f29a786e8b 100644 --- a/src/app/info/privacy/privacy-content/privacy-content.component.html +++ b/src/app/info/privacy/privacy-content/privacy-content.component.html @@ -1,37 +1,91 @@ -

    {{ 'info.privacy.head' | translate }}

    -

    - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nunc sed velit dignissim sodales ut eu. In ante metus dictum at tempor. Diam phasellus vestibulum lorem sed risus. Sed cras ornare arcu dui vivamus. Sit amet consectetur adipiscing elit pellentesque. Id velit ut tortor pretium viverra suspendisse potenti. Sed euismod nisi porta lorem mollis aliquam ut. Justo laoreet sit amet cursus sit amet dictum sit. Ullamcorper morbi tincidunt ornare massa eget egestas. -

    -

    - In iaculis nunc sed augue lacus. Curabitur vitae nunc sed velit dignissim sodales ut eu sem. Tellus id interdum velit laoreet id donec ultrices tincidunt arcu. Quis vel eros donec ac odio tempor. Viverra accumsan in nisl nisi scelerisque eu ultrices vitae. Varius quam quisque id diam vel quam. Nisl tincidunt eget nullam non nisi est sit. Nunc aliquet bibendum enim facilisis. Aenean sed adipiscing diam donec adipiscing. Convallis tellus id interdum velit laoreet. Massa placerat duis ultricies lacus sed turpis tincidunt. Sed cras ornare arcu dui vivamus arcu. Egestas integer eget aliquet nibh praesent tristique. Sit amet purus gravida quis blandit turpis cursus in hac. Porta non pulvinar neque laoreet suspendisse. Quis risus sed vulputate odio ut. Dignissim enim sit amet venenatis urna cursus. -

    -

    - Interdum velit laoreet id donec ultrices tincidunt arcu non sodales. Massa sapien faucibus et molestie. Dictumst vestibulum rhoncus est pellentesque elit ullamcorper. Metus dictum at tempor commodo ullamcorper. Tincidunt lobortis feugiat vivamus at augue eget. Non diam phasellus vestibulum lorem sed risus ultricies. Neque aliquam vestibulum morbi blandit cursus risus at ultrices mi. Euismod lacinia at quis risus sed. Lorem mollis aliquam ut porttitor leo a diam. Ipsum dolor sit amet consectetur. Ante in nibh mauris cursus mattis molestie a iaculis at. Commodo ullamcorper a lacus vestibulum. Pellentesque elit eget gravida cum sociis. Sit amet commodo nulla facilisi nullam vehicula. Vehicula ipsum a arcu cursus vitae congue mauris rhoncus aenean. -

    -

    - Ac turpis egestas maecenas pharetra convallis. Lacus sed viverra tellus in. Nullam eget felis eget nunc lobortis mattis aliquam faucibus purus. Id aliquet risus feugiat in ante metus dictum at. Quis enim lobortis scelerisque fermentum dui faucibus. Eu volutpat odio facilisis mauris sit amet massa vitae tortor. Tellus elementum sagittis vitae et leo. Cras sed felis eget velit aliquet sagittis. Proin fermentum leo vel orci porta non pulvinar neque laoreet. Dui sapien eget mi proin sed libero enim. Ultrices mi tempus imperdiet nulla malesuada. Mattis molestie a iaculis at. Turpis massa sed elementum tempus egestas. -

    -

    - Dui faucibus in ornare quam viverra orci sagittis eu volutpat. Cras adipiscing enim eu turpis. Ac felis donec et odio pellentesque. Iaculis nunc sed augue lacus viverra vitae congue eu consequat. Posuere lorem ipsum dolor sit amet consectetur adipiscing elit duis. Elit eget gravida cum sociis natoque penatibus. Id faucibus nisl tincidunt eget nullam non. Sagittis aliquam malesuada bibendum arcu vitae. Fermentum leo vel orci porta. Aliquam ultrices sagittis orci a scelerisque purus semper. Diam maecenas sed enim ut sem viverra aliquet eget sit. Et ultrices neque ornare aenean euismod. Eu mi bibendum neque egestas congue quisque egestas diam. Eget lorem dolor sed viverra. Ut lectus arcu bibendum at. Rutrum tellus pellentesque eu tincidunt tortor. Vitae congue eu consequat ac. Elit ullamcorper dignissim cras tincidunt. Sit amet volutpat consequat mauris nunc congue nisi. -

    -

    - Cursus in hac habitasse platea dictumst quisque sagittis purus. Placerat duis ultricies lacus sed turpis tincidunt. In egestas erat imperdiet sed euismod nisi porta lorem mollis. Non nisi est sit amet facilisis magna. In massa tempor nec feugiat nisl pretium fusce. Pulvinar neque laoreet suspendisse interdum consectetur. Ullamcorper morbi tincidunt ornare massa eget egestas purus viverra accumsan. Fringilla urna porttitor rhoncus dolor purus non enim. Mauris nunc congue nisi vitae suscipit. Commodo elit at imperdiet dui accumsan sit amet nulla. Tempor id eu nisl nunc mi ipsum faucibus. Porta non pulvinar neque laoreet suspendisse. Nec nam aliquam sem et tortor consequat. -

    -

    - Eget nunc lobortis mattis aliquam faucibus purus. Odio tempor orci dapibus ultrices. Sed nisi lacus sed viverra tellus. Elit ullamcorper dignissim cras tincidunt. Porttitor rhoncus dolor purus non enim praesent elementum facilisis. Viverra orci sagittis eu volutpat odio. Pharetra massa massa ultricies mi quis. Lectus vestibulum mattis ullamcorper velit sed ullamcorper. Pulvinar neque laoreet suspendisse interdum consectetur. Vitae auctor eu augue ut. Arcu dictum varius duis at consectetur lorem donec. Massa sed elementum tempus egestas sed sed. Risus viverra adipiscing at in tellus integer. Vulputate enim nulla aliquet porttitor lacus luctus accumsan. Pharetra massa massa ultricies mi. Elementum eu facilisis sed odio morbi quis commodo odio. Tincidunt lobortis feugiat vivamus at. Felis donec et odio pellentesque diam volutpat commodo sed. Risus feugiat in ante metus dictum at tempor commodo ullamcorper. Fringilla phasellus faucibus scelerisque eleifend donec pretium vulputate. -

    -

    - Lectus proin nibh nisl condimentum id venenatis a condimentum. Id consectetur purus ut faucibus pulvinar elementum integer enim. Non pulvinar neque laoreet suspendisse interdum consectetur. Est pellentesque elit ullamcorper dignissim cras tincidunt lobortis feugiat vivamus. Suscipit tellus mauris a diam maecenas sed enim ut sem. Dolor purus non enim praesent elementum facilisis. Non enim praesent elementum facilisis leo vel. Ultricies leo integer malesuada nunc vel risus commodo viverra maecenas. Nulla porttitor massa id neque aliquam vestibulum. Erat velit scelerisque in dictum non consectetur. Amet cursus sit amet dictum. Nec tincidunt praesent semper feugiat nibh. Rutrum quisque non tellus orci ac auctor. Sagittis aliquam malesuada bibendum arcu vitae elementum. Massa tincidunt dui ut ornare lectus sit amet est. Aliquet porttitor lacus luctus accumsan tortor posuere ac. Quis hendrerit dolor magna eget est lorem ipsum dolor sit. Lectus mauris ultrices eros in. -

    -

    - Massa massa ultricies mi quis hendrerit dolor magna. Est ullamcorper eget nulla facilisi etiam dignissim diam. Vulputate sapien nec sagittis aliquam malesuada. Nisi porta lorem mollis aliquam ut porttitor leo a diam. Tempus quam pellentesque nec nam. Faucibus vitae aliquet nec ullamcorper sit amet risus nullam eget. Gravida arcu ac tortor dignissim convallis aenean et tortor. A scelerisque purus semper eget duis at tellus at. Viverra ipsum nunc aliquet bibendum enim. Semper feugiat nibh sed pulvinar proin gravida hendrerit. Et ultrices neque ornare aenean euismod. Consequat semper viverra nam libero justo laoreet. Nunc mattis enim ut tellus elementum sagittis. Consectetur lorem donec massa sapien faucibus et. Vel risus commodo viverra maecenas accumsan lacus vel facilisis. Diam sollicitudin tempor id eu nisl nunc. Dolor magna eget est lorem ipsum dolor. Adipiscing elit pellentesque habitant morbi tristique. -

    -

    - Nec sagittis aliquam malesuada bibendum arcu vitae elementum curabitur. Egestas fringilla phasellus faucibus scelerisque eleifend donec pretium vulputate sapien. Porttitor leo a diam sollicitudin tempor. Pellentesque dignissim enim sit amet venenatis urna cursus eget nunc. Posuere sollicitudin aliquam ultrices sagittis orci a scelerisque. Vehicula ipsum a arcu cursus vitae congue mauris rhoncus. Leo urna molestie at elementum. Duis tristique sollicitudin nibh sit amet commodo nulla facilisi. Libero id faucibus nisl tincidunt eget nullam. Tellus elementum sagittis vitae et leo duis ut diam. Sodales ut etiam sit amet nisl purus in mollis. Ipsum faucibus vitae aliquet nec ullamcorper sit amet risus. Lacus laoreet non curabitur gravida arcu ac tortor dignissim convallis. Aliquam malesuada bibendum arcu vitae elementum. Leo vel orci porta non pulvinar neque laoreet. Ipsum suspendisse ultrices gravida dictum fusce. -

    -

    - Egestas erat imperdiet sed euismod nisi porta lorem. Venenatis a condimentum vitae sapien pellentesque habitant. Sit amet luctus venenatis lectus magna fringilla urna porttitor. Orci sagittis eu volutpat odio facilisis mauris sit amet massa. Ut enim blandit volutpat maecenas volutpat blandit aliquam. Libero volutpat sed cras ornare. Molestie ac feugiat sed lectus vestibulum mattis ullamcorper velit sed. Diam quis enim lobortis scelerisque fermentum dui. Pellentesque habitant morbi tristique senectus et netus. Auctor urna nunc id cursus metus aliquam eleifend. Elit scelerisque mauris pellentesque pulvinar pellentesque habitant morbi tristique. Sed risus ultricies tristique nulla aliquet enim tortor. Tincidunt arcu non sodales neque sodales ut. Sed lectus vestibulum mattis ullamcorper velit sed ullamcorper morbi tincidunt. -

    -

    - Pulvinar etiam non quam lacus suspendisse faucibus. Eu mi bibendum neque egestas congue. Egestas purus viverra accumsan in nisl nisi scelerisque eu. Vulputate enim nulla aliquet porttitor lacus luctus accumsan. Eu non diam phasellus vestibulum. Semper feugiat nibh sed pulvinar. Ante in nibh mauris cursus mattis molestie a. Maecenas accumsan lacus vel facilisis volutpat. Non quam lacus suspendisse faucibus. Quis commodo odio aenean sed adipiscing. Vel elit scelerisque mauris pellentesque pulvinar pellentesque habitant morbi. Sed cras ornare arcu dui vivamus arcu felis. Tortor vitae purus faucibus ornare suspendisse sed. Morbi tincidunt ornare massa eget egestas purus viverra. Nibh cras pulvinar mattis nunc. Luctus venenatis lectus magna fringilla urna porttitor. Enim blandit volutpat maecenas volutpat blandit aliquam etiam erat. Malesuada pellentesque elit eget gravida cum sociis natoque penatibus et. Felis eget nunc lobortis mattis aliquam faucibus purus in. Vivamus arcu felis bibendum ut. -

    +

    {{ 'info.privacy.head' | translate }}

    +

    Last updated May 4, 2023

    + +

    Introduction

    +

    {{ 'repository.title' | translate }} ("Company" or "We") respects your privacy and is committed to protecting it through our compliance with this policy.

    +

    This policy describes the types of information we may collect from you or that you may provide when you visit this website (our "Website") and our practices for collecting, using, maintaining, protecting, and disclosing that information.

    +

    This policy applies to information we collect:

    +
      +
    • On this Website.
    • +
    • In email, text, and other electronic messages between you and this Website.
    • +
    +

    It does not apply to information collected by:

    +
      +
    • us offline or through any other means, including on any other website operated by Company or any third party; or
    • +
    • any third party, including through any application or content (including advertising) that may link to or be accessible from or on the Website.
    • +
    +

    Please read this policy carefully to understand our policies and practices regarding your information and how we will treat it. If you do not agree with our policies and practices, your choice is not to use our Website. By accessing or using this Website, you agree to this privacy policy. This policy may change from time to time. Your continued use of this Website after we make changes is deemed to be acceptance of those changes, so please check the policy periodically for updates.

    + +

    Children under the age of 13

    +

    Our Website is not intended for children under 13 years of age. No one under age 13 may provide any personal information to or on the Website. We do not knowingly collect personal information from children under 13. If you are under 13, do not use or provide any information on this Website or provide any information about yourself to us, including your name, address, telephone number, email address, or any screen name or username you may use. If we learn we have collected or received personal information from a child under 13 without verification of parental consent, we will delete that information.

    + +

    Information we collect about you and how we collect it

    +

    We collect several types of information from and about users of our Website, including information:

    +
      +
    • by which you may be personally identified, such as name, e-mail address, telephone number, or any other identifier by which you may be contacted online or offline ("personal information"); and/or
    • +
    • about your internet connection, the equipment you use to access our Website and usage details.
    • +
    +

    We collect this information:

    +
      +
    • directly from you when you provide it to us.
    • +
    • automatically as you navigate through the site. Information collected automatically may include usage details, IP addresses, and information collected through cookies, web beacons, and other tracking technologies; and/or
    • +
    • from third parties, for example, our business partners.
    • +
    + +

    Information you provide to us

    +

    The information we collect on or through our Website may include:

    +
      +
    • Information that you provide by filling in forms on our Website. We may also ask you for information when you report a problem with our Website.
    • +
    • Records and copies of your correspondence (including email addresses), if you contact us.
    • +
    • Your responses to surveys that we might ask you to complete for research purpose.
    • +
    + +

    Information we collect through automatic data collection technologies

    +

    As you navigate through and interact with our Website, we may use automatic data collection technologies to collect certain information about your equipment, browsing actions, and patterns, including:

    +
      +
    • Details of your visits to our Website, including traffic data, location data, logs, and other communication data and the resources that you access and use on the Website.
    • +
    • Information about your computer and internet connection, including your IP address, operating system, and browser type.
    • +
    +

    The information we collect automatically is statistical data and does not include personal information, but we may maintain it or associate it with personal information we collect in other ways or receive from third parties. It helps us to improve our Website and to deliver a better and more personalized service, including by enabling us to:

    +
      +
    • Estimate our audience size and usage patterns.
    • +
    • Store information about your preferences, allowing us to customize our Website according to your individual interests.
    • +
    • Speed up your searches.
    • +
    • Recognize you when you return to our Website.
    • +
    +

    The technologies we use for this automatic data collection may include:

    +
      +
    • Cookies (or browser cookies). A cookie is a small file placed on the hard drive of your computer. You may refuse to accept browser cookies by activating the appropriate setting on your browser. However, if you select this setting you may be unable to access certain parts of our Website. Unless you have adjusted your browser setting so that it will refuse cookies, our system will issue cookies when you direct your browser to our Website.
    • +
    + +

    How we use your information

    +

    We use information that we collect about you or that you provide to us, including any personal information:

    +
      +
    • To present our Website and its contents to you.
    • +
    • To provide you with information, products, or services that you request from us.
    • +
    • To fulfill any other purpose for which you provide it.
    • +
    • To carry out our obligations and enforce our rights arising from any contracts entered into between you and us, including for billing and collection.
    • +
    • To notify you about changes to our Website or any products or services we offer or provide through it.
    • +
    • In any other way we may describe when you provide the information.
    • +
    • For any other purpose with your consent.
    • +
    + +

    Disclosure of your information

    +

    We may disclose aggregated information about our users, and information that does not identify any individual, without restriction.

    +

    We may disclose personal information that we collect or you provide as described in this privacy policy:

    +
      +
    • To contractors, service providers, and other third parties we use to support our business and who are bound by contractual obligations to keep personal information confidential and use it only for the purposes for which we disclose it to them.
    • +
    • To a buyer or other successor in the event of a merger, divestiture, restructuring, reorganization, dissolution, or other sale or transfer of some or all of Company's assets, whether as a going concern or as part of bankruptcy, liquidation, or similar proceeding, in which personal information held by Company about our Website users is among the assets transferred.
    • +
    • To fulfill the purpose for which you provide it.
    • +
    • For any other purpose disclosed by us when you provide the information.
    • +
    • With your consent.
    • +
    +

    We may also disclose your personal information:

    +
      +
    • To comply with any court order, law, or legal process, including to respond to any government or regulatory request.
    • +
    • To enforce or apply our End User Agreement and other agreements, including for billing and collection purposes.
    • +
    • If we believe disclosure is necessary or appropriate to protect the rights, property, or safety of the Company, our customers, or others.
    • +
    + +

    Changes to our privacy policy

    +

    It is our policy to post any changes we make to our privacy policy on this page. The date the privacy policy was last revised is identified at the top of the page. You are responsible for periodically visiting our Website and this privacy policy to check for any changes.

    \ No newline at end of file diff --git a/src/app/item-page/bitstreams/request-a-copy/bitstream-request-a-copy-page.component.ts b/src/app/item-page/bitstreams/request-a-copy/bitstream-request-a-copy-page.component.ts index 59819a4a66..77e1049d87 100644 --- a/src/app/item-page/bitstreams/request-a-copy/bitstream-request-a-copy-page.component.ts +++ b/src/app/item-page/bitstreams/request-a-copy/bitstream-request-a-copy-page.component.ts @@ -11,7 +11,7 @@ import { combineLatest as observableCombineLatest, Observable, of as observableO import { getBitstreamDownloadRoute, getForbiddenRoute } from '../../../app-routing-paths'; import { TranslateService } from '@ngx-translate/core'; import { EPerson } from '../../../core/eperson/models/eperson.model'; -import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; +import { UntypedFormBuilder, UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms'; import { ItemRequestDataService } from '../../../core/data/item-request-data.service'; import { ItemRequest } from '../../../core/shared/item-request.model'; import { Item } from '../../../core/shared/item.model'; @@ -34,7 +34,7 @@ export class BitstreamRequestACopyPageComponent implements OnInit, OnDestroy { canDownload$: Observable; private subs: Subscription[] = []; - requestCopyForm: FormGroup; + requestCopyForm: UntypedFormGroup; item: Item; itemName: string; @@ -49,7 +49,7 @@ export class BitstreamRequestACopyPageComponent implements OnInit, OnDestroy { protected router: Router, private authorizationService: AuthorizationDataService, private auth: AuthService, - private formBuilder: FormBuilder, + private formBuilder: UntypedFormBuilder, private itemRequestDataService: ItemRequestDataService, private notificationsService: NotificationsService, private dsoNameService: DSONameService, @@ -59,15 +59,15 @@ export class BitstreamRequestACopyPageComponent implements OnInit, OnDestroy { ngOnInit(): void { this.requestCopyForm = this.formBuilder.group({ - name: new FormControl('', { + name: new UntypedFormControl('', { validators: [Validators.required], }), - email: new FormControl('', { + email: new UntypedFormControl('', { validators: [Validators.required, Validators.pattern('^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$')] }), - allfiles: new FormControl(''), - message: new FormControl(''), + allfiles: new UntypedFormControl(''), + message: new UntypedFormControl(''), }); diff --git a/src/app/item-page/bitstreams/upload/upload-bitstream.component.html b/src/app/item-page/bitstreams/upload/upload-bitstream.component.html index 7a193451f7..1732da1235 100644 --- a/src/app/item-page/bitstreams/upload/upload-bitstream.component.html +++ b/src/app/item-page/bitstreams/upload/upload-bitstream.component.html @@ -1,12 +1,12 @@
    -
    +

    {{'item.bitstreams.upload.title' | translate}}

    {{'item.bitstreams.upload.item' | translate}} - {{item.name}} + {{ dsoNameService.getName(item) }}
    @@ -24,7 +24,7 @@ (click)="f.open()" ngDefaultControl> - + diff --git a/src/app/item-page/edit-item-page/item-access-control/item-access-control.component.scss b/src/app/item-page/edit-item-page/item-access-control/item-access-control.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/item-page/edit-item-page/item-access-control/item-access-control.component.spec.ts b/src/app/item-page/edit-item-page/item-access-control/item-access-control.component.spec.ts new file mode 100644 index 0000000000..d841b97e2a --- /dev/null +++ b/src/app/item-page/edit-item-page/item-access-control/item-access-control.component.spec.ts @@ -0,0 +1,25 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { ItemAccessControlComponent } from './item-access-control.component'; + +xdescribe('ItemAccessControlComponent', () => { + let component: ItemAccessControlComponent; + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + declarations: [ ItemAccessControlComponent ] + }) + .compileComponents(); + }); + + beforeEach(() => { + fixture = TestBed.createComponent(ItemAccessControlComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/src/app/item-page/edit-item-page/item-access-control/item-access-control.component.ts b/src/app/item-page/edit-item-page/item-access-control/item-access-control.component.ts new file mode 100644 index 0000000000..874b624494 --- /dev/null +++ b/src/app/item-page/edit-item-page/item-access-control/item-access-control.component.ts @@ -0,0 +1,26 @@ +import { Component, OnInit } from '@angular/core'; +import { Observable } from 'rxjs'; +import { map } from 'rxjs/operators'; +import { getFirstSucceededRemoteData } from '../../../core/shared/operators'; +import { RemoteData } from '../../../core/data/remote-data'; +import { Item } from '../../../core/shared/item.model'; +import { ActivatedRoute } from '@angular/router'; + +@Component({ + selector: 'ds-item-access-control', + templateUrl: './item-access-control.component.html', + styleUrls: [ './item-access-control.component.scss' ], +}) +export class ItemAccessControlComponent implements OnInit { + + itemRD$: Observable>; + + constructor(private route: ActivatedRoute) {} + + ngOnInit(): void { + this.itemRD$ = this.route.parent.parent.data.pipe( + map((data) => data.dso) + ).pipe(getFirstSucceededRemoteData()) as Observable>; + } + +} diff --git a/src/app/item-page/edit-item-page/item-authorizations/item-authorizations.component.html b/src/app/item-page/edit-item-page/item-authorizations/item-authorizations.component.html index 5437525185..7f121081f2 100644 --- a/src/app/item-page/edit-item-page/item-authorizations/item-authorizations.component.html +++ b/src/app/item-page/edit-item-page/item-authorizations/item-authorizations.component.html @@ -11,7 +11,7 @@
    diff --git a/src/app/item-page/edit-item-page/item-authorizations/item-authorizations.component.ts b/src/app/item-page/edit-item-page/item-authorizations/item-authorizations.component.ts index c06bcad7f2..635cf455b5 100644 --- a/src/app/item-page/edit-item-page/item-authorizations/item-authorizations.component.ts +++ b/src/app/item-page/edit-item-page/item-authorizations/item-authorizations.component.ts @@ -101,7 +101,7 @@ export class ItemAuthorizationsComponent implements OnInit, OnDestroy { constructor( private linkService: LinkService, private route: ActivatedRoute, - private nameService: DSONameService + public nameService: DSONameService ) { } diff --git a/src/app/item-page/edit-item-page/item-bitstreams/item-bitstreams.component.spec.ts b/src/app/item-page/edit-item-page/item-bitstreams/item-bitstreams.component.spec.ts index 67d047d776..10e1812131 100644 --- a/src/app/item-page/edit-item-page/item-bitstreams/item-bitstreams.component.spec.ts +++ b/src/app/item-page/edit-item-page/item-bitstreams/item-bitstreams.component.spec.ts @@ -25,6 +25,7 @@ import { getMockRequestService } from '../../../shared/mocks/request.service.moc import { createSuccessfulRemoteDataObject, createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils'; import { createPaginatedList } from '../../../shared/testing/utils.test'; import { FieldChangeType } from '../../../core/data/object-updates/field-change-type.model'; +import { BitstreamDataServiceStub } from '../../../shared/testing/bitstream-data-service.stub'; let comp: ItemBitstreamsComponent; let fixture: ComponentFixture; @@ -71,7 +72,7 @@ let objectUpdatesService: ObjectUpdatesService; let router: any; let route: ActivatedRoute; let notificationsService: NotificationsService; -let bitstreamService: BitstreamDataService; +let bitstreamService: BitstreamDataServiceStub; let objectCache: ObjectCacheService; let requestService: RequestService; let searchConfig: SearchConfigurationService; @@ -112,9 +113,7 @@ describe('ItemBitstreamsComponent', () => { success: successNotification } ); - bitstreamService = jasmine.createSpyObj('bitstreamService', { - delete: jasmine.createSpy('delete') - }); + bitstreamService = new BitstreamDataServiceStub(); objectCache = jasmine.createSpyObj('objectCache', { remove: jasmine.createSpy('remove') }); @@ -179,15 +178,16 @@ describe('ItemBitstreamsComponent', () => { describe('when submit is called', () => { beforeEach(() => { + spyOn(bitstreamService, 'removeMultiple').and.callThrough(); comp.submit(); }); - it('should call delete on the bitstreamService for the marked field', () => { - expect(bitstreamService.delete).toHaveBeenCalledWith(bitstream2.id); + it('should call removeMultiple on the bitstreamService for the marked field', () => { + expect(bitstreamService.removeMultiple).toHaveBeenCalledWith([bitstream2]); }); - it('should not call delete on the bitstreamService for the unmarked field', () => { - expect(bitstreamService.delete).not.toHaveBeenCalledWith(bitstream1.id); + it('should not call removeMultiple on the bitstreamService for the unmarked field', () => { + expect(bitstreamService.removeMultiple).not.toHaveBeenCalledWith([bitstream1]); }); }); @@ -210,7 +210,6 @@ describe('ItemBitstreamsComponent', () => { comp.dropBitstream(bundle, { fromIndex: 0, toIndex: 50, - // eslint-disable-next-line no-empty, @typescript-eslint/no-empty-function finish: () => { done(); } diff --git a/src/app/item-page/edit-item-page/item-bitstreams/item-bitstreams.component.ts b/src/app/item-page/edit-item-page/item-bitstreams/item-bitstreams.component.ts index 0c7dfb1e34..ee53bd919c 100644 --- a/src/app/item-page/edit-item-page/item-bitstreams/item-bitstreams.component.ts +++ b/src/app/item-page/edit-item-page/item-bitstreams/item-bitstreams.component.ts @@ -1,7 +1,7 @@ import { ChangeDetectorRef, Component, NgZone, OnDestroy } from '@angular/core'; import { AbstractItemUpdateComponent } from '../abstract-item-update/abstract-item-update.component'; import { filter, map, switchMap, take } from 'rxjs/operators'; -import { Observable, of as observableOf, Subscription, zip as observableZip } from 'rxjs'; +import { Observable, Subscription, zip as observableZip } from 'rxjs'; import { ItemDataService } from '../../../core/data/item-data.service'; import { ObjectUpdatesService } from '../../../core/data/object-updates/object-updates.service'; import { ActivatedRoute, Router } from '@angular/router'; @@ -133,20 +133,16 @@ export class ItemBitstreamsComponent extends AbstractItemUpdateComponent impleme ); // Send out delete requests for all deleted bitstreams - const removedResponses$ = removedBitstreams$.pipe( + const removedResponses$: Observable> = removedBitstreams$.pipe( take(1), - switchMap((removedBistreams: Bitstream[]) => { - if (isNotEmpty(removedBistreams)) { - return observableZip(...removedBistreams.map((bitstream: Bitstream) => this.bitstreamService.delete(bitstream.id))); - } else { - return observableOf(undefined); - } + switchMap((removedBitstreams: Bitstream[]) => { + return this.bitstreamService.removeMultiple(removedBitstreams); }) ); // Perform the setup actions from above in order and display notifications - removedResponses$.pipe(take(1)).subscribe((responses: RemoteData[]) => { - this.displayNotifications('item.edit.bitstreams.notifications.remove', responses); + removedResponses$.subscribe((responses: RemoteData) => { + this.displayNotifications('item.edit.bitstreams.notifications.remove', [responses]); this.submitting = false; }); } diff --git a/src/app/item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component.html b/src/app/item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component.html index b732e6a950..62170235a3 100644 --- a/src/app/item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component.html +++ b/src/app/item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component.html @@ -3,7 +3,7 @@
    - {{'item.edit.bitstreams.bundle.name' | translate:{ name: bundle.name } }} + {{'item.edit.bitstreams.bundle.name' | translate:{ name: dsoNameService.getName(bundle) } }}
    diff --git a/src/app/item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component.ts b/src/app/item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component.ts index eb05d5e74f..70f4b63217 100644 --- a/src/app/item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component.ts +++ b/src/app/item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component.ts @@ -4,6 +4,7 @@ import { Item } from '../../../../core/shared/item.model'; import { ResponsiveColumnSizes } from '../../../../shared/responsive-table-sizes/responsive-column-sizes'; import { ResponsiveTableSizes } from '../../../../shared/responsive-table-sizes/responsive-table-sizes'; import { getItemPageRoute } from '../../../item-page-routing-paths'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; @Component({ selector: 'ds-item-edit-bitstream-bundle', @@ -55,7 +56,10 @@ export class ItemEditBitstreamBundleComponent implements OnInit { */ itemPageRoute: string; - constructor(private viewContainerRef: ViewContainerRef) { + constructor( + protected viewContainerRef: ViewContainerRef, + public dsoNameService: DSONameService, + ) { } ngOnInit(): void { diff --git a/src/app/item-page/edit-item-page/item-collection-mapper/item-collection-mapper.component.html b/src/app/item-page/edit-item-page/item-collection-mapper/item-collection-mapper.component.html index 507e35e630..c522b8a9c5 100644 --- a/src/app/item-page/edit-item-page/item-collection-mapper/item-collection-mapper.component.html +++ b/src/app/item-page/edit-item-page/item-collection-mapper/item-collection-mapper.component.html @@ -1,4 +1,4 @@ -
    +

    {{'item.edit.item-mapper.head' | translate}}

    diff --git a/src/app/item-page/edit-item-page/item-move/item-move.component.html b/src/app/item-page/edit-item-page/item-move/item-move.component.html index 8cb8d1c1c4..589aac655f 100644 --- a/src/app/item-page/edit-item-page/item-move/item-move.component.html +++ b/src/app/item-page/edit-item-page/item-move/item-move.component.html @@ -20,9 +20,10 @@

    +

    {{'item.edit.move.inheritpolicies.description' | translate}} diff --git a/src/app/item-page/edit-item-page/item-move/item-move.component.ts b/src/app/item-page/edit-item-page/item-move/item-move.component.ts index 4f53fa7df1..0f9df588a1 100644 --- a/src/app/item-page/edit-item-page/item-move/item-move.component.ts +++ b/src/app/item-page/edit-item-page/item-move/item-move.component.ts @@ -16,6 +16,7 @@ import { SearchService } from '../../../core/shared/search/search.service'; import { getItemEditRoute, getItemPageRoute } from '../../item-page-routing-paths'; import { followLink } from '../../../shared/utils/follow-link-config.model'; import { RequestService } from '../../../core/data/request.service'; +import { DSONameService } from '../../../core/breadcrumbs/dso-name.service'; @Component({ selector: 'ds-item-move', @@ -57,6 +58,7 @@ export class ItemMoveComponent implements OnInit { private searchService: SearchService, private translateService: TranslateService, private requestService: RequestService, + protected dsoNameService: DSONameService, ) {} ngOnInit(): void { @@ -88,7 +90,7 @@ export class ItemMoveComponent implements OnInit { */ selectDso(data: any): void { this.selectedCollection = data; - this.selectedCollectionName = data.name; + this.selectedCollectionName = this.dsoNameService.getName(data); this.canSubmit = true; } diff --git a/src/app/item-page/edit-item-page/item-status/item-status.component.ts b/src/app/item-page/edit-item-page/item-status/item-status.component.ts index c2db518415..828f8d7439 100644 --- a/src/app/item-page/edit-item-page/item-status/item-status.component.ts +++ b/src/app/item-page/edit-item-page/item-status/item-status.component.ts @@ -3,15 +3,15 @@ import { fadeIn, fadeInOut } from '../../../shared/animations/fade'; import { Item } from '../../../core/shared/item.model'; import { ActivatedRoute } from '@angular/router'; import { ItemOperation } from '../item-operation/itemOperation.model'; -import { distinctUntilChanged, first, map, mergeMap, switchMap, toArray } from 'rxjs/operators'; +import { distinctUntilChanged, map, mergeMap, switchMap, toArray } from 'rxjs/operators'; import { BehaviorSubject, Observable, Subscription } from 'rxjs'; import { RemoteData } from '../../../core/data/remote-data'; import { getItemEditRoute, getItemPageRoute } from '../../item-page-routing-paths'; import { AuthorizationDataService } from '../../../core/data/feature-authorization/authorization-data.service'; import { FeatureID } from '../../../core/data/feature-authorization/feature-id'; -import { hasValue } from '../../../shared/empty.util'; +import { hasValue, isNotEmpty } from '../../../shared/empty.util'; import { - getAllSucceededRemoteDataPayload, getFirstSucceededRemoteData, getRemoteDataPayload, + getAllSucceededRemoteDataPayload, getFirstCompletedRemoteData, getFirstSucceededRemoteData, getRemoteDataPayload, } from '../../../core/shared/operators'; import { IdentifierDataService } from '../../../core/data/identifier-data.service'; import { Identifier } from '../../../shared/object-list/identifier-data/identifier.model'; @@ -82,7 +82,6 @@ export class ItemStatusComponent implements OnInit { ngOnInit(): void { this.itemRD$ = this.route.parent.data.pipe(map((data) => data.dso)); this.itemRD$.pipe( - first(), map((data: RemoteData) => data.payload) ).subscribe((item: Item) => { this.statusData = Object.assign({ @@ -105,12 +104,13 @@ export class ItemStatusComponent implements OnInit { // Observable for configuration determining whether the Register DOI feature is enabled let registerConfigEnabled$: Observable = this.configurationService.findByPropertyName('identifiers.item-status.register-doi').pipe( - getFirstSucceededRemoteData(), - getRemoteDataPayload(), - map((enabled: ConfigurationProperty) => { - if (enabled !== undefined && enabled.values) { - return true; + getFirstCompletedRemoteData(), + map((rd: RemoteData) => { + // If the config property is exposed via rest and has a value set, return it + if (rd.hasSucceeded && hasValue(rd.payload) && isNotEmpty(rd.payload.values)) { + return rd.payload.values[0] === 'true'; } + // Otherwise, return false return false; }) ); diff --git a/src/app/item-page/edit-item-page/item-status/themed-item-status.component.ts b/src/app/item-page/edit-item-page/item-status/themed-item-status.component.ts new file mode 100644 index 0000000000..eac5a53702 --- /dev/null +++ b/src/app/item-page/edit-item-page/item-status/themed-item-status.component.ts @@ -0,0 +1,23 @@ +import { Component } from '@angular/core'; +import { ThemedComponent } from '../../../shared/theme-support/themed.component'; +import { ItemStatusComponent } from './item-status.component'; + +@Component({ + selector: 'ds-themed-item-status', + styleUrls: [], + templateUrl: '../../../shared/theme-support/themed.component.html', +}) +export class ThemedItemStatusComponent extends ThemedComponent { + protected getComponentName(): string { + return 'ItemStatusComponent'; + } + + protected importThemedComponent(themeName: string): Promise { + return import(`../../../../themes/${themeName}/app/item-page/edit-item-page/item-status/item-status.component`); + } + + protected importUnthemedComponent(): Promise { + return import('./item-status.component'); + } + +} diff --git a/src/app/item-page/field-components/collections/collections.component.html b/src/app/item-page/field-components/collections/collections.component.html index ac68ae1c31..27ebb41d61 100644 --- a/src/app/item-page/field-components/collections/collections.component.html +++ b/src/app/item-page/field-components/collections/collections.component.html @@ -1,7 +1,7 @@

    diff --git a/src/app/item-page/field-components/collections/collections.component.spec.ts b/src/app/item-page/field-components/collections/collections.component.spec.ts index c293109ba6..8ea5219308 100644 --- a/src/app/item-page/field-components/collections/collections.component.spec.ts +++ b/src/app/item-page/field-components/collections/collections.component.spec.ts @@ -12,6 +12,8 @@ import { CollectionsComponent } from './collections.component'; import { buildPaginatedList, PaginatedList } from '../../../core/data/paginated-list.model'; import { PageInfo } from '../../../core/shared/page-info.model'; import { FindListOptions } from '../../../core/data/find-list-options.model'; +import { DSONameService } from '../../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../../shared/mocks/dso-name.service.mock'; const createMockCollection = (id: string) => Object.assign(new Collection(), { id: id, @@ -46,6 +48,7 @@ describe('CollectionsComponent', () => { imports: [TranslateModule.forRoot()], declarations: [ CollectionsComponent ], providers: [ + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: RemoteDataBuildService, useValue: getMockRemoteDataBuildService()}, { provide: CollectionDataService, useValue: collectionDataService }, ], diff --git a/src/app/item-page/field-components/collections/collections.component.ts b/src/app/item-page/field-components/collections/collections.component.ts index 6c7053b25d..78d7c985a3 100644 --- a/src/app/item-page/field-components/collections/collections.component.ts +++ b/src/app/item-page/field-components/collections/collections.component.ts @@ -1,4 +1,4 @@ -import { Component, Input, OnInit } from '@angular/core'; +import { Component, Input, OnInit, ChangeDetectorRef } from '@angular/core'; import { BehaviorSubject, combineLatest, Observable } from 'rxjs'; import {map, scan, startWith, switchMap, tap, withLatestFrom} from 'rxjs/operators'; import { CollectionDataService } from '../../../core/data/collection-data.service'; @@ -14,6 +14,7 @@ import { getPaginatedListPayload, } from '../../../core/shared/operators'; import { FindListOptions } from '../../../core/data/find-list-options.model'; +import { DSONameService } from '../../../core/breadcrumbs/dso-name.service'; /** * This component renders the parent collections section of the item @@ -65,8 +66,11 @@ export class CollectionsComponent implements OnInit { */ collections$: Observable; - constructor(private cds: CollectionDataService) { - + constructor( + private cds: CollectionDataService, + public dsoNameService: DSONameService, + protected cdr: ChangeDetectorRef, + ) { } ngOnInit(): void { @@ -114,6 +118,7 @@ export class CollectionsComponent implements OnInit { return [owningCollection, ...mappedCollections].filter(collection => hasValue(collection)); }), ); + this.cdr.detectChanges(); } handleLoadMore() { diff --git a/src/app/item-page/field-components/metadata-values/metadata-values.component.ts b/src/app/item-page/field-components/metadata-values/metadata-values.component.ts index 49ce453fbe..cbbae9006d 100644 --- a/src/app/item-page/field-components/metadata-values/metadata-values.component.ts +++ b/src/app/item-page/field-components/metadata-values/metadata-values.component.ts @@ -3,6 +3,7 @@ import { MetadataValue } from '../../../core/shared/metadata.models'; import { APP_CONFIG, AppConfig } from '../../../../config/app-config.interface'; import { BrowseDefinition } from '../../../core/shared/browse-definition.model'; import { hasValue } from '../../../shared/empty.util'; +import { VALUE_LIST_BROWSE_DEFINITION } from '../../../core/shared/value-list-browse-definition.resource-type'; /** * This component renders the configured 'values' into the ds-metadata-field-wrapper component. @@ -84,7 +85,7 @@ export class MetadataValuesComponent implements OnChanges { */ getQueryParams(value) { let queryParams = {startsWith: value}; - if (this.browseDefinition.metadataBrowse) { + if (this.browseDefinition.getRenderType() === VALUE_LIST_BROWSE_DEFINITION.value) { return {value: value}; } return queryParams; diff --git a/src/app/item-page/full/field-components/file-section/full-file-section.component.html b/src/app/item-page/full/field-components/file-section/full-file-section.component.html index f474c666f2..8b8603011d 100644 --- a/src/app/item-page/full/field-components/file-section/full-file-section.component.html +++ b/src/app/item-page/full/field-components/file-section/full-file-section.component.html @@ -13,12 +13,12 @@
    - +
    {{"item.page.filesection.name" | translate}}
    -
    {{file.name}}
    +
    {{ dsoNameService.getName(file) }}
    {{"item.page.filesection.size" | translate}}
    {{(file.sizeBytes) | dsFileSize }}
    @@ -27,9 +27,10 @@
    {{"item.page.filesection.format" | translate}}
    {{(file.format | async)?.payload?.description}}
    - +
    {{"item.page.filesection.description" | translate}}
    {{file.firstMetadataValue("dc.description")}}
    +
    @@ -55,12 +56,12 @@
    - +
    {{"item.page.filesection.name" | translate}}
    -
    {{file.name}}
    +
    {{ dsoNameService.getName(file) }}
    {{"item.page.filesection.size" | translate}}
    {{(file.sizeBytes) | dsFileSize }}
    diff --git a/src/app/item-page/full/field-components/file-section/full-file-section.component.ts b/src/app/item-page/full/field-components/file-section/full-file-section.component.ts index 3be0d58c81..d34edeb025 100644 --- a/src/app/item-page/full/field-components/file-section/full-file-section.component.ts +++ b/src/app/item-page/full/field-components/file-section/full-file-section.component.ts @@ -1,4 +1,4 @@ -import { Component, Inject, Input, OnInit } from '@angular/core'; +import { Component, Inject, Input, OnDestroy, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import { BitstreamDataService } from '../../../../core/data/bitstream-data.service'; @@ -14,6 +14,7 @@ import { NotificationsService } from '../../../../shared/notifications/notificat import { TranslateService } from '@ngx-translate/core'; import { hasValue, isEmpty } from '../../../../shared/empty.util'; import { PaginationService } from '../../../../core/pagination/pagination.service'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; import { AppConfig, APP_CONFIG } from 'src/config/app-config.interface'; /** @@ -26,7 +27,7 @@ import { AppConfig, APP_CONFIG } from 'src/config/app-config.interface'; styleUrls: ['./full-file-section.component.scss'], templateUrl: './full-file-section.component.html' }) -export class FullFileSectionComponent extends FileSectionComponent implements OnInit { +export class FullFileSectionComponent extends FileSectionComponent implements OnDestroy, OnInit { @Input() item: Item; @@ -52,9 +53,10 @@ export class FullFileSectionComponent extends FileSectionComponent implements On protected notificationsService: NotificationsService, protected translateService: TranslateService, protected paginationService: PaginationService, + public dsoNameService: DSONameService, @Inject(APP_CONFIG) protected appConfig: AppConfig ) { - super(bitstreamDataService, notificationsService, translateService, appConfig); + super(bitstreamDataService, notificationsService, translateService, dsoNameService, appConfig); } ngOnInit(): void { diff --git a/src/app/item-page/full/full-item-page.component.spec.ts b/src/app/item-page/full/full-item-page.component.spec.ts index 53e36be1d1..9fc078c2cd 100644 --- a/src/app/item-page/full/full-item-page.component.spec.ts +++ b/src/app/item-page/full/full-item-page.component.spec.ts @@ -2,7 +2,7 @@ import { ComponentFixture, fakeAsync, TestBed, waitForAsync } from '@angular/cor import { ItemDataService } from '../../core/data/item-data.service'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { TranslateLoaderMock } from '../../shared/mocks/translate-loader.mock'; -import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA, PLATFORM_ID } from '@angular/core'; import { TruncatePipe } from '../../shared/utils/truncate.pipe'; import { FullItemPageComponent } from './full-item-page.component'; import { MetadataService } from '../../core/metadata/metadata.service'; @@ -20,6 +20,9 @@ import { createPaginatedList } from '../../shared/testing/utils.test'; import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service'; import { createRelationshipsObservable } from '../simple/item-types/shared/item.component.spec'; import { RemoteData } from '../../core/data/remote-data'; +import { ServerResponseService } from '../../core/services/server-response.service'; +import { SignpostingDataService } from '../../core/data/signposting-data.service'; +import { LinkHeadService } from '../../core/services/link-head.service'; const mockItem: Item = Object.assign(new Item(), { bundles: createSuccessfulRemoteDataObject$(createPaginatedList([])), @@ -55,8 +58,21 @@ describe('FullItemPageComponent', () => { let routeStub: ActivatedRouteStub; let routeData; let authorizationDataService: AuthorizationDataService; + let serverResponseService: jasmine.SpyObj; + let signpostingDataService: jasmine.SpyObj; + let linkHeadService: jasmine.SpyObj; + const mocklink = { + href: 'http://test.org', + rel: 'test', + type: 'test' + }; + const mocklink2 = { + href: 'http://test2.org', + rel: 'test', + type: 'test' + }; beforeEach(waitForAsync(() => { authService = jasmine.createSpyObj('authService', { @@ -76,6 +92,19 @@ describe('FullItemPageComponent', () => { isAuthorized: observableOf(false), }); + serverResponseService = jasmine.createSpyObj('ServerResponseService', { + setHeader: jasmine.createSpy('setHeader'), + }); + + signpostingDataService = jasmine.createSpyObj('SignpostingDataService', { + getLinks: observableOf([mocklink, mocklink2]), + }); + + linkHeadService = jasmine.createSpyObj('LinkHeadService', { + addTag: jasmine.createSpy('setHeader'), + removeTag: jasmine.createSpy('removeTag'), + }); + TestBed.configureTestingModule({ imports: [TranslateModule.forRoot({ loader: { @@ -90,8 +119,11 @@ describe('FullItemPageComponent', () => { { provide: MetadataService, useValue: metadataServiceStub }, { provide: AuthService, useValue: authService }, { provide: AuthorizationDataService, useValue: authorizationDataService }, + { provide: ServerResponseService, useValue: serverResponseService }, + { provide: SignpostingDataService, useValue: signpostingDataService }, + { provide: LinkHeadService, useValue: linkHeadService }, + { provide: PLATFORM_ID, useValue: 'server' } ], - schemas: [NO_ERRORS_SCHEMA] }).overrideComponent(FullItemPageComponent, { set: { changeDetection: ChangeDetectionStrategy.Default } @@ -143,6 +175,11 @@ describe('FullItemPageComponent', () => { const objectLoader = fixture.debugElement.query(By.css('.full-item-info')); expect(objectLoader.nativeElement).not.toBeNull(); }); + + it('should add the signposting links', () => { + expect(serverResponseService.setHeader).toHaveBeenCalled(); + expect(linkHeadService.addTag).toHaveBeenCalledTimes(2); + }); }); describe('when the item is withdrawn and the user is not an admin', () => { beforeEach(() => { @@ -167,6 +204,11 @@ describe('FullItemPageComponent', () => { const objectLoader = fixture.debugElement.query(By.css('.full-item-info')); expect(objectLoader).not.toBeNull(); }); + + it('should add the signposting links', () => { + expect(serverResponseService.setHeader).toHaveBeenCalled(); + expect(linkHeadService.addTag).toHaveBeenCalledTimes(2); + }); }); describe('when the item is not withdrawn and the user is not an admin', () => { @@ -179,5 +221,10 @@ describe('FullItemPageComponent', () => { const objectLoader = fixture.debugElement.query(By.css('.full-item-info')); expect(objectLoader).not.toBeNull(); }); + + it('should add the signposting links', () => { + expect(serverResponseService.setHeader).toHaveBeenCalled(); + expect(linkHeadService.addTag).toHaveBeenCalledTimes(2); + }); }); }); diff --git a/src/app/item-page/full/full-item-page.component.ts b/src/app/item-page/full/full-item-page.component.ts index 118e436004..31dd2c5fc2 100644 --- a/src/app/item-page/full/full-item-page.component.ts +++ b/src/app/item-page/full/full-item-page.component.ts @@ -1,5 +1,5 @@ import { filter, map } from 'rxjs/operators'; -import { ChangeDetectionStrategy, Component, OnDestroy, OnInit } from '@angular/core'; +import { ChangeDetectionStrategy, Component, Inject, OnDestroy, OnInit, PLATFORM_ID } from '@angular/core'; import { ActivatedRoute, Data, Router } from '@angular/router'; import { BehaviorSubject, Observable } from 'rxjs'; @@ -16,7 +16,9 @@ import { hasValue } from '../../shared/empty.util'; import { AuthService } from '../../core/auth/auth.service'; import { Location } from '@angular/common'; import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service'; - +import { ServerResponseService } from '../../core/services/server-response.service'; +import { SignpostingDataService } from '../../core/data/signposting-data.service'; +import { LinkHeadService } from '../../core/services/link-head.service'; /** * This component renders a full item page. @@ -43,13 +45,19 @@ export class FullItemPageComponent extends ItemPageComponent implements OnInit, subs = []; - constructor(protected route: ActivatedRoute, - router: Router, - items: ItemDataService, - authService: AuthService, - authorizationService: AuthorizationDataService, - private _location: Location) { - super(route, router, items, authService, authorizationService); + constructor( + protected route: ActivatedRoute, + protected router: Router, + protected items: ItemDataService, + protected authService: AuthService, + protected authorizationService: AuthorizationDataService, + protected _location: Location, + protected responseService: ServerResponseService, + protected signpostingDataService: SignpostingDataService, + protected linkHeadService: LinkHeadService, + @Inject(PLATFORM_ID) protected platformId: string, + ) { + super(route, router, items, authService, authorizationService, responseService, signpostingDataService, linkHeadService, platformId); } /*** AoT inheritance fix, will hopefully be resolved in the near future **/ diff --git a/src/app/item-page/media-viewer/media-viewer-video/media-viewer-video.component.html b/src/app/item-page/media-viewer/media-viewer-video/media-viewer-video.component.html index 73f27e4d81..3217680815 100644 --- a/src/app/item-page/media-viewer/media-viewer-video/media-viewer-video.component.html +++ b/src/app/item-page/media-viewer/media-viewer-video/media-viewer-video.component.html @@ -47,7 +47,7 @@ class="list-element" (click)="selectedMedia(indexOfelement)" > - {{ item.bitstream.name }} + {{ dsoNameService.getName(item.bitstream) }}
    diff --git a/src/app/item-page/media-viewer/media-viewer-video/media-viewer-video.component.ts b/src/app/item-page/media-viewer/media-viewer-video/media-viewer-video.component.ts index 8b8b4d1531..52cd3cac34 100644 --- a/src/app/item-page/media-viewer/media-viewer-video/media-viewer-video.component.ts +++ b/src/app/item-page/media-viewer/media-viewer-video/media-viewer-video.component.ts @@ -1,5 +1,6 @@ import { Component, Input } from '@angular/core'; import { MediaViewerItem } from '../../../core/shared/media-viewer-item.model'; +import { DSONameService } from '../../../core/breadcrumbs/dso-name.service'; import { languageHelper } from './language-helper'; import { CaptionInfo } from './caption-info'; import { Bitstream } from 'src/app/core/shared/bitstream.model'; @@ -26,6 +27,11 @@ export class MediaViewerVideoComponent { audio: './assets/images/replacement_audio.svg', }; + constructor( + public dsoNameService: DSONameService, + ) { + } + /** * This method check if there is caption file for the media * The caption file name is the media name plus "-" following two letter diff --git a/src/app/item-page/orcid-page/orcid-queue/orcid-queue.component.html b/src/app/item-page/orcid-page/orcid-queue/orcid-queue.component.html index 9358bcf835..6ba318f7fd 100644 --- a/src/app/item-page/orcid-page/orcid-queue/orcid-queue.component.html +++ b/src/app/item-page/orcid-page/orcid-queue/orcid-queue.component.html @@ -34,11 +34,13 @@
    diff --git a/src/app/item-page/orcid-page/orcid-sync-settings/orcid-sync-settings.component.spec.ts b/src/app/item-page/orcid-page/orcid-sync-settings/orcid-sync-settings.component.spec.ts index cd466ae4a4..f2fa9d2440 100644 --- a/src/app/item-page/orcid-page/orcid-sync-settings/orcid-sync-settings.component.spec.ts +++ b/src/app/item-page/orcid-page/orcid-sync-settings/orcid-sync-settings.component.spec.ts @@ -1,6 +1,6 @@ import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; -import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; +import { UntypedFormControl, UntypedFormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; import { RouterTestingModule } from '@angular/router/testing'; import { By } from '@angular/platform-browser'; @@ -26,7 +26,7 @@ describe('OrcidSyncSettingsComponent test suite', () => { let scheduler: TestScheduler; let researcherProfileService: jasmine.SpyObj; let notificationsService; - let formGroup: FormGroup; + let formGroup: UntypedFormGroup; const mockResearcherProfile: ResearcherProfile = Object.assign(new ResearcherProfile(), { id: 'test-id', @@ -186,12 +186,12 @@ describe('OrcidSyncSettingsComponent test suite', () => { beforeEach(() => { scheduler = getTestScheduler(); notificationsService = (comp as any).notificationsService; - formGroup = new FormGroup({ - syncMode: new FormControl('MANUAL'), - syncFundings: new FormControl('ALL'), - syncPublications: new FormControl('ALL'), - syncProfile_BIOGRAPHICAL: new FormControl(true), - syncProfile_IDENTIFIERS: new FormControl(true), + formGroup = new UntypedFormGroup({ + syncMode: new UntypedFormControl('MANUAL'), + syncFundings: new UntypedFormControl('ALL'), + syncPublications: new UntypedFormControl('ALL'), + syncProfile_BIOGRAPHICAL: new UntypedFormControl(true), + syncProfile_IDENTIFIERS: new UntypedFormControl(true), }); spyOn(comp.settingsUpdated, 'emit'); }); diff --git a/src/app/item-page/orcid-page/orcid-sync-settings/orcid-sync-settings.component.ts b/src/app/item-page/orcid-page/orcid-sync-settings/orcid-sync-settings.component.ts index 494075c0f0..0bcbc295ac 100644 --- a/src/app/item-page/orcid-page/orcid-sync-settings/orcid-sync-settings.component.ts +++ b/src/app/item-page/orcid-page/orcid-sync-settings/orcid-sync-settings.component.ts @@ -1,5 +1,5 @@ import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { TranslateService } from '@ngx-translate/core'; import { Operation } from 'fast-json-patch'; @@ -127,7 +127,7 @@ export class OrcidSyncSettingsComponent implements OnInit { * * @param form The form group */ - onSubmit(form: FormGroup): void { + onSubmit(form: UntypedFormGroup): void { const operations: Operation[] = []; this.fillOperationsFor(operations, '/orcid/mode', form.value.syncMode); this.fillOperationsFor(operations, '/orcid/publications', form.value.syncPublications); diff --git a/src/app/item-page/simple/field-components/file-section/file-section.component.html b/src/app/item-page/simple/field-components/file-section/file-section.component.html index 8e4f4dfcb0..cd708510e8 100644 --- a/src/app/item-page/simple/field-components/file-section/file-section.component.html +++ b/src/app/item-page/simple/field-components/file-section/file-section.component.html @@ -2,16 +2,16 @@
    - {{file?.name}} - ({{(file?.sizeBytes) | dsFileSize }}) + {{ dsoNameService.getName(file) }} + ({{(file?.sizeBytes) | dsFileSize }})
    - {{'item.page.bitstreams.view-more' | translate}} +
    - {{'item.page.bitstreams.collapse' | translate}} +
    diff --git a/src/app/item-page/simple/field-components/file-section/file-section.component.ts b/src/app/item-page/simple/field-components/file-section/file-section.component.ts index 08e792fc8b..3c41731c5f 100644 --- a/src/app/item-page/simple/field-components/file-section/file-section.component.ts +++ b/src/app/item-page/simple/field-components/file-section/file-section.component.ts @@ -11,6 +11,7 @@ import { NotificationsService } from '../../../../shared/notifications/notificat import { TranslateService } from '@ngx-translate/core'; import { getFirstCompletedRemoteData } from '../../../../core/shared/operators'; import { AppConfig, APP_CONFIG } from 'src/config/app-config.interface'; +import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service'; /** * This component renders the file section of the item @@ -42,6 +43,7 @@ export class FileSectionComponent implements OnInit { protected bitstreamDataService: BitstreamDataService, protected notificationsService: NotificationsService, protected translateService: TranslateService, + public dsoNameService: DSONameService, @Inject(APP_CONFIG) protected appConfig: AppConfig ) { this.pageSize = this.appConfig.item.bitstream.pageSize; diff --git a/src/app/item-page/simple/item-page.component.spec.ts b/src/app/item-page/simple/item-page.component.spec.ts index 9b0e87939d..b3202108f4 100644 --- a/src/app/item-page/simple/item-page.component.spec.ts +++ b/src/app/item-page/simple/item-page.component.spec.ts @@ -2,7 +2,7 @@ import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { TranslateLoaderMock } from '../../shared/mocks/translate-loader.mock'; import { ItemDataService } from '../../core/data/item-data.service'; -import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA, PLATFORM_ID } from '@angular/core'; import { ItemPageComponent } from './item-page.component'; import { ActivatedRoute, Router } from '@angular/router'; import { ActivatedRouteStub } from '../../shared/testing/active-router.stub'; @@ -22,6 +22,10 @@ import { import { AuthService } from '../../core/auth/auth.service'; import { createPaginatedList } from '../../shared/testing/utils.test'; import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service'; +import { ServerResponseService } from '../../core/services/server-response.service'; +import { SignpostingDataService } from '../../core/data/signposting-data.service'; +import { LinkDefinition, LinkHeadService } from '../../core/services/link-head.service'; +import { SignpostingLink } from '../../core/data/signposting-links.model'; const mockItem: Item = Object.assign(new Item(), { bundles: createSuccessfulRemoteDataObject$(createPaginatedList([])), @@ -36,11 +40,28 @@ const mockWithdrawnItem: Item = Object.assign(new Item(), { isWithdrawn: true }); +const mocklink = { + href: 'http://test.org', + rel: 'rel1', + type: 'type1' +}; + +const mocklink2 = { + href: 'http://test2.org', + rel: 'rel2', + type: undefined +}; + +const mockSignpostingLinks: SignpostingLink[] = [mocklink, mocklink2]; + describe('ItemPageComponent', () => { let comp: ItemPageComponent; let fixture: ComponentFixture; let authService: AuthService; let authorizationDataService: AuthorizationDataService; + let serverResponseService: jasmine.SpyObj; + let signpostingDataService: jasmine.SpyObj; + let linkHeadService: jasmine.SpyObj; const mockMetadataService = { /* eslint-disable no-empty,@typescript-eslint/no-empty-function */ @@ -60,6 +81,18 @@ describe('ItemPageComponent', () => { authorizationDataService = jasmine.createSpyObj('authorizationDataService', { isAuthorized: observableOf(false), }); + serverResponseService = jasmine.createSpyObj('ServerResponseService', { + setHeader: jasmine.createSpy('setHeader'), + }); + + signpostingDataService = jasmine.createSpyObj('SignpostingDataService', { + getLinks: observableOf([mocklink, mocklink2]), + }); + + linkHeadService = jasmine.createSpyObj('LinkHeadService', { + addTag: jasmine.createSpy('setHeader'), + removeTag: jasmine.createSpy('removeTag'), + }); TestBed.configureTestingModule({ imports: [TranslateModule.forRoot({ @@ -76,6 +109,10 @@ describe('ItemPageComponent', () => { { provide: Router, useValue: {} }, { provide: AuthService, useValue: authService }, { provide: AuthorizationDataService, useValue: authorizationDataService }, + { provide: ServerResponseService, useValue: serverResponseService }, + { provide: SignpostingDataService, useValue: signpostingDataService }, + { provide: LinkHeadService, useValue: linkHeadService }, + { provide: PLATFORM_ID, useValue: 'server' }, ], schemas: [NO_ERRORS_SCHEMA] @@ -126,6 +163,33 @@ describe('ItemPageComponent', () => { const objectLoader = fixture.debugElement.query(By.css('ds-listable-object-component-loader')); expect(objectLoader.nativeElement).toBeDefined(); }); + + it('should add the signposting links', () => { + expect(serverResponseService.setHeader).toHaveBeenCalled(); + expect(linkHeadService.addTag).toHaveBeenCalledTimes(2); + }); + + + it('should add link tags correctly', () => { + + expect(comp.signpostingLinks).toEqual([mocklink, mocklink2]); + + // Check if linkHeadService.addTag() was called with the correct arguments + expect(linkHeadService.addTag).toHaveBeenCalledTimes(mockSignpostingLinks.length); + let expected: LinkDefinition = mockSignpostingLinks[0] as LinkDefinition; + expect(linkHeadService.addTag).toHaveBeenCalledWith(expected); + expected = { + href: 'http://test2.org', + rel: 'rel2' + }; + expect(linkHeadService.addTag).toHaveBeenCalledWith(expected); + }); + + it('should set Link header on the server', () => { + + expect(serverResponseService.setHeader).toHaveBeenCalledWith('Link', ' ; rel="rel1" ; type="type1" , ; rel="rel2" '); + }); + }); describe('when the item is withdrawn and the user is not an admin', () => { beforeEach(() => { @@ -150,6 +214,11 @@ describe('ItemPageComponent', () => { const objectLoader = fixture.debugElement.query(By.css('ds-listable-object-component-loader')); expect(objectLoader.nativeElement).toBeDefined(); }); + + it('should add the signposting links', () => { + expect(serverResponseService.setHeader).toHaveBeenCalled(); + expect(linkHeadService.addTag).toHaveBeenCalledTimes(2); + }); }); describe('when the item is not withdrawn and the user is not an admin', () => { @@ -162,6 +231,11 @@ describe('ItemPageComponent', () => { const objectLoader = fixture.debugElement.query(By.css('ds-listable-object-component-loader')); expect(objectLoader.nativeElement).toBeDefined(); }); + + it('should add the signposting links', () => { + expect(serverResponseService.setHeader).toHaveBeenCalled(); + expect(linkHeadService.addTag).toHaveBeenCalledTimes(2); + }); }); }); diff --git a/src/app/item-page/simple/item-page.component.ts b/src/app/item-page/simple/item-page.component.ts index 6e0db386db..b9be6bebfb 100644 --- a/src/app/item-page/simple/item-page.component.ts +++ b/src/app/item-page/simple/item-page.component.ts @@ -1,8 +1,9 @@ -import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; +import { ChangeDetectionStrategy, Component, Inject, OnDestroy, OnInit, PLATFORM_ID } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; +import { isPlatformServer } from '@angular/common'; import { Observable } from 'rxjs'; -import { map } from 'rxjs/operators'; +import { map, take } from 'rxjs/operators'; import { ItemDataService } from '../../core/data/item-data.service'; import { RemoteData } from '../../core/data/remote-data'; @@ -15,6 +16,11 @@ import { getItemPageRoute } from '../item-page-routing-paths'; import { redirectOn4xx } from '../../core/shared/authorized.operators'; import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service'; import { FeatureID } from '../../core/data/feature-authorization/feature-id'; +import { ServerResponseService } from '../../core/services/server-response.service'; +import { SignpostingDataService } from '../../core/data/signposting-data.service'; +import { SignpostingLink } from '../../core/data/signposting-links.model'; +import { isNotEmpty } from '../../shared/empty.util'; +import { LinkDefinition, LinkHeadService } from '../../core/services/link-head.service'; /** * This component renders a simple item page. @@ -28,7 +34,7 @@ import { FeatureID } from '../../core/data/feature-authorization/feature-id'; changeDetection: ChangeDetectionStrategy.OnPush, animations: [fadeInOut] }) -export class ItemPageComponent implements OnInit { +export class ItemPageComponent implements OnInit, OnDestroy { /** * The item's id @@ -57,13 +63,23 @@ export class ItemPageComponent implements OnInit { itemUrl: string; + /** + * Contains a list of SignpostingLink related to the item + */ + signpostingLinks: SignpostingLink[] = []; + constructor( protected route: ActivatedRoute, - private router: Router, - private items: ItemDataService, - private authService: AuthService, - private authorizationService: AuthorizationDataService + protected router: Router, + protected items: ItemDataService, + protected authService: AuthService, + protected authorizationService: AuthorizationDataService, + protected responseService: ServerResponseService, + protected signpostingDataService: SignpostingDataService, + protected linkHeadService: LinkHeadService, + @Inject(PLATFORM_ID) protected platformId: string ) { + this.initPageLinks(); } /** @@ -82,4 +98,42 @@ export class ItemPageComponent implements OnInit { this.isAdmin$ = this.authorizationService.isAuthorized(FeatureID.AdministratorOf); } + + /** + * Create page links if any are retrieved by signposting endpoint + * + * @private + */ + private initPageLinks(): void { + this.route.params.subscribe(params => { + this.signpostingDataService.getLinks(params.id).pipe(take(1)).subscribe((signpostingLinks: SignpostingLink[]) => { + let links = ''; + this.signpostingLinks = signpostingLinks; + + signpostingLinks.forEach((link: SignpostingLink) => { + links = links + (isNotEmpty(links) ? ', ' : '') + `<${link.href}> ; rel="${link.rel}"` + (isNotEmpty(link.type) ? ` ; type="${link.type}" ` : ' '); + let tag: LinkDefinition = { + href: link.href, + rel: link.rel + }; + if (isNotEmpty(link.type)) { + tag = Object.assign(tag, { + type: link.type + }); + } + this.linkHeadService.addTag(tag); + }); + + if (isPlatformServer(this.platformId)) { + this.responseService.setHeader('Link', links); + } + }); + }); + } + + ngOnDestroy(): void { + this.signpostingLinks.forEach((link: SignpostingLink) => { + this.linkHeadService.removeTag(`href='${link.href}'`); + }); + } } diff --git a/src/app/item-page/simple/item-types/publication/publication.component.html b/src/app/item-page/simple/item-types/publication/publication.component.html index dcf243c63b..3749f63964 100644 --- a/src/app/item-page/simple/item-types/publication/publication.component.html +++ b/src/app/item-page/simple/item-types/publication/publication.component.html @@ -17,7 +17,7 @@
    - +
    diff --git a/src/app/item-page/simple/item-types/untyped-item/untyped-item.component.html b/src/app/item-page/simple/item-types/untyped-item/untyped-item.component.html index ff98057334..904b7e039c 100644 --- a/src/app/item-page/simple/item-types/untyped-item/untyped-item.component.html +++ b/src/app/item-page/simple/item-types/untyped-item/untyped-item.component.html @@ -18,7 +18,7 @@
    - +
    diff --git a/src/app/item-page/simple/metadata-representation-list/metadata-representation-list.component.html b/src/app/item-page/simple/metadata-representation-list/metadata-representation-list.component.html index 65660eaa34..efbe9206d1 100644 --- a/src/app/item-page/simple/metadata-representation-list/metadata-representation-list.component.html +++ b/src/app/item-page/simple/metadata-representation-list/metadata-representation-list.component.html @@ -7,12 +7,12 @@
    - {{'item.page.related-items.view-more' | - translate:{ amount: (total - (objects.length * incrementBy) < incrementBy) ? total - (objects.length * incrementBy) : incrementBy } }} +
    - {{'item.page.related-items.view-less' | - translate:{ amount: representations?.length } }} +
    diff --git a/src/app/item-page/simple/related-items/related-items.component.html b/src/app/item-page/simple/related-items/related-items.component.html index 0d1e14941d..bee1f345fd 100644 --- a/src/app/item-page/simple/related-items/related-items.component.html +++ b/src/app/item-page/simple/related-items/related-items.component.html @@ -7,12 +7,12 @@
    - {{'item.page.related-items.view-more' | - translate:{ amount: (itemsRD?.payload?.totalElements - (incrementBy * objects.length) < incrementBy) ? itemsRD?.payload?.totalElements - (incrementBy * objects.length) : incrementBy } }} +
    - {{'item.page.related-items.view-less' | - translate:{ amount: itemsRD?.payload?.page?.length } }} +
    diff --git a/src/app/item-page/versions/item-versions.component.spec.ts b/src/app/item-page/versions/item-versions.component.spec.ts index 999176d996..e46f1585d7 100644 --- a/src/app/item-page/versions/item-versions.component.spec.ts +++ b/src/app/item-page/versions/item-versions.component.spec.ts @@ -18,7 +18,7 @@ import { PaginationServiceStub } from '../../shared/testing/pagination-service.s import { AuthService } from '../../core/auth/auth.service'; import { VersionDataService } from '../../core/data/version-data.service'; import { ItemDataService } from '../../core/data/item-data.service'; -import { FormBuilder, FormsModule, ReactiveFormsModule } from '@angular/forms'; +import { UntypedFormBuilder, FormsModule, ReactiveFormsModule } from '@angular/forms'; import { NotificationsService } from '../../shared/notifications/notifications.service'; import { NotificationsServiceStub } from '../../shared/testing/notifications-service.stub'; import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service'; @@ -140,7 +140,7 @@ describe('ItemVersionsComponent', () => { imports: [TranslateModule.forRoot(), CommonModule, FormsModule, ReactiveFormsModule, BrowserModule, ItemSharedModule], providers: [ {provide: PaginationService, useValue: new PaginationServiceStub()}, - {provide: FormBuilder, useValue: new FormBuilder()}, + {provide: UntypedFormBuilder, useValue: new UntypedFormBuilder()}, {provide: NotificationsService, useValue: new NotificationsServiceStub()}, {provide: AuthService, useValue: authenticationServiceSpy}, {provide: AuthorizationDataService, useValue: authorizationServiceSpy}, diff --git a/src/app/item-page/versions/item-versions.component.ts b/src/app/item-page/versions/item-versions.component.ts index e0fc623f49..700a35552c 100644 --- a/src/app/item-page/versions/item-versions.component.ts +++ b/src/app/item-page/versions/item-versions.component.ts @@ -1,4 +1,4 @@ -import { Component, Input, OnInit } from '@angular/core'; +import { Component, Input, OnDestroy, OnInit } from '@angular/core'; import { Item } from '../../core/shared/item.model'; import { Version } from '../../core/shared/version.model'; import { RemoteData } from '../../core/data/remote-data'; @@ -32,7 +32,7 @@ import { getItemPageRoute, getItemVersionRoute } from '../item-page-routing-paths'; -import { FormBuilder } from '@angular/forms'; +import { UntypedFormBuilder } from '@angular/forms'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import { ItemVersionsSummaryModalComponent } from './item-versions-summary-modal/item-versions-summary-modal.component'; import { NotificationsService } from '../../shared/notifications/notifications.service'; @@ -58,7 +58,7 @@ import { ConfigurationDataService } from '../../core/data/configuration-data.ser /** * Component listing all available versions of the history the provided item is a part of */ -export class ItemVersionsComponent implements OnInit { +export class ItemVersionsComponent implements OnDestroy, OnInit { /** * The item to display a version history for @@ -171,7 +171,7 @@ export class ItemVersionsComponent implements OnInit { private versionService: VersionDataService, private itemService: ItemDataService, private paginationService: PaginationService, - private formBuilder: FormBuilder, + private formBuilder: UntypedFormBuilder, private modalService: NgbModal, private notificationsService: NotificationsService, private translateService: TranslateService, diff --git a/src/app/menu.resolver.ts b/src/app/menu.resolver.ts index 3ec1df85fd..70e2b6462f 100644 --- a/src/app/menu.resolver.ts +++ b/src/app/menu.resolver.ts @@ -47,6 +47,7 @@ import { import { ExportBatchSelectorComponent } from './shared/dso-selector/modal-wrappers/export-batch-selector/export-batch-selector.component'; +import { NOTIFICATIONS_RECITER_SUGGESTION_PATH } from './admin/admin-notifications/admin-notifications-routing-paths'; /** * Creates all of the app's menus @@ -532,6 +533,40 @@ export class MenuResolver implements Resolve { createSiteAdministratorMenuSections() { this.authorizationService.isAuthorized(FeatureID.AdministratorOf).subscribe((authorized) => { const menuList = [ + /* Notifications */ + { + id: 'notifications', + active: false, + visible: authorized, + model: { + type: MenuItemType.TEXT, + text: 'menu.section.notifications' + } as TextMenuItemModel, + icon: 'bell', + index: 4 + }, + { + id: 'notifications_quality-assurance', + parentID: 'notifications', + active: false, + visible: authorized, + model: { + type: MenuItemType.LINK, + text: 'menu.section.quality-assurance', + link: '/admin/notifications/quality-assurance' + } as LinkMenuItemModel, + }, + { + id: 'notifications_reciter', + parentID: 'notifications', + active: false, + visible: authorized, + model: { + type: MenuItemType.LINK, + text: 'menu.section.notifications_reciter', + link: '/admin/notifications/' + NOTIFICATIONS_RECITER_SUGGESTION_PATH + } as LinkMenuItemModel, + }, /* Admin Search */ { id: 'admin_search', @@ -659,6 +694,17 @@ export class MenuResolver implements Resolve { link: '/access-control/groups' } as LinkMenuItemModel, }, + { + id: 'access_control_bulk', + parentID: 'access_control', + active: false, + visible: isSiteAdmin, + model: { + type: MenuItemType.LINK, + text: 'menu.section.access_control_bulk', + link: '/access-control/bulk-access' + } as LinkMenuItemModel, + }, // TODO: enable this menu item once the feature has been implemented // { // id: 'access_control_authorizations', diff --git a/src/app/my-dspace-page/my-dspace-page.component.html b/src/app/my-dspace-page/my-dspace-page.component.html index ea5784170f..c5e49b0cec 100644 --- a/src/app/my-dspace-page/my-dspace-page.component.html +++ b/src/app/my-dspace-page/my-dspace-page.component.html @@ -1,5 +1,6 @@
    +
    ; @@ -66,30 +68,35 @@ describe('NavbarComponent', () => { beforeEach(waitForAsync(() => { browseDefinitions = [ Object.assign( - new BrowseDefinition(), { + new FlatBrowseDefinition(), { id: 'title', dataType: BrowseByDataType.Title, } ), Object.assign( - new BrowseDefinition(), { + new FlatBrowseDefinition(), { id: 'dateissued', dataType: BrowseByDataType.Date, metadataKeys: ['dc.date.issued'] } ), Object.assign( - new BrowseDefinition(), { + new ValueListBrowseDefinition(), { id: 'author', dataType: BrowseByDataType.Metadata, } ), Object.assign( - new BrowseDefinition(), { + new ValueListBrowseDefinition(), { id: 'subject', dataType: BrowseByDataType.Metadata, } ), + Object.assign( + new HierarchicalBrowseDefinition(), { + id: 'srsc', + } + ), ]; initialState = { core: { diff --git a/src/app/process-page/detail/process-detail.component.html b/src/app/process-page/detail/process-detail.component.html index 29cbfc113f..5f905cbfff 100644 --- a/src/app/process-page/detail/process-detail.component.html +++ b/src/app/process-page/detail/process-detail.component.html @@ -1,10 +1,15 @@ -
    -
    -

    {{'process.detail.title' | translate:{ - id: process?.processId, - name: process?.scriptName - } }}

    +
    +
    +
    +

    + {{ 'process.detail.title' | translate:{ id: process?.processId, name: process?.scriptName } }} +

    +
    +
    + Refreshing in {{ seconds }}s +
    +
    {{ process?.scriptName }}
    @@ -17,10 +22,12 @@
    +
    - {{getFileName(file)}} - ({{(file?.sizeBytes) | dsFileSize }}) + {{getFileName(file)}} + ({{(file?.sizeBytes) | dsFileSize }}) +
    @@ -70,7 +77,7 @@ -
    +
    diff --git a/src/app/search-navbar/search-navbar.component.scss b/src/app/search-navbar/search-navbar.component.scss index d5f3d8d615..cf46c25d91 100644 --- a/src/app/search-navbar/search-navbar.component.scss +++ b/src/app/search-navbar/search-navbar.component.scss @@ -1,13 +1,14 @@ input[type="text"] { margin-top: calc(-0.5 * var(--bs-font-size-base)); background-color: #fff !important; + border-color: var(--ds-header-icon-color); &.collapsed { opacity: 0; } } -a.submit-icon { +.submit-icon { cursor: pointer; position: sticky; top: 0; diff --git a/src/app/search-navbar/search-navbar.component.ts b/src/app/search-navbar/search-navbar.component.ts index ccdaa27861..98e64f6e10 100644 --- a/src/app/search-navbar/search-navbar.component.ts +++ b/src/app/search-navbar/search-navbar.component.ts @@ -1,5 +1,5 @@ import { Component, ElementRef, ViewChild } from '@angular/core'; -import { FormBuilder } from '@angular/forms'; +import { UntypedFormBuilder } from '@angular/forms'; import { Router } from '@angular/router'; import { SearchService } from '../core/shared/search/search.service'; import { expandSearchInput } from '../shared/animations/slide'; @@ -24,7 +24,7 @@ export class SearchNavbarComponent { // Search input field @ViewChild('searchInput') searchField: ElementRef; - constructor(private formBuilder: FormBuilder, private router: Router, private searchService: SearchService) { + constructor(private formBuilder: UntypedFormBuilder, private router: Router, private searchService: SearchService) { this.searchForm = this.formBuilder.group(({ query: '', })); diff --git a/src/app/search-page/search-page.module.ts b/src/app/search-page/search-page.module.ts index 19fd9bd309..cc76d0427d 100644 --- a/src/app/search-page/search-page.module.ts +++ b/src/app/search-page/search-page.module.ts @@ -4,7 +4,6 @@ import { CoreModule } from '../core/core.module'; import { SharedModule } from '../shared/shared.module'; import { SidebarService } from '../shared/sidebar/sidebar.service'; import { ConfigurationSearchPageGuard } from './configuration-search-page.guard'; -import { SearchTrackerComponent } from './search-tracker.component'; import { StatisticsModule } from '../statistics/statistics.module'; import { SearchPageComponent } from './search-page.component'; import { SearchFilterService } from '../core/shared/search/search-filter.service'; @@ -16,7 +15,6 @@ import { SearchModule } from '../shared/search/search.module'; const components = [ SearchPageComponent, - SearchTrackerComponent, ThemedSearchPageComponent ]; diff --git a/src/app/search-page/search-tracker.component.html b/src/app/search-page/search-tracker.component.html deleted file mode 100644 index c0c0ffe181..0000000000 --- a/src/app/search-page/search-tracker.component.html +++ /dev/null @@ -1 +0,0 @@ -  diff --git a/src/app/search-page/search-tracker.component.scss b/src/app/search-page/search-tracker.component.scss deleted file mode 100644 index c76cafbe44..0000000000 --- a/src/app/search-page/search-tracker.component.scss +++ /dev/null @@ -1,3 +0,0 @@ -:host { - display: none -} diff --git a/src/app/search-page/search-tracker.component.ts b/src/app/search-page/search-tracker.component.ts deleted file mode 100644 index f766e6f669..0000000000 --- a/src/app/search-page/search-tracker.component.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { Component, Inject, OnInit } from '@angular/core'; -import { Angulartics2 } from 'angulartics2'; -import { map, switchMap } from 'rxjs/operators'; -import { SearchComponent } from '../shared/search/search.component'; -import { SidebarService } from '../shared/sidebar/sidebar.service'; -import { HostWindowService } from '../shared/host-window.service'; -import { SEARCH_CONFIG_SERVICE } from '../my-dspace-page/my-dspace-page.component'; -import { RouteService } from '../core/services/route.service'; -import { SearchConfigurationService } from '../core/shared/search/search-configuration.service'; -import { SearchService } from '../core/shared/search/search.service'; -import { PaginatedSearchOptions } from '../shared/search/models/paginated-search-options.model'; -import { SearchObjects } from '../shared/search/models/search-objects.model'; -import { Router } from '@angular/router'; -import { RemoteData } from '../core/data/remote-data'; -import { DSpaceObject } from '../core/shared/dspace-object.model'; -import { getFirstSucceededRemoteData } from '../core/shared/operators'; - -/** - * This component triggers a page view statistic - */ -@Component({ - selector: 'ds-search-tracker', - styleUrls: ['./search-tracker.component.scss'], - templateUrl: './search-tracker.component.html', - providers: [ - { - provide: SEARCH_CONFIG_SERVICE, - useClass: SearchConfigurationService - } - ] -}) -export class SearchTrackerComponent extends SearchComponent implements OnInit { - - constructor( - protected service: SearchService, - protected sidebarService: SidebarService, - protected windowService: HostWindowService, - @Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService, - protected routeService: RouteService, - public angulartics2: Angulartics2, - protected router: Router - ) { - super(service, sidebarService, windowService, searchConfigService, routeService, router); - } - - ngOnInit(): void { - // super.ngOnInit(); - this.getSearchOptions().pipe( - switchMap((options: PaginatedSearchOptions) => - this.service.searchEntries(options).pipe( - getFirstSucceededRemoteData(), - map((rd: RemoteData>) => ({ - config: options, - searchQueryResponse: rd.payload - })) - )), - ).subscribe(({ config, searchQueryResponse }) => { - const filters: { filter: string, operator: string, value: string, label: string; }[] = []; - const appliedFilters = searchQueryResponse.appliedFilters || []; - for (let i = 0, filtersLength = appliedFilters.length; i < filtersLength; i++) { - const appliedFilter = appliedFilters[i]; - filters.push(appliedFilter); - } - this.angulartics2.eventTrack.next({ - action: 'search', - properties: { - searchOptions: config, - page: { - size: config.pagination.size, // same as searchQueryResponse.page.elementsPerPage - totalElements: searchQueryResponse.pageInfo.totalElements, - totalPages: searchQueryResponse.pageInfo.totalPages, - number: config.pagination.currentPage, // same as searchQueryResponse.page.currentPage - }, - sort: { - by: config.sort.field, - order: config.sort.direction - }, - filters: filters, - }, - }); - }); - } -} diff --git a/src/app/shared/access-control-form-container/access-control-array-form/access-control-array-form.component.html b/src/app/shared/access-control-form-container/access-control-array-form/access-control-array-form.component.html new file mode 100644 index 0000000000..cd56904bd7 --- /dev/null +++ b/src/app/shared/access-control-form-container/access-control-array-form/access-control-array-form.component.html @@ -0,0 +1,111 @@ +
    +
    + {{'access-control-no-access-conditions-warning-message' | translate}} +
    + + +
    + +
    +
    + + + + {{'access-control-option-note' | translate}} + +
    + +
    + +
    + +
    + +
    +
    + + {{'access-control-option-start-date-note' | translate}} + +
    + +
    + +
    + +
    + +
    +
    + + {{'access-control-option-end-date-note' | translate}} + +
    +
    + +
    + +
    + + +
    +
    +
    +
    + + + +
    diff --git a/src/app/shared/access-control-form-container/access-control-array-form/access-control-array-form.component.scss b/src/app/shared/access-control-form-container/access-control-array-form/access-control-array-form.component.scss new file mode 100644 index 0000000000..43cc0789b2 --- /dev/null +++ b/src/app/shared/access-control-form-container/access-control-array-form/access-control-array-form.component.scss @@ -0,0 +1,7 @@ +.access-control-item { + display: grid; + grid-template-columns: 1fr 50px; + grid-gap: 10px; + padding-bottom: 15px; + border-bottom: 2px dotted grey; +} diff --git a/src/app/shared/access-control-form-container/access-control-array-form/access-control-array-form.component.spec.ts b/src/app/shared/access-control-form-container/access-control-array-form/access-control-array-form.component.spec.ts new file mode 100644 index 0000000000..964eb30de2 --- /dev/null +++ b/src/app/shared/access-control-form-container/access-control-array-form/access-control-array-form.component.spec.ts @@ -0,0 +1,116 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { AccessControlArrayFormComponent } from './access-control-array-form.component'; +import { FormsModule } from '@angular/forms'; +import { CommonModule } from '@angular/common'; +import { TranslateModule } from '@ngx-translate/core'; +import { NgbDatepickerModule } from '@ng-bootstrap/ng-bootstrap'; +import { DebugElement } from '@angular/core'; +import { By } from '@angular/platform-browser'; +import { ToDatePipe } from './to-date.pipe'; +import { SharedBrowseByModule } from '../../browse-by/shared-browse-by.module'; + +describe('AccessControlArrayFormComponent', () => { + let component: AccessControlArrayFormComponent; + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [ CommonModule, FormsModule, SharedBrowseByModule, TranslateModule.forRoot(), NgbDatepickerModule ], + declarations: [ AccessControlArrayFormComponent, ToDatePipe ] + }) + .compileComponents(); + }); + + beforeEach(() => { + fixture = TestBed.createComponent(AccessControlArrayFormComponent); + component = fixture.componentInstance; + component.dropdownOptions = [{name: 'Option1'}, {name: 'Option2'}] as any; + component.type = 'item'; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); + + it('should have only one empty control access item in the form', () => { + const accessControlItems = fixture.debugElement.queryAll(By.css('.access-control-item')); + expect(accessControlItems.length).toEqual(1); + }); + + it('should add access control item', () => { + component.addAccessControlItem(); + expect(component.form.accessControls.length).toEqual(2); + }); + + it('should remove access control item', () => { + expect(component.form.accessControls.length).toEqual(1); + + component.addAccessControlItem(); + expect(component.form.accessControls.length).toEqual(2); + + const id = component.form.accessControls[0].id; + component.removeAccessControlItem(id); + expect(component.form.accessControls.length).toEqual(1); + }); + + it('should reset form value', () => { + const item = { itemName: 'item1', startDate: '2022-01-01', endDate: '2022-02-01' }; + component.addAccessControlItem(item.itemName); + + // set value to item1 + component.accessControlChanged( + component.form.accessControls[1], + 'item1' + ); + + component.reset(); + expect(component.form.accessControls[1]?.itemName).toEqual(undefined); + }); + + + it('should display a select dropdown with options', () => { + component.enable(); + fixture.detectChanges(); + + const id = component.form.accessControls[0].id; + + const selectElement: DebugElement = fixture.debugElement.query(By.css(`select#accesscontroloption-${id}`)); + expect(selectElement).toBeTruthy(); + + const options = selectElement.nativeElement.querySelectorAll('option'); + expect(options.length).toEqual(3); // 2 options + default empty option + + expect(options[0].value).toEqual(''); + expect(options[1].value).toEqual('Option1'); + expect(options[2].value).toEqual('Option2'); + }); + + it('should add new access control items when clicking "Add more" button', () => { + component.enable(); + fixture.detectChanges(); + + const addButton: DebugElement = fixture.debugElement.query(By.css(`button#add-btn-${component.type}`)); + addButton.nativeElement.click(); + fixture.detectChanges(); + + const accessControlItems = fixture.debugElement.queryAll(By.css('.access-control-item')); + expect(accessControlItems.length).toEqual(2); + }); + + it('should remove access control items when clicking remove button', () => { + component.enable(); + + component.addAccessControlItem('test'); + + fixture.detectChanges(); + + const removeButton: DebugElement[] = fixture.debugElement.queryAll(By.css('button.btn-outline-danger')); + removeButton[1].nativeElement.click(); + fixture.detectChanges(); + + const accessControlItems = fixture.debugElement.queryAll(By.css('.access-control-item')); + expect(accessControlItems.length).toEqual(1); + }); +}); diff --git a/src/app/shared/access-control-form-container/access-control-array-form/access-control-array-form.component.ts b/src/app/shared/access-control-form-container/access-control-array-form/access-control-array-form.component.ts new file mode 100644 index 0000000000..227de596ff --- /dev/null +++ b/src/app/shared/access-control-form-container/access-control-array-form/access-control-array-form.component.ts @@ -0,0 +1,150 @@ +import {Component, Input, OnInit, ViewChild} from '@angular/core'; +import {NgForm} from '@angular/forms'; +import {AccessesConditionOption} from '../../../core/config/models/config-accesses-conditions-options.model'; +import {dateToISOFormat} from '../../date.util'; + +@Component({ + selector: 'ds-access-control-array-form', + templateUrl: './access-control-array-form.component.html', + styleUrls: ['./access-control-array-form.component.scss'], + exportAs: 'accessControlArrayForm' +}) +export class AccessControlArrayFormComponent implements OnInit { + @Input() dropdownOptions: AccessesConditionOption[] = []; + @Input() mode!: 'add' | 'replace'; + @Input() type!: 'item' | 'bitstream'; + + @ViewChild('ngForm', {static: true}) ngForm!: NgForm; + + form: { accessControls: AccessControlItem[] } = { + accessControls: [emptyAccessControlItem()] // Start with one empty access control item + }; + + formDisabled = true; + + ngOnInit(): void { + this.disable(); // Disable the form by default + } + + get allControlsAreEmpty() { + return this.form.accessControls + .every(x => x.itemName === null || x.itemName === ''); + } + + get showWarning() { + return this.mode === 'replace' && this.allControlsAreEmpty && !this.formDisabled; + } + + /** + * Add a new access control item to the form. + * Start and end date are disabled by default. + * @param itemName The name of the item to add + */ + addAccessControlItem(itemName: string = null) { + this.form.accessControls = [ + ...this.form.accessControls, + {...emptyAccessControlItem(), itemName} + ]; + } + + /** + * Remove an access control item from the form. + * @param ngModelGroup + * @param index + */ + removeAccessControlItem(id: number) { + this.form.accessControls = this.form.accessControls.filter(item => item.id !== id); + } + + /** + * Get the value of the form. + * This will be used to read the form value from the parent component. + * @return The form value + */ + getValue() { + return this.form.accessControls + .filter(x => x.itemName !== null && x.itemName !== '') + .map(x => ({ + name: x.itemName, + startDate: (x.startDate ? dateToISOFormat(x.startDate) : null), + endDate: (x.endDate ? dateToISOFormat(x.endDate) : null) + })); + } + + /** + * Set the value of the form from the parent component. + */ + reset() { + this.form.accessControls = []; + + // Add an empty access control item by default + this.addAccessControlItem(); + + this.disable(); + } + + /** + * Disable the form. + * This will be used to disable the form from the parent component. + */ + disable = () => { + this.ngForm.form.disable(); + this.formDisabled = true; + }; + + /** + * Enable the form. + * This will be used to enable the form from the parent component. + */ + enable = () => { + this.ngForm.form.enable(); + this.formDisabled = false; + }; + + accessControlChanged(control: AccessControlItem, selectedItem: string) { + const item = this.dropdownOptions + .find((x) => x.name === selectedItem); + + control.startDate = null; + control.endDate = null; + + control.hasStartDate = item?.hasStartDate || false; + control.hasEndDate = item?.hasEndDate || false; + + control.maxStartDate = item?.maxStartDate || null; + control.maxEndDate = item?.maxEndDate || null; + } + + trackById(index: number, item: AccessControlItem) { + return item.id; + } + +} + + +export interface AccessControlItem { + id: number; // will be used only locally + + itemName: string | null; + + hasStartDate?: boolean; + startDate: string | null; + maxStartDate?: string | null; + + hasEndDate?: boolean; + endDate: string | null; + maxEndDate?: string | null; +} + +const emptyAccessControlItem = (): AccessControlItem => ({ + id: randomID(), + itemName: null, + startDate: null, + hasStartDate: false, + maxStartDate: null, + endDate: null, + hasEndDate: false, + maxEndDate: null, +}); + +const randomID = () => Math.floor(Math.random() * 1000000); diff --git a/src/app/shared/access-control-form-container/access-control-array-form/to-date.pipe.ts b/src/app/shared/access-control-form-container/access-control-array-form/to-date.pipe.ts new file mode 100644 index 0000000000..203d12a59d --- /dev/null +++ b/src/app/shared/access-control-form-container/access-control-array-form/to-date.pipe.ts @@ -0,0 +1,23 @@ +import {Pipe, PipeTransform} from '@angular/core'; +import {NgbDateStruct} from '@ng-bootstrap/ng-bootstrap/datepicker/ngb-date-struct'; + +@Pipe({ + // eslint-disable-next-line @angular-eslint/pipe-prefix + name: 'toDate', + pure: false +}) +export class ToDatePipe implements PipeTransform { + transform(dateValue: string | null): NgbDateStruct | null { + if (!dateValue) { + return null; + } + + const date = new Date(dateValue); + return { + year: date.getFullYear(), + month: date.getMonth() + 1, + day: date.getDate() + } as NgbDateStruct; + } + +} diff --git a/src/app/shared/access-control-form-container/access-control-form-container-intial-state.ts b/src/app/shared/access-control-form-container/access-control-form-container-intial-state.ts new file mode 100644 index 0000000000..b5081db6c2 --- /dev/null +++ b/src/app/shared/access-control-form-container/access-control-form-container-intial-state.ts @@ -0,0 +1,27 @@ +import {ListableObject} from '../object-collection/shared/listable-object.model'; + +export const createAccessControlInitialFormState = (): AccessControlFormState => ({ + item: { + toggleStatus: false, + accessMode: 'replace', + }, + bitstream: { + toggleStatus: false, + accessMode: 'replace', + changesLimit: 'all', // 'all' | 'selected' + selectedBitstreams: [] as ListableObject[], + }, +}); + +export interface AccessControlFormState { + item: { + toggleStatus: boolean, + accessMode: 'add' | 'replace', + }, + bitstream: { + toggleStatus: boolean, + accessMode: 'add' | 'replace', + changesLimit: string, + selectedBitstreams: ListableObject[], + } +} diff --git a/src/app/shared/access-control-form-container/access-control-form-container.component.html b/src/app/shared/access-control-form-container/access-control-form-container.component.html new file mode 100644 index 0000000000..a5173d10d7 --- /dev/null +++ b/src/app/shared/access-control-form-container/access-control-form-container.component.html @@ -0,0 +1,167 @@ +
    +
    +
    + + + +
    +
    + +
    +
    +

    + {{ 'access-control-item-header-toggle' | translate }} +

    + + +
    + +
    +
    + {{ 'access-control-mode' | translate }} +
    +
    +
    + + +
    +
    + + +
    +
    +
    +
    + +
    +
    {{'access-control-access-conditions' | translate}}
    + + + +
    + +
    + +
    + +
    +
    +

    + {{'access-control-bitstream-header-toggle' | translate}} +

    + + +
    + +
    +
    + {{'access-control-limit-to-specific' | translate}} +
    +
    +
    + + +
    +
    + + +
    +
    +
    +
    + +
    +
    + {{'access-control-mode' | translate}} +
    +
    +
    + + +
    +
    + + +
    +
    +
    + +
    +
    {{'access-control-access-conditions' | translate}}
    + + + +
    +
    +
    + +
    + +
    + + +
    +
    +
    +
    diff --git a/src/app/shared/access-control-form-container/access-control-form-container.component.scss b/src/app/shared/access-control-form-container/access-control-form-container.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/access-control-form-container/access-control-form-container.component.spec.ts b/src/app/shared/access-control-form-container/access-control-form-container.component.spec.ts new file mode 100644 index 0000000000..4d02f7a52d --- /dev/null +++ b/src/app/shared/access-control-form-container/access-control-form-container.component.spec.ts @@ -0,0 +1,149 @@ +import {ComponentFixture, fakeAsync, TestBed} from '@angular/core/testing'; +import {NgbDatepickerModule, NgbModal, NgbModalRef} from '@ng-bootstrap/ng-bootstrap'; +import {Component} from '@angular/core'; +import {of} from 'rxjs'; +import {AccessControlFormContainerComponent} from './access-control-form-container.component'; +import {BulkAccessControlService} from './bulk-access-control.service'; +import {BulkAccessConfigDataService} from '../../core/config/bulk-access-config-data.service'; +import {Item} from '../../core/shared/item.model'; +import {SelectableListService} from '../object-list/selectable-list/selectable-list.service'; +import {createAccessControlInitialFormState} from './access-control-form-container-intial-state'; +import {CommonModule} from '@angular/common'; +import {SharedBrowseByModule} from '../browse-by/shared-browse-by.module'; +import {TranslateModule} from '@ngx-translate/core'; +import {FormsModule} from '@angular/forms'; +import {UiSwitchModule} from 'ngx-ui-switch'; +import { + ITEM_ACCESS_CONTROL_SELECT_BITSTREAMS_LIST_ID +} from './item-access-control-select-bitstreams-modal/item-access-control-select-bitstreams-modal.component'; +import {AccessControlFormModule} from './access-control-form.module'; + + +describe('AccessControlFormContainerComponent', () => { + let component: AccessControlFormContainerComponent; + let fixture: ComponentFixture>; + + +// Mock NgbModal + @Component({selector: 'ds-ngb-modal', template: ''}) + class MockNgbModalComponent { + } + +// Mock dependencies + const mockBulkAccessControlService = { + createPayloadFile: jasmine.createSpy('createPayloadFile').and.returnValue({file: 'mocked-file'}), + executeScript: jasmine.createSpy('executeScript').and.returnValue(of('success')), + }; + + const mockBulkAccessConfigDataService = { + findByName: jasmine.createSpy('findByName').and.returnValue(of({payload: {options: []}})), + }; + + const mockSelectableListService = { + getSelectableList: jasmine.createSpy('getSelectableList').and.returnValue(of({selection: []})), + deselectAll: jasmine.createSpy('deselectAll'), + }; + + const mockNgbModal = { + open: jasmine.createSpy('open').and.returnValue( + { componentInstance: {}, closed: of({})} as NgbModalRef + ) + }; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + declarations: [AccessControlFormContainerComponent, MockNgbModalComponent], + imports: [ + CommonModule, + FormsModule, + SharedBrowseByModule, + AccessControlFormModule, + TranslateModule.forRoot(), + NgbDatepickerModule, + UiSwitchModule + ], + providers: [ + {provide: BulkAccessControlService, useValue: mockBulkAccessControlService}, + {provide: BulkAccessConfigDataService, useValue: mockBulkAccessConfigDataService}, + {provide: SelectableListService, useValue: mockSelectableListService}, + {provide: NgbModal, useValue: mockNgbModal}, + ], + }).compileComponents(); + }); + + beforeEach(() => { + fixture = TestBed.createComponent(AccessControlFormContainerComponent); + component = fixture.componentInstance; + component.state = createAccessControlInitialFormState(); + fixture.detectChanges(); + }); + + it('should create the component', () => { + expect(component).toBeTruthy(); + }); + + it('should reset the form', fakeAsync(() => { + fixture.detectChanges(); + const resetSpy = spyOn(component.bitstreamAccessCmp, 'reset'); + spyOn(component.itemAccessCmp, 'reset'); + + component.reset(); + + expect(resetSpy).toHaveBeenCalled(); + expect(component.itemAccessCmp.reset).toHaveBeenCalled(); + expect(component.state).toEqual(createAccessControlInitialFormState()); + })); + + it('should submit the form', () => { + const bitstreamAccess = 'bitstreamAccess'; + const itemAccess = 'itemAccess'; + component.bitstreamAccessCmp.getValue = jasmine.createSpy('getValue').and.returnValue(bitstreamAccess); + component.itemAccessCmp.getValue = jasmine.createSpy('getValue').and.returnValue(itemAccess); + component.itemRD = {payload: {uuid: 'item-uuid'}} as any; + + component.submit(); + + expect(mockBulkAccessControlService.createPayloadFile).toHaveBeenCalledWith({ + bitstreamAccess, + itemAccess, + state: createAccessControlInitialFormState(), + }); + expect(mockBulkAccessControlService.executeScript).toHaveBeenCalledWith(['item-uuid'], 'mocked-file'); + }); + + it('should handle the status change for bitstream access', () => { + component.bitstreamAccessCmp.enable = jasmine.createSpy('enable'); + component.bitstreamAccessCmp.disable = jasmine.createSpy('disable'); + + component.handleStatusChange('bitstream', true); + expect(component.bitstreamAccessCmp.enable).toHaveBeenCalled(); + + component.handleStatusChange('bitstream', false); + expect(component.bitstreamAccessCmp.disable).toHaveBeenCalled(); + }); + + it('should handle the status change for item access', () => { + component.itemAccessCmp.enable = jasmine.createSpy('enable'); + component.itemAccessCmp.disable = jasmine.createSpy('disable'); + + component.handleStatusChange('item', true); + expect(component.itemAccessCmp.enable).toHaveBeenCalled(); + + component.handleStatusChange('item', false); + expect(component.itemAccessCmp.disable).toHaveBeenCalled(); + }); + + it('should open the select bitstreams modal', () => { + const modalService = TestBed.inject(NgbModal); + + component.openSelectBitstreamsModal(new Item()); + expect(modalService.open).toHaveBeenCalled(); + }); + + it('should unsubscribe and deselect all on component destroy', () => { + component.ngOnDestroy(); + expect(component.selectableListService.deselectAll).toHaveBeenCalledWith( + ITEM_ACCESS_CONTROL_SELECT_BITSTREAMS_LIST_ID + ); + }); +}); diff --git a/src/app/shared/access-control-form-container/access-control-form-container.component.ts b/src/app/shared/access-control-form-container/access-control-form-container.component.ts new file mode 100644 index 0000000000..69a598f7ce --- /dev/null +++ b/src/app/shared/access-control-form-container/access-control-form-container.component.ts @@ -0,0 +1,160 @@ +import { ChangeDetectorRef, Component, Input, OnDestroy, ViewChild } from '@angular/core'; +import { concatMap, Observable, shareReplay } from 'rxjs'; +import { RemoteData } from '../../core/data/remote-data'; +import { Item } from '../../core/shared/item.model'; +import { AccessControlArrayFormComponent } from './access-control-array-form/access-control-array-form.component'; +import { BulkAccessControlService } from './bulk-access-control.service'; +import { SelectableListService } from '../object-list/selectable-list/selectable-list.service'; +import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; +import { map, take } from 'rxjs/operators'; +import { DSpaceObject } from '../../core/shared/dspace-object.model'; +import { + ITEM_ACCESS_CONTROL_SELECT_BITSTREAMS_LIST_ID, + ItemAccessControlSelectBitstreamsModalComponent +} from './item-access-control-select-bitstreams-modal/item-access-control-select-bitstreams-modal.component'; +import { BulkAccessConfigDataService } from '../../core/config/bulk-access-config-data.service'; +import { getFirstCompletedRemoteData } from '../../core/shared/operators'; +import { BulkAccessConditionOptions } from '../../core/config/models/bulk-access-condition-options.model'; +import { AlertType } from '../alert/aletr-type'; +import { + createAccessControlInitialFormState +} from './access-control-form-container-intial-state'; + +@Component({ + selector: 'ds-access-control-form-container', + templateUrl: './access-control-form-container.component.html', + styleUrls: [ './access-control-form-container.component.scss' ], + exportAs: 'dsAccessControlForm' +}) +export class AccessControlFormContainerComponent implements OnDestroy { + + /** + * Will be used to determine if we need to show the limit changes to specific bitstreams radio buttons + */ + @Input() showLimitToSpecificBitstreams = false; + + /** + * The title message of the access control form (translate key) + */ + @Input() titleMessage = ''; + + /** + * The item to which the access control form applies + */ + @Input() itemRD: RemoteData; + + /** + * Whether to show the submit and cancel button + * We want to hide these buttons when the form is + * used in an accordion, and we want to show buttons somewhere else + */ + @Input() showSubmit = true; + + @ViewChild('bitstreamAccessCmp', { static: true }) bitstreamAccessCmp: AccessControlArrayFormComponent; + @ViewChild('itemAccessCmp', { static: true }) itemAccessCmp: AccessControlArrayFormComponent; + + readonly AlertType = AlertType; + + constructor( + private bulkAccessConfigService: BulkAccessConfigDataService, + private bulkAccessControlService: BulkAccessControlService, + public selectableListService: SelectableListService, + protected modalService: NgbModal, + private cdr: ChangeDetectorRef + ) {} + + state = createAccessControlInitialFormState(); + + dropdownData$: Observable = this.bulkAccessConfigService.findByName('default').pipe( + getFirstCompletedRemoteData(), + map((configRD: RemoteData) => configRD.hasSucceeded ? configRD.payload : null), + shareReplay(1) + ); + + /** + * Will be used from a parent component to read the value of the form + */ + getFormValue() { + console.log({ + bitstream: this.bitstreamAccessCmp.getValue(), + item: this.itemAccessCmp.getValue(), + state: this.state + }); + return { + bitstream: this.bitstreamAccessCmp.getValue(), + item: this.itemAccessCmp.getValue(), + state: this.state + }; + } + + /** + * Reset the form to its initial state + * This will also reset the state of the child components (bitstream and item access) + */ + reset() { + this.bitstreamAccessCmp.reset(); + this.itemAccessCmp.reset(); + this.state = createAccessControlInitialFormState(); + } + + /** + * Submit the form + * This will create a payload file and execute the script + */ + submit() { + const bitstreamAccess = this.bitstreamAccessCmp.getValue(); + const itemAccess = this.itemAccessCmp.getValue(); + + const { file } = this.bulkAccessControlService.createPayloadFile({ + bitstreamAccess, + itemAccess, + state: this.state + }); + + this.bulkAccessControlService.executeScript( + [ this.itemRD.payload.uuid ], + file + ).pipe(take(1)).subscribe((res) => { + console.log('success', res); + }); + } + + /** + * Handle the status change of the access control form (item or bitstream) + * This will enable/disable the access control form for the item or bitstream + * @param type The type of the access control form (item or bitstream) + * @param active boolean indicating whether the access control form should be enabled or disabled + */ + handleStatusChange(type: 'item' | 'bitstream', active: boolean) { + if (type === 'bitstream') { + active ? this.bitstreamAccessCmp.enable() : this.bitstreamAccessCmp.disable(); + } else if (type === 'item') { + active ? this.itemAccessCmp.enable() : this.itemAccessCmp.disable(); + } + } + + /** + * Open the modal to select bitstreams for which to change the access control + * This will open the modal and pass the currently selected bitstreams + * @param item The item for which to change the access control + */ + openSelectBitstreamsModal(item: Item) { + const ref = this.modalService.open(ItemAccessControlSelectBitstreamsModalComponent); + ref.componentInstance.selectedBitstreams = this.state.bitstream.selectedBitstreams; + ref.componentInstance.item = item; + + ref.closed.pipe( + concatMap(() => this.selectableListService.getSelectableList(ITEM_ACCESS_CONTROL_SELECT_BITSTREAMS_LIST_ID)), + take(1) + ).subscribe((list) => { + this.state.bitstream.selectedBitstreams = list?.selection || []; + this.cdr.detectChanges(); + }); + } + + ngOnDestroy(): void { + this.selectableListService.deselectAll(ITEM_ACCESS_CONTROL_SELECT_BITSTREAMS_LIST_ID); + } + +} + diff --git a/src/app/shared/access-control-form-container/access-control-form.module.ts b/src/app/shared/access-control-form-container/access-control-form.module.ts new file mode 100644 index 0000000000..3bbdb3ab5d --- /dev/null +++ b/src/app/shared/access-control-form-container/access-control-form.module.ts @@ -0,0 +1,32 @@ +import {NgModule} from '@angular/core'; +import {CommonModule} from '@angular/common'; + +import {TranslateModule} from '@ngx-translate/core'; +import {UiSwitchModule} from 'ngx-ui-switch'; + +import {AccessControlArrayFormComponent} from './access-control-array-form/access-control-array-form.component'; +import {SharedModule} from '../shared.module'; +import { + ItemAccessControlSelectBitstreamsModalComponent +} from './item-access-control-select-bitstreams-modal/item-access-control-select-bitstreams-modal.component'; +import {AccessControlFormContainerComponent} from './access-control-form-container.component'; +import {NgbDatepickerModule} from '@ng-bootstrap/ng-bootstrap'; +import {ToDatePipe} from './access-control-array-form/to-date.pipe'; + +@NgModule({ + imports: [ + CommonModule, + SharedModule, + TranslateModule, + UiSwitchModule, + NgbDatepickerModule + ], + declarations: [ + AccessControlFormContainerComponent, + AccessControlArrayFormComponent, + ItemAccessControlSelectBitstreamsModalComponent, + ToDatePipe + ], + exports: [ AccessControlFormContainerComponent, AccessControlArrayFormComponent ], +}) +export class AccessControlFormModule {} diff --git a/src/app/shared/access-control-form-container/bulk-access-control.service.spec.ts b/src/app/shared/access-control-form-container/bulk-access-control.service.spec.ts new file mode 100644 index 0000000000..16d05edeb7 --- /dev/null +++ b/src/app/shared/access-control-form-container/bulk-access-control.service.spec.ts @@ -0,0 +1,94 @@ +import { TestBed } from '@angular/core/testing'; +import { RouterTestingModule } from '@angular/router/testing'; +import { TranslateModule } from '@ngx-translate/core'; + +import { BulkAccessControlService } from './bulk-access-control.service'; +import { ScriptDataService } from '../../core/data/processes/script-data.service'; +import { ProcessParameter } from '../../process-page/processes/process-parameter.model'; +import { NotificationsService } from '../notifications/notifications.service'; +import { NotificationsServiceStub } from '../testing/notifications-service.stub'; +import { createSuccessfulRemoteDataObject$ } from '../remote-data.utils'; +import { Process } from '../../process-page/processes/process.model'; + +describe('BulkAccessControlService', () => { + let service: BulkAccessControlService; + let scriptServiceSpy: jasmine.SpyObj; + + const mockPayload: any = { + 'bitstream': [], + 'item': [ + { + 'name': 'embargo', + 'startDate': { + 'year': 2026, + 'month': 5, + 'day': 31 + }, + 'endDate': null + } + ], + 'state': { + 'item': { + 'toggleStatus': true, + 'accessMode': 'replace' + }, + 'bitstream': { + 'toggleStatus': false, + 'accessMode': '', + 'changesLimit': '', + 'selectedBitstreams': [] + } + } + }; + + beforeEach(() => { + const spy = jasmine.createSpyObj('ScriptDataService', ['invoke']); + TestBed.configureTestingModule({ + imports: [ + RouterTestingModule, + TranslateModule.forRoot() + ], + providers: [ + BulkAccessControlService, + { provide: ScriptDataService, useValue: spy }, + { provide: NotificationsService, useValue: NotificationsServiceStub }, + ] + }); + service = TestBed.inject(BulkAccessControlService); + scriptServiceSpy = TestBed.inject(ScriptDataService) as jasmine.SpyObj; + }); + + it('should be created', () => { + expect(service).toBeTruthy(); + }); + + describe('createPayloadFile', () => { + it('should create a file and return the URL and file object', () => { + const payload = mockPayload; + const result = service.createPayloadFile(payload); + + expect(result.url).toBeTruthy(); + expect(result.file).toBeTruthy(); + }); + }); + + describe('executeScript', () => { + it('should invoke the script service with the correct parameters', () => { + const uuids = ['123', '456']; + const file = new File(['test'], 'data.json', { type: 'application/json' }); + const expectedParams: ProcessParameter[] = [ + { name: '-f', value: 'data.json' }, + { name: '-u', value: '123' }, + { name: '-u', value: '456' }, + ]; + + // @ts-ignore + scriptServiceSpy.invoke.and.returnValue(createSuccessfulRemoteDataObject$(new Process())); + + const result = service.executeScript(uuids, file); + + expect(scriptServiceSpy.invoke).toHaveBeenCalledWith('bulk-access-control', expectedParams, [file]); + expect(result).toBeTruthy(); + }); + }); +}); diff --git a/src/app/shared/access-control-form-container/bulk-access-control.service.ts b/src/app/shared/access-control-form-container/bulk-access-control.service.ts new file mode 100644 index 0000000000..6fb6b62532 --- /dev/null +++ b/src/app/shared/access-control-form-container/bulk-access-control.service.ts @@ -0,0 +1,146 @@ +import { Injectable } from '@angular/core'; +import { Router } from '@angular/router'; + +import { Observable } from 'rxjs'; +import { map } from 'rxjs/operators'; +import { TranslateService } from '@ngx-translate/core'; + +import { ScriptDataService } from '../../core/data/processes/script-data.service'; +import { ProcessParameter } from '../../process-page/processes/process-parameter.model'; +import { AccessControlFormState } from './access-control-form-container-intial-state'; +import { getFirstCompletedRemoteData } from '../../core/shared/operators'; +import { RemoteData } from '../../core/data/remote-data'; +import { Process } from '../../process-page/processes/process.model'; +import { isNotEmpty } from '../empty.util'; +import { getProcessDetailRoute } from '../../process-page/process-page-routing.paths'; +import { NotificationsService } from '../notifications/notifications.service'; + +export interface BulkAccessPayload { + state: AccessControlFormState; + bitstreamAccess: any; + itemAccess: any; +} + +/** + * This service is used to create a payload file and execute the bulk access control script + */ +@Injectable({ providedIn: 'root' }) +export class BulkAccessControlService { + constructor( + private notificationsService: NotificationsService, + private router: Router, + private scriptService: ScriptDataService, + private translationService: TranslateService + ) {} + + /** + * Create a payload file from the given payload and return the file and the url to the file + * The created file will be used as input for the bulk access control script + * @param payload The payload to create the file from + */ + createPayloadFile(payload: BulkAccessPayload) { + const content = convertToBulkAccessControlFileModel(payload); + + const blob = new Blob([JSON.stringify(content, null, 2)], { + type: 'application/json', + }); + + const file = new File([blob], 'data.json', { + type: 'application/json', + }); + + const url = URL.createObjectURL(file); + + return { url, file }; + } + + /** + * Execute the bulk access control script with the given uuids and file + * @param uuids + * @param file + */ + executeScript(uuids: string[], file: File): Observable { + console.log('execute', { uuids, file }); + + const params: ProcessParameter[] = [ + { name: '-f', value: file.name } + ]; + uuids.forEach((uuid) => { + params.push({ name: '-u', value: uuid }); + }); + + return this.scriptService.invoke('bulk-access-control', params, [file]).pipe( + getFirstCompletedRemoteData(), + map((rd: RemoteData) => { + if (rd.hasSucceeded) { + const title = this.translationService.get('process.new.notification.success.title'); + const content = this.translationService.get('process.new.notification.success.content'); + this.notificationsService.success(title, content); + if (isNotEmpty(rd.payload)) { + this.router.navigateByUrl(getProcessDetailRoute(rd.payload.processId)); + } + return true; + } else { + const title = this.translationService.get('process.new.notification.error.title'); + const content = this.translationService.get('process.new.notification.error.content'); + this.notificationsService.error(title, content); + return false; + } + }) + ); + } +} + +/** + * Convert the given payload to a BulkAccessControlFileModel + * @param payload + */ +export const convertToBulkAccessControlFileModel = (payload: { state: AccessControlFormState, bitstreamAccess: AccessCondition[], itemAccess: AccessCondition[] }): BulkAccessControlFileModel => { + let finalPayload: BulkAccessControlFileModel = {}; + + const itemEnabled = payload.state.item.toggleStatus; + const bitstreamEnabled = payload.state.bitstream.toggleStatus; + + if (itemEnabled) { + finalPayload.item = { + mode: payload.state.item.accessMode, + accessConditions: payload.itemAccess + }; + } + + if (bitstreamEnabled) { + const constraints = { uuid: [] }; + + if (bitstreamEnabled && payload.state.bitstream.changesLimit === 'selected') { + // @ts-ignore + constraints.uuid = payload.state.bitstream.selectedBitstreams.map((x) => x.id); + } + + finalPayload.bitstream = { + constraints, + mode: payload.state.bitstream.accessMode, + accessConditions: payload.bitstreamAccess + }; + } + + return finalPayload; +}; + + +export interface BulkAccessControlFileModel { + item?: { + mode: string; + accessConditions: AccessCondition[]; + }, + bitstream?: { + constraints: { uuid: string[] }; + mode: string; + accessConditions: AccessCondition[]; + } +} + +interface AccessCondition { + name: string; + startDate?: string; + endDate?: string; +} diff --git a/src/app/shared/access-control-form-container/item-access-control-select-bitstreams-modal/item-access-control-select-bitstreams-modal.component.html b/src/app/shared/access-control-form-container/item-access-control-select-bitstreams-modal/item-access-control-select-bitstreams-modal.component.html new file mode 100644 index 0000000000..8cf0ecea38 --- /dev/null +++ b/src/app/shared/access-control-form-container/item-access-control-select-bitstreams-modal/item-access-control-select-bitstreams-modal.component.html @@ -0,0 +1,35 @@ + + + diff --git a/src/app/shared/access-control-form-container/item-access-control-select-bitstreams-modal/item-access-control-select-bitstreams-modal.component.scss b/src/app/shared/access-control-form-container/item-access-control-select-bitstreams-modal/item-access-control-select-bitstreams-modal.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/access-control-form-container/item-access-control-select-bitstreams-modal/item-access-control-select-bitstreams-modal.component.spec.ts b/src/app/shared/access-control-form-container/item-access-control-select-bitstreams-modal/item-access-control-select-bitstreams-modal.component.spec.ts new file mode 100644 index 0000000000..f60d9a70e7 --- /dev/null +++ b/src/app/shared/access-control-form-container/item-access-control-select-bitstreams-modal/item-access-control-select-bitstreams-modal.component.spec.ts @@ -0,0 +1,25 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { ItemAccessControlSelectBitstreamsModalComponent } from './item-access-control-select-bitstreams-modal.component'; + +xdescribe('ItemAccessControlSelectBitstreamsModalComponent', () => { + let component: ItemAccessControlSelectBitstreamsModalComponent; + let fixture: ComponentFixture; + + beforeEach(async () => { + await TestBed.configureTestingModule({ + declarations: [ ItemAccessControlSelectBitstreamsModalComponent ] + }) + .compileComponents(); + }); + + beforeEach(() => { + fixture = TestBed.createComponent(ItemAccessControlSelectBitstreamsModalComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/src/app/shared/access-control-form-container/item-access-control-select-bitstreams-modal/item-access-control-select-bitstreams-modal.component.ts b/src/app/shared/access-control-form-container/item-access-control-select-bitstreams-modal/item-access-control-select-bitstreams-modal.component.ts new file mode 100644 index 0000000000..617803a0c4 --- /dev/null +++ b/src/app/shared/access-control-form-container/item-access-control-select-bitstreams-modal/item-access-control-select-bitstreams-modal.component.ts @@ -0,0 +1,62 @@ +import { Component, Input, OnInit } from '@angular/core'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { BehaviorSubject } from 'rxjs'; +import { PaginatedList } from 'src/app/core/data/paginated-list.model'; +import { RemoteData } from 'src/app/core/data/remote-data'; +import { Bitstream } from 'src/app/core/shared/bitstream.model'; +import { Context } from 'src/app/core/shared/context.model'; +import { PaginationComponentOptions } from '../../pagination/pagination-component-options.model'; +import { Item } from '../../../core/shared/item.model'; +import { BitstreamDataService } from '../../../core/data/bitstream-data.service'; +import { PaginationService } from '../../../core/pagination/pagination.service'; +import { TranslateService } from '@ngx-translate/core'; +import { hasValue } from '../../empty.util'; +import { getFirstCompletedRemoteData } from '../../../core/shared/operators'; + +export const ITEM_ACCESS_CONTROL_SELECT_BITSTREAMS_LIST_ID = 'item-access-control-select-bitstreams'; + +@Component({ + selector: 'ds-item-access-control-select-bitstreams-modal', + templateUrl: './item-access-control-select-bitstreams-modal.component.html', + styleUrls: [ './item-access-control-select-bitstreams-modal.component.scss' ] +}) +export class ItemAccessControlSelectBitstreamsModalComponent implements OnInit { + + LIST_ID = ITEM_ACCESS_CONTROL_SELECT_BITSTREAMS_LIST_ID; + + @Input() item!: Item; + @Input() selectedBitstreams: string[] = []; + + data$ = new BehaviorSubject> | null>(null); + paginationConfig: PaginationComponentOptions; + pageSize = 5; + + context: Context = Context.Bitstream; + + constructor( + private bitstreamService: BitstreamDataService, + protected paginationService: PaginationService, + protected translateService: TranslateService, + public activeModal: NgbActiveModal + ) { } + + ngOnInit() { + this.loadForPage(1); + + this.paginationConfig = new PaginationComponentOptions(); + this.paginationConfig.id = 'iacsbm'; + this.paginationConfig.currentPage = 1; + if (hasValue(this.pageSize)) { + this.paginationConfig.pageSize = this.pageSize; + } + } + + loadForPage(page: number) { + this.bitstreamService.findAllByItemAndBundleName(this.item, 'ORIGINAL', { currentPage: page}, false) + .pipe( + getFirstCompletedRemoteData(), + ) + .subscribe(this.data$); + } + +} diff --git a/src/app/shared/auth-nav-menu/auth-nav-menu.component.html b/src/app/shared/auth-nav-menu/auth-nav-menu.component.html index 94cbd4368a..05f502afa1 100644 --- a/src/app/shared/auth-nav-menu/auth-nav-menu.component.html +++ b/src/app/shared/auth-nav-menu/auth-nav-menu.component.html @@ -19,7 +19,7 @@
    diff --git a/src/app/shared/comcol/comcol-forms/edit-comcol-page/comcol-role/comcol-role.component.spec.ts b/src/app/shared/comcol/comcol-forms/edit-comcol-page/comcol-role/comcol-role.component.spec.ts index 59fc95b67f..00efc3ccaa 100644 --- a/src/app/shared/comcol/comcol-forms/edit-comcol-page/comcol-role/comcol-role.component.spec.ts +++ b/src/app/shared/comcol/comcol-forms/edit-comcol-page/comcol-role/comcol-role.component.spec.ts @@ -12,6 +12,8 @@ import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { ComcolModule } from '../../../comcol.module'; import { NotificationsService } from '../../../../notifications/notifications.service'; import { NotificationsServiceStub } from '../../../../testing/notifications-service.stub'; +import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service'; +import { DSONameServiceMock } from '../../../../mocks/dso-name.service.mock'; describe('ComcolRoleComponent', () => { @@ -41,6 +43,7 @@ describe('ComcolRoleComponent', () => { NoopAnimationsModule ], providers: [ + { provide: DSONameService, useValue: new DSONameServiceMock() }, { provide: GroupDataService, useValue: groupService }, { provide: RequestService, useValue: requestService }, { provide: NotificationsService, useClass: NotificationsServiceStub } diff --git a/src/app/shared/comcol/comcol-forms/edit-comcol-page/comcol-role/comcol-role.component.ts b/src/app/shared/comcol/comcol-forms/edit-comcol-page/comcol-role/comcol-role.component.ts index 3091dd0cf0..5ae22d754e 100644 --- a/src/app/shared/comcol/comcol-forms/edit-comcol-page/comcol-role/comcol-role.component.ts +++ b/src/app/shared/comcol/comcol-forms/edit-comcol-page/comcol-role/comcol-role.component.ts @@ -14,6 +14,7 @@ import { hasNoValue, hasValue } from '../../../../empty.util'; import { NoContent } from '../../../../../core/shared/NoContent.model'; import { NotificationsService } from '../../../../notifications/notifications.service'; import { TranslateService } from '@ngx-translate/core'; +import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service'; /** * Component for managing a community or collection role. @@ -76,6 +77,7 @@ export class ComcolRoleComponent implements OnInit { protected groupService: GroupDataService, protected notificationsService: NotificationsService, protected translateService: TranslateService, + public dsoNameService: DSONameService, ) { } diff --git a/src/app/shared/comcol/comcol-forms/edit-comcol-page/edit-comcol-page.component.ts b/src/app/shared/comcol/comcol-forms/edit-comcol-page/edit-comcol-page.component.ts index 48eb9aec96..e4d6c9c8a7 100644 --- a/src/app/shared/comcol/comcol-forms/edit-comcol-page/edit-comcol-page.component.ts +++ b/src/app/shared/comcol/comcol-forms/edit-comcol-page/edit-comcol-page.component.ts @@ -1,7 +1,7 @@ import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; -import { first, map } from 'rxjs/operators'; +import { map } from 'rxjs/operators'; import { ActivatedRoute, Router } from '@angular/router'; import { RemoteData } from '../../../../core/data/remote-data'; @@ -53,7 +53,7 @@ export class EditComColPageComponent implements On this.pages = this.route.routeConfig.children .map((child: any) => child.path) .filter((path: string) => isNotEmpty(path)); // ignore reroutes - this.dsoRD$ = this.route.data.pipe(first(), map((data) => data.dso)); + this.dsoRD$ = this.route.data.pipe(map((data) => data.dso)); } /** diff --git a/src/app/shared/confirmation-modal/confirmation-modal.component.html b/src/app/shared/confirmation-modal/confirmation-modal.component.html index 82c70b662b..02434b1fa1 100644 --- a/src/app/shared/confirmation-modal/confirmation-modal.component.html +++ b/src/app/shared/confirmation-modal/confirmation-modal.component.html @@ -1,18 +1,18 @@
    - diff --git a/src/app/shared/confirmation-modal/confirmation-modal.component.ts b/src/app/shared/confirmation-modal/confirmation-modal.component.ts index 4fa4858600..46eb4cedc5 100644 --- a/src/app/shared/confirmation-modal/confirmation-modal.component.ts +++ b/src/app/shared/confirmation-modal/confirmation-modal.component.ts @@ -1,6 +1,7 @@ import { Component, EventEmitter, Input, Output } from '@angular/core'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { DSpaceObject } from '../../core/shared/dspace-object.model'; +import { DSONameService } from '../../core/breadcrumbs/dso-name.service'; @Component({ selector: 'ds-confirmation-modal', @@ -25,7 +26,10 @@ export class ConfirmationModalComponent { @Output() response = new EventEmitter(); - constructor(protected activeModal: NgbActiveModal) { + constructor( + protected activeModal: NgbActiveModal, + public dsoNameService: DSONameService, + ) { } /** diff --git a/src/app/shared/context-help-wrapper/context-help-wrapper.component.html b/src/app/shared/context-help-wrapper/context-help-wrapper.component.html index b031d0f42d..083b8163ff 100644 --- a/src/app/shared/context-help-wrapper/context-help-wrapper.component.html +++ b/src/app/shared/context-help-wrapper/context-help-wrapper.component.html @@ -2,7 +2,7 @@
    - {{elem.text}} + {{elem.text}} {{ elem }} diff --git a/src/app/shared/dso-page/dso-edit-menu.resolver.ts b/src/app/shared/dso-page/dso-edit-menu.resolver.ts index 749d5580a4..80a69c2830 100644 --- a/src/app/shared/dso-page/dso-edit-menu.resolver.ts +++ b/src/app/shared/dso-page/dso-edit-menu.resolver.ts @@ -50,27 +50,32 @@ export class DSOEditMenuResolver implements Resolve<{ [key: string]: MenuSection if (hasNoValue(id) && hasValue(route.queryParams.scope)) { id = route.queryParams.scope; } - return this.dSpaceObjectDataService.findById(id, true, false).pipe( - getFirstCompletedRemoteData(), - switchMap((dsoRD) => { - if (dsoRD.hasSucceeded) { - const dso = dsoRD.payload; - return combineLatest(this.getDsoMenus(dso, route, state)).pipe( - // Menu sections are retrieved as an array of arrays and flattened into a single array - map((combinedMenus) => [].concat.apply([], combinedMenus)), - map((menus) => this.addDsoUuidToMenuIDs(menus, dso)), - map((menus) => { - return { - ...route.data?.menu, - [MenuID.DSO_EDIT]: menus - }; - }) - ); - } else { - return observableOf({...route.data?.menu}); - } - }) - ); + if (hasNoValue(id)) { + // If there's no ID, we're not on a DSO homepage, so pass on any pre-existing menu route data + return observableOf({ ...route.data?.menu }); + } else { + return this.dSpaceObjectDataService.findById(id, true, false).pipe( + getFirstCompletedRemoteData(), + switchMap((dsoRD) => { + if (dsoRD.hasSucceeded) { + const dso = dsoRD.payload; + return combineLatest(this.getDsoMenus(dso, route, state)).pipe( + // Menu sections are retrieved as an array of arrays and flattened into a single array + map((combinedMenus) => [].concat.apply([], combinedMenus)), + map((menus) => this.addDsoUuidToMenuIDs(menus, dso)), + map((menus) => { + return { + ...route.data?.menu, + [MenuID.DSO_EDIT]: menus + }; + }) + ); + } else { + return observableOf({...route.data?.menu}); + } + }) + ); + } } /** diff --git a/src/app/shared/dso-selector/dso-selector/dso-selector.component.ts b/src/app/shared/dso-selector/dso-selector/dso-selector.component.ts index fe64c0a41e..503e4c4412 100644 --- a/src/app/shared/dso-selector/dso-selector/dso-selector.component.ts +++ b/src/app/shared/dso-selector/dso-selector/dso-selector.component.ts @@ -9,7 +9,7 @@ import { QueryList, ViewChildren } from '@angular/core'; -import { FormControl } from '@angular/forms'; +import { UntypedFormControl } from '@angular/forms'; import { BehaviorSubject, @@ -86,7 +86,7 @@ export class DSOSelectorComponent implements OnInit, OnDestroy { /** * Input form control to query the list */ - public input: FormControl = new FormControl(); + public input: UntypedFormControl = new UntypedFormControl(); /** * Default pagination for this feature diff --git a/src/app/shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component.ts b/src/app/shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component.ts index 3f81687c9f..6798449094 100644 --- a/src/app/shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component.ts +++ b/src/app/shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component.ts @@ -1,4 +1,4 @@ -import { Component, Input, OnInit } from '@angular/core'; +import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; import { ActivatedRoute, ActivatedRouteSnapshot } from '@angular/router'; import { DSpaceObject } from '../../../core/shared/dspace-object.model'; import { RemoteData } from '../../../core/data/remote-data'; @@ -29,6 +29,11 @@ export abstract class DSOSelectorModalWrapperComponent implements OnInit { */ @Input() dsoRD: RemoteData; + /** + * Representing if component should emit value of selected entries or navigate + */ + @Input() emitOnly = false; + /** * Optional header to display above the selection list * Supports i18n keys @@ -50,6 +55,11 @@ export abstract class DSOSelectorModalWrapperComponent implements OnInit { */ action: SelectorActionType; + /** + * Event emitted when a DSO entry is selected if emitOnly is set to true + */ + @Output() select: EventEmitter = new EventEmitter(); + /** * Default DSO ordering */ @@ -93,7 +103,11 @@ export abstract class DSOSelectorModalWrapperComponent implements OnInit { */ selectObject(dso: DSpaceObject) { this.close(); - this.navigate(dso); + if (this.emitOnly) { + this.select.emit(dso); + } else { + this.navigate(dso); + } } /** diff --git a/src/app/shared/eperson-group-list/eperson-search-box/eperson-search-box.component.spec.ts b/src/app/shared/eperson-group-list/eperson-search-box/eperson-search-box.component.spec.ts index 5a9e74055a..e88f08a131 100644 --- a/src/app/shared/eperson-group-list/eperson-search-box/eperson-search-box.component.spec.ts +++ b/src/app/shared/eperson-group-list/eperson-search-box/eperson-search-box.component.spec.ts @@ -1,6 +1,6 @@ import { ComponentFixture, inject, TestBed, waitForAsync } from '@angular/core/testing'; import { Component, NO_ERRORS_SCHEMA } from '@angular/core'; -import { FormBuilder, FormsModule, ReactiveFormsModule } from '@angular/forms'; +import { UntypedFormBuilder, FormsModule, ReactiveFormsModule } from '@angular/forms'; import { TranslateModule } from '@ngx-translate/core'; @@ -13,7 +13,7 @@ describe('EpersonSearchBoxComponent test suite', () => { let compAsAny: any; let fixture: ComponentFixture; let de; - let formBuilder: FormBuilder; + let formBuilder: UntypedFormBuilder; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ @@ -27,7 +27,7 @@ describe('EpersonSearchBoxComponent test suite', () => { TestComponent ], providers: [ - FormBuilder, + UntypedFormBuilder, EpersonSearchBoxComponent ], schemas: [ @@ -64,7 +64,7 @@ describe('EpersonSearchBoxComponent test suite', () => { beforeEach(() => { // initTestScheduler(); fixture = TestBed.createComponent(EpersonSearchBoxComponent); - formBuilder = TestBed.inject(FormBuilder); + formBuilder = TestBed.inject(UntypedFormBuilder); comp = fixture.componentInstance; compAsAny = fixture.componentInstance; }); diff --git a/src/app/shared/eperson-group-list/eperson-search-box/eperson-search-box.component.ts b/src/app/shared/eperson-group-list/eperson-search-box/eperson-search-box.component.ts index 2aa4891c03..4689d29a8c 100644 --- a/src/app/shared/eperson-group-list/eperson-search-box/eperson-search-box.component.ts +++ b/src/app/shared/eperson-group-list/eperson-search-box/eperson-search-box.component.ts @@ -1,5 +1,5 @@ import { Component, EventEmitter, Output } from '@angular/core'; -import { FormBuilder } from '@angular/forms'; +import { UntypedFormBuilder } from '@angular/forms'; import { Subscription } from 'rxjs'; @@ -33,7 +33,7 @@ export class EpersonSearchBoxComponent { */ @Output() search: EventEmitter = new EventEmitter(); - constructor(private formBuilder: FormBuilder) { + constructor(private formBuilder: UntypedFormBuilder) { this.searchForm = this.formBuilder.group(({ scope: 'metadata', query: '', diff --git a/src/app/shared/eperson-group-list/group-search-box/group-search-box.component.spec.ts b/src/app/shared/eperson-group-list/group-search-box/group-search-box.component.spec.ts index d28a144245..b4c663902d 100644 --- a/src/app/shared/eperson-group-list/group-search-box/group-search-box.component.spec.ts +++ b/src/app/shared/eperson-group-list/group-search-box/group-search-box.component.spec.ts @@ -1,6 +1,6 @@ import { ComponentFixture, inject, TestBed, waitForAsync } from '@angular/core/testing'; import { Component, NO_ERRORS_SCHEMA } from '@angular/core'; -import { FormBuilder, FormsModule, ReactiveFormsModule } from '@angular/forms'; +import { UntypedFormBuilder, FormsModule, ReactiveFormsModule } from '@angular/forms'; import { TranslateModule } from '@ngx-translate/core'; @@ -13,7 +13,7 @@ describe('GroupSearchBoxComponent test suite', () => { let compAsAny: any; let fixture: ComponentFixture; let de; - let formBuilder: FormBuilder; + let formBuilder: UntypedFormBuilder; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ @@ -27,7 +27,7 @@ describe('GroupSearchBoxComponent test suite', () => { TestComponent ], providers: [ - FormBuilder, + UntypedFormBuilder, GroupSearchBoxComponent ], schemas: [ @@ -64,7 +64,7 @@ describe('GroupSearchBoxComponent test suite', () => { beforeEach(() => { // initTestScheduler(); fixture = TestBed.createComponent(GroupSearchBoxComponent); - formBuilder = TestBed.inject(FormBuilder); + formBuilder = TestBed.inject(UntypedFormBuilder); comp = fixture.componentInstance; compAsAny = fixture.componentInstance; }); diff --git a/src/app/shared/eperson-group-list/group-search-box/group-search-box.component.ts b/src/app/shared/eperson-group-list/group-search-box/group-search-box.component.ts index 3e45bb0336..154bee2d07 100644 --- a/src/app/shared/eperson-group-list/group-search-box/group-search-box.component.ts +++ b/src/app/shared/eperson-group-list/group-search-box/group-search-box.component.ts @@ -1,5 +1,5 @@ import { Component, EventEmitter, Output } from '@angular/core'; -import { FormBuilder } from '@angular/forms'; +import { UntypedFormBuilder } from '@angular/forms'; import { Subscription } from 'rxjs'; @@ -33,7 +33,7 @@ export class GroupSearchBoxComponent { */ @Output() search: EventEmitter = new EventEmitter(); - constructor(private formBuilder: FormBuilder) { + constructor(private formBuilder: UntypedFormBuilder) { this.searchForm = this.formBuilder.group(({ query: '', })); diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-form-control-container.component.spec.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-form-control-container.component.spec.ts index 08966f0f78..b77ee9950c 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-form-control-container.component.spec.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-form-control-container.component.spec.ts @@ -1,6 +1,6 @@ import { ComponentFixture, inject, TestBed, waitForAsync } from '@angular/core/testing'; import { CUSTOM_ELEMENTS_SCHEMA, DebugElement, NgZone, SimpleChange } from '@angular/core'; -import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; +import { UntypedFormControl, UntypedFormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; import { BrowserDynamicTestingModule } from '@angular/platform-browser-dynamic/testing'; import { By } from '@angular/platform-browser'; @@ -187,7 +187,7 @@ describe('DsDynamicFormControlContainerComponent test suite', () => { new DynamicQualdropModel({ id: 'combobox', readOnly: false, required: false }) ]; const testModel = formModel[8]; - let formGroup: FormGroup; + let formGroup: UntypedFormGroup; let fixture: ComponentFixture; let component: DsDynamicFormControlContainerComponent; let debugElement: DebugElement; @@ -270,8 +270,8 @@ describe('DsDynamicFormControlContainerComponent test suite', () => { it('should initialize correctly', () => { expect(component.context).toBeNull(); - expect(component.control instanceof FormControl).toBe(true); - expect(component.group instanceof FormGroup).toBe(true); + expect(component.control instanceof UntypedFormControl).toBe(true); + expect(component.group instanceof UntypedFormGroup).toBe(true); expect(component.model instanceof DynamicFormControlModel).toBe(true); expect(component.hasErrorMessaging).toBe(false); diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-form-control-container.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-form-control-container.component.ts index 5eee8f932d..ff5a119b6f 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-form-control-container.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-form-control-container.component.ts @@ -17,7 +17,7 @@ import { ViewChild, ViewContainerRef } from '@angular/core'; -import { FormArray, FormGroup } from '@angular/forms'; +import { UntypedFormArray, UntypedFormGroup } from '@angular/forms'; import { DYNAMIC_FORM_CONTROL_TYPE_ARRAY, @@ -199,12 +199,12 @@ export class DsDynamicFormControlContainerComponent extends DynamicFormControlCo @Input('templates') inputTemplateList: QueryList; @Input() hasMetadataModel: any; @Input() formId: string; - @Input() formGroup: FormGroup; + @Input() formGroup: UntypedFormGroup; @Input() formModel: DynamicFormControlModel[]; @Input() asBootstrapFormGroup = false; @Input() bindId = true; @Input() context: any | null = null; - @Input() group: FormGroup; + @Input() group: UntypedFormGroup; @Input() hostClass: string[]; @Input() hasErrorMessaging = false; @Input() layout = null as DynamicFormLayout; @@ -475,7 +475,7 @@ export class DsDynamicFormControlContainerComponent extends DynamicFormControlCo onRemove(): void { const arrayContext: DynamicFormArrayModel = (this.context as DynamicFormArrayGroupModel).context; const path = this.formBuilderService.getPath(arrayContext); - const formArrayControl = this.group.root.get(path) as FormArray; + const formArrayControl = this.group.root.get(path) as UntypedFormArray; this.formBuilderService.removeFormArrayGroup(this.context.index, formArrayControl, arrayContext); if (this.model.parent.context.groups.length === 0) { this.formBuilderService.addFormArrayGroup(formArrayControl, arrayContext); diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-form.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-form.component.ts index 537a1f0f52..45511d6941 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-form.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-form.component.ts @@ -8,7 +8,7 @@ import { QueryList, ViewChildren } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { DynamicFormComponent, DynamicFormControlContainerComponent, @@ -27,7 +27,7 @@ import { DsDynamicFormControlContainerComponent } from './ds-dynamic-form-contro export class DsDynamicFormComponent extends DynamicFormComponent { @Input() formId: string; - @Input() formGroup: FormGroup; + @Input() formGroup: UntypedFormGroup; @Input() formModel: DynamicFormControlModel[]; @Input() formLayout: DynamicFormLayout; diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-type-bind-relation.service.spec.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-type-bind-relation.service.spec.ts index 7f0c7e2e35..12b2409bf2 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-type-bind-relation.service.spec.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-type-bind-relation.service.spec.ts @@ -14,7 +14,7 @@ import { } from '../../../mocks/form-models.mock'; import {DsDynamicTypeBindRelationService} from './ds-dynamic-type-bind-relation.service'; import {FormFieldMetadataValueObject} from '../models/form-field-metadata-value.model'; -import {FormControl, ReactiveFormsModule} from '@angular/forms'; +import {UntypedFormControl, ReactiveFormsModule} from '@angular/forms'; import {FormBuilderService} from '../form-builder.service'; import {getMockFormBuilderService} from '../../../mocks/form-builder-service.mock'; import {Injector} from '@angular/core'; @@ -87,7 +87,7 @@ describe('DSDynamicTypeBindRelationService test suite', () => { it('Should receive one subscription to dc.type type binding"', () => { const testModel = mockInputWithTypeBindModel; testModel.typeBindRelations = getTypeBindRelations(['boundType']); - const dcTypeControl = new FormControl(); + const dcTypeControl = new UntypedFormControl(); dcTypeControl.setValue('boundType'); let subscriptions = service.subscribeRelations(testModel, dcTypeControl); expect(subscriptions).toHaveSize(1); @@ -96,7 +96,7 @@ describe('DSDynamicTypeBindRelationService test suite', () => { it('Expect hasMatch to be true (ie. this should be hidden)', () => { const testModel = mockInputWithTypeBindModel; testModel.typeBindRelations = getTypeBindRelations(['boundType']); - const dcTypeControl = new FormControl(); + const dcTypeControl = new UntypedFormControl(); dcTypeControl.setValue('boundType'); testModel.typeBindRelations[0].when[0].value = 'anotherType'; const relation = dynamicFormRelationService.findRelationByMatcher((testModel as any).typeBindRelations, HIDDEN_MATCHER); @@ -111,7 +111,7 @@ describe('DSDynamicTypeBindRelationService test suite', () => { it('Expect hasMatch to be false (ie. this should NOT be hidden)', () => { const testModel = mockInputWithTypeBindModel; testModel.typeBindRelations = getTypeBindRelations(['boundType']); - const dcTypeControl = new FormControl(); + const dcTypeControl = new UntypedFormControl(); dcTypeControl.setValue('boundType'); testModel.typeBindRelations[0].when[0].value = 'boundType'; const relation = dynamicFormRelationService.findRelationByMatcher((testModel as any).typeBindRelations, HIDDEN_MATCHER); diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-type-bind-relation.service.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-type-bind-relation.service.ts index 5dd4a6627d..d5e735ed1a 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-type-bind-relation.service.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/ds-dynamic-type-bind-relation.service.ts @@ -1,5 +1,5 @@ import { Inject, Injectable, Injector, Optional } from '@angular/core'; -import { FormControl } from '@angular/forms'; +import { UntypedFormControl } from '@angular/forms'; import { Subscription } from 'rxjs'; import { startWith } from 'rxjs/operators'; @@ -172,7 +172,7 @@ export class DsDynamicTypeBindRelationService { * @param model * @param control */ - subscribeRelations(model: DynamicFormControlModel, control: FormControl): Subscription[] { + subscribeRelations(model: DynamicFormControlModel, control: UntypedFormControl): Subscription[] { const relatedModels = this.getRelatedFormModel(model); const subscriptions: Subscription[] = []; diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/existing-metadata-list-element/existing-metadata-list-element.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/existing-metadata-list-element/existing-metadata-list-element.component.ts index 3160bccb41..aa50133e8a 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/existing-metadata-list-element/existing-metadata-list-element.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/existing-metadata-list-element/existing-metadata-list-element.component.ts @@ -1,6 +1,6 @@ /* eslint-disable max-classes-per-file */ import { Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output } from '@angular/core'; -import { FormControl } from '@angular/forms'; +import { UntypedFormControl } from '@angular/forms'; import { DynamicFormArrayGroupModel } from '@ng-dynamic-forms/core'; import { Store } from '@ngrx/store'; import { BehaviorSubject, Subscription } from 'rxjs'; @@ -64,7 +64,7 @@ export class ReorderableFormFieldMetadataValue extends Reorderable { constructor( public metadataValue: FormFieldMetadataValueObject, public model: DynamicConcatModel, - public control: FormControl, + public control: UntypedFormControl, public group: DynamicFormArrayGroupModel, oldIndex?: number, newIndex?: number diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/array-group/dynamic-form-array.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/array-group/dynamic-form-array.component.ts index 01bba74cc8..9d48bdac21 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/array-group/dynamic-form-array.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/array-group/dynamic-form-array.component.ts @@ -1,6 +1,6 @@ import { CdkDragDrop } from '@angular/cdk/drag-drop'; import { Component, EventEmitter, Input, Output, QueryList } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { DynamicFormArrayComponent, DynamicFormControlCustomEvent, @@ -26,7 +26,7 @@ export class DsDynamicFormArrayComponent extends DynamicFormArrayComponent { @Input() bindId = true; @Input() formModel: DynamicFormControlModel[]; @Input() formLayout: DynamicFormLayout; - @Input() group: FormGroup; + @Input() group: UntypedFormGroup; @Input() layout: DynamicFormControlLayout; @Input() model: DynamicRowArrayModel;// DynamicRow? @Input() templates: QueryList | undefined; diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/custom-switch/custom-switch.component.spec.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/custom-switch/custom-switch.component.spec.ts index 9f85ccc013..ceb498fe56 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/custom-switch/custom-switch.component.spec.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/custom-switch/custom-switch.component.spec.ts @@ -1,5 +1,5 @@ import { DynamicFormsCoreModule, DynamicFormService } from '@ng-dynamic-forms/core'; -import { FormGroup, ReactiveFormsModule } from '@angular/forms'; +import { UntypedFormGroup, ReactiveFormsModule } from '@angular/forms'; import { ComponentFixture, inject, TestBed, waitForAsync } from '@angular/core/testing'; import { DebugElement } from '@angular/core'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; @@ -11,7 +11,7 @@ describe('CustomSwitchComponent', () => { const testModel = new DynamicCustomSwitchModel({ id: 'switch' }); const formModel = [testModel]; - let formGroup: FormGroup; + let formGroup: UntypedFormGroup; let fixture: ComponentFixture; let component: CustomSwitchComponent; let debugElement: DebugElement; @@ -47,7 +47,7 @@ describe('CustomSwitchComponent', () => { it('should initialize correctly', () => { expect(component.bindId).toBe(true); - expect(component.group instanceof FormGroup).toBe(true); + expect(component.group instanceof UntypedFormGroup).toBe(true); expect(component.model instanceof DynamicCustomSwitchModel).toBe(true); expect(component.blur).toBeDefined(); diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/custom-switch/custom-switch.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/custom-switch/custom-switch.component.ts index 5b3f1e89e4..47780e66f6 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/custom-switch/custom-switch.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/custom-switch/custom-switch.component.ts @@ -1,5 +1,5 @@ import { Component, EventEmitter, Input, Output } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { DynamicNGBootstrapCheckboxComponent } from '@ng-dynamic-forms/ui-ng-bootstrap'; import { DynamicFormLayoutService, DynamicFormValidationService } from '@ng-dynamic-forms/core'; @@ -24,7 +24,7 @@ export class CustomSwitchComponent extends DynamicNGBootstrapCheckboxComponent { /** * The formgroup containing this component */ - @Input() group: FormGroup; + @Input() group: UntypedFormGroup; /** * The model used for displaying the switch diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/date-picker-inline/dynamic-date-picker-inline.component.spec.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/date-picker-inline/dynamic-date-picker-inline.component.spec.ts index 0756e48a8d..c0d1c83bf9 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/date-picker-inline/dynamic-date-picker-inline.component.spec.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/date-picker-inline/dynamic-date-picker-inline.component.spec.ts @@ -1,6 +1,6 @@ import { ComponentFixture, inject, TestBed, waitForAsync } from '@angular/core/testing'; import { DebugElement } from '@angular/core'; -import { FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'; +import { UntypedFormControl, UntypedFormGroup, ReactiveFormsModule } from '@angular/forms'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { By } from '@angular/platform-browser'; import { NgbDatepickerModule } from '@ng-bootstrap/ng-bootstrap'; @@ -11,7 +11,7 @@ describe('DsDatePickerInlineComponent test suite', () => { const testModel = new DynamicDatePickerModel({ id: 'datepicker' }); const formModel = [testModel]; - let formGroup: FormGroup; + let formGroup: UntypedFormGroup; let fixture: ComponentFixture; let component: DsDatePickerInlineComponent; let debugElement: DebugElement; @@ -53,8 +53,8 @@ describe('DsDatePickerInlineComponent test suite', () => { it('should initialize correctly', () => { expect(component.bindId).toBe(true); - expect(component.control instanceof FormControl).toBe(true); - expect(component.group instanceof FormGroup).toBe(true); + expect(component.control instanceof UntypedFormControl).toBe(true); + expect(component.group instanceof UntypedFormGroup).toBe(true); expect(component.model instanceof DynamicDatePickerModel).toBe(true); expect(component.blur).toBeDefined(); diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/date-picker-inline/dynamic-date-picker-inline.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/date-picker-inline/dynamic-date-picker-inline.component.ts index f23b6c1e7b..2eb6e9291c 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/date-picker-inline/dynamic-date-picker-inline.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/date-picker-inline/dynamic-date-picker-inline.component.ts @@ -1,5 +1,5 @@ import { Component, EventEmitter, Input, Output, ViewChild } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { NgbDatepicker, NgbDatepickerConfig } from '@ng-bootstrap/ng-bootstrap'; import { DynamicDatePickerModel, @@ -16,7 +16,7 @@ import { export class DsDatePickerInlineComponent extends DynamicFormControlComponent { @Input() bindId = true; - @Input() group: FormGroup; + @Input() group: UntypedFormGroup; @Input() layout: DynamicFormControlLayout; @Input() model: DynamicDatePickerModel; diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/date-picker/date-picker.component.spec.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/date-picker/date-picker.component.spec.ts index 4989dab93a..ffc36008c6 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/date-picker/date-picker.component.spec.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/date-picker/date-picker.component.spec.ts @@ -1,7 +1,7 @@ // Load the implementations that should be tested import { ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { ComponentFixture, inject, TestBed, waitForAsync, } from '@angular/core/testing'; -import { FormControl, FormGroup } from '@angular/forms'; +import { UntypedFormControl, UntypedFormGroup } from '@angular/forms'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { DynamicFormLayoutService, DynamicFormValidationService } from '@ng-dynamic-forms/core'; @@ -15,8 +15,8 @@ import { } from '../../../../../testing/dynamic-form-mock-services'; -export const DATE_TEST_GROUP = new FormGroup({ - date: new FormControl() +export const DATE_TEST_GROUP = new UntypedFormGroup({ + date: new UntypedFormControl() }); export const DATE_TEST_MODEL_CONFIG = { diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/date-picker/date-picker.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/date-picker/date-picker.component.ts index 78f9935829..8d5ce5b48e 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/date-picker/date-picker.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/date-picker/date-picker.component.ts @@ -1,5 +1,5 @@ import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { DynamicDsDatePickerModel } from './date-picker.model'; import { hasValue } from '../../../../../empty.util'; import { @@ -18,7 +18,7 @@ export const DS_DATE_PICKER_SEPARATOR = '-'; export class DsDatePickerComponent extends DynamicFormControlComponent implements OnInit { @Input() bindId = true; - @Input() group: FormGroup; + @Input() group: UntypedFormGroup; @Input() model: DynamicDsDatePickerModel; @Input() legend: string; diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/disabled/dynamic-disabled.component.spec.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/disabled/dynamic-disabled.component.spec.ts index 8cfa5c818a..a25ad4d231 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/disabled/dynamic-disabled.component.spec.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/disabled/dynamic-disabled.component.spec.ts @@ -1,6 +1,6 @@ import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core'; -import { FormControl, FormGroup, FormsModule } from '@angular/forms'; +import { UntypedFormControl, UntypedFormGroup, FormsModule } from '@angular/forms'; import { By } from '@angular/platform-browser'; import { TranslateModule } from '@ngx-translate/core'; @@ -31,8 +31,8 @@ describe('DsDynamicDisabledComponent', () => { name: 'disabledInput', hasSelectableMetadata: false }); - group = new FormGroup({ - disabledInput: new FormControl(), + group = new UntypedFormGroup({ + disabledInput: new UntypedFormControl(), }); } diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/disabled/dynamic-disabled.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/disabled/dynamic-disabled.component.ts index 974858b1cc..222ad51049 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/disabled/dynamic-disabled.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/disabled/dynamic-disabled.component.ts @@ -1,5 +1,5 @@ import { Component, EventEmitter, Input, Output } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { DynamicFormControlComponent, DynamicFormLayoutService, DynamicFormValidationService } from '@ng-dynamic-forms/core'; @@ -18,7 +18,7 @@ import { DynamicDisabledModel } from './dynamic-disabled.model'; export class DsDynamicDisabledComponent extends DynamicFormControlComponent { @Input() formId: string; - @Input() group: FormGroup; + @Input() group: UntypedFormGroup; @Input() model: DynamicDisabledModel; modelValuesString = ''; diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/ds-dynamic-concat.model.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/ds-dynamic-concat.model.ts index 1d6037a409..dc7c796648 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/ds-dynamic-concat.model.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/ds-dynamic-concat.model.ts @@ -46,6 +46,7 @@ export class DynamicConcatModel extends DynamicFormGroupModel { @serializable() submissionId: string; @serializable() hasSelectableMetadata: boolean; @serializable() metadataValue: MetadataValue; + @serializable() readOnly?: boolean; isCustomGroup = true; valueUpdates: Subject; @@ -65,6 +66,7 @@ export class DynamicConcatModel extends DynamicFormGroupModel { this.valueUpdates = new Subject(); this.valueUpdates.subscribe((value: string) => this.value = value); this.typeBindRelations = config.typeBindRelations ? config.typeBindRelations : []; + this.readOnly = config.disabled; } get value() { diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/ds-dynamic-input.model.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/ds-dynamic-input.model.ts index edbd5710d2..3c6abaa851 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/ds-dynamic-input.model.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/ds-dynamic-input.model.ts @@ -55,6 +55,7 @@ export class DsDynamicInputModel extends DynamicInputModel { this.metadataFields = config.metadataFields; this.hint = config.hint; this.readOnly = config.readOnly; + this.disabled = config.readOnly; this.value = config.value; this.relationship = config.relationship; this.submissionId = config.submissionId; diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/dynamic-vocabulary.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/dynamic-vocabulary.component.ts index 4c24443633..f19b660295 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/dynamic-vocabulary.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/dynamic-vocabulary.component.ts @@ -1,5 +1,5 @@ import { Component, EventEmitter, Input, Output } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { DynamicFormControlComponent, @@ -25,7 +25,7 @@ import { PageInfo } from '../../../../../core/shared/page-info.model'; }) export abstract class DsDynamicVocabularyComponent extends DynamicFormControlComponent { - @Input() abstract group: FormGroup; + @Input() abstract group: UntypedFormGroup; @Input() abstract model: DsDynamicInputModel; @Output() abstract blur: EventEmitter; @@ -53,7 +53,7 @@ export abstract class DsDynamicVocabularyComponent extends DynamicFormControlCom */ getInitValueFromModel(): Observable { let initValue$: Observable; - if (isNotEmpty(this.model.value) && (this.model.value instanceof FormFieldMetadataValueObject)) { + if (isNotEmpty(this.model.value) && (this.model.value instanceof FormFieldMetadataValueObject) && !this.model.value.hasAuthorityToGenerate()) { let initEntry$: Observable; if (this.model.value.hasAuthority()) { initEntry$ = this.vocabularyService.getVocabularyEntryByID(this.model.value.authority, this.model.vocabularyOptions); diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/form-group/dynamic-form-group.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/form-group/dynamic-form-group.component.ts index 9d8d73eab5..cfd1bc293c 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/form-group/dynamic-form-group.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/form-group/dynamic-form-group.component.ts @@ -1,5 +1,5 @@ import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output, QueryList } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { DynamicFormControlComponent, DynamicFormControlCustomEvent, @@ -22,7 +22,7 @@ export class DsDynamicFormGroupComponent extends DynamicFormControlComponent { @Input() formModel: DynamicFormControlModel[]; @Input() formLayout: DynamicFormLayout; - @Input() group: FormGroup; + @Input() group: UntypedFormGroup; @Input() layout: DynamicFormControlLayout; @Input() model: DynamicFormGroupModel; @Input() templates: QueryList | DynamicTemplateDirective[] | undefined; diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/list/dynamic-list.component.spec.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/list/dynamic-list.component.spec.ts index b4a02457dc..51ce584bb1 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/list/dynamic-list.component.spec.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/list/dynamic-list.component.spec.ts @@ -1,6 +1,6 @@ // Load the implementations that should be tested import { ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; -import { FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; +import { UntypedFormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; import { ComponentFixture, inject, TestBed, waitForAsync, } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; @@ -136,9 +136,9 @@ describe('DsDynamicListComponent test suite', () => { listFixture = TestBed.createComponent(DsDynamicListComponent); listComp = listFixture.componentInstance; // FormComponent test instance - listComp.group = new FormGroup({ - listCheckbox: new FormGroup({}), - listRadio: new FormGroup({}) + listComp.group = new UntypedFormGroup({ + listCheckbox: new UntypedFormGroup({}), + listRadio: new UntypedFormGroup({}) }); listComp.model = new DynamicListCheckboxGroupModel(LIST_CHECKBOX_TEST_MODEL_CONFIG, LAYOUT_TEST); listFixture.detectChanges(); @@ -184,9 +184,9 @@ describe('DsDynamicListComponent test suite', () => { listFixture = TestBed.createComponent(DsDynamicListComponent); listComp = listFixture.componentInstance; // FormComponent test instance - listComp.group = new FormGroup({ - listCheckbox: new FormGroup({}), - listRadio: new FormGroup({}) + listComp.group = new UntypedFormGroup({ + listCheckbox: new UntypedFormGroup({}), + listRadio: new UntypedFormGroup({}) }); listComp.model = new DynamicListCheckboxGroupModel(LIST_CHECKBOX_TEST_MODEL_CONFIG, LAYOUT_TEST); modelValue = [Object.assign(new VocabularyEntry(), { authority: 1, display: 'one', value: 1 })]; @@ -224,9 +224,9 @@ describe('DsDynamicListComponent test suite', () => { listFixture = TestBed.createComponent(DsDynamicListComponent); listComp = listFixture.componentInstance; // FormComponent test instance - listComp.group = new FormGroup({ - listCheckbox: new FormGroup({}), - listRadio: new FormGroup({}) + listComp.group = new UntypedFormGroup({ + listCheckbox: new UntypedFormGroup({}), + listRadio: new UntypedFormGroup({}) }); listComp.model = new DynamicListRadioGroupModel(LIST_RADIO_TEST_MODEL_CONFIG, LAYOUT_TEST); listFixture.detectChanges(); @@ -260,9 +260,9 @@ describe('DsDynamicListComponent test suite', () => { listFixture = TestBed.createComponent(DsDynamicListComponent); listComp = listFixture.componentInstance; // FormComponent test instance - listComp.group = new FormGroup({ - listCheckbox: new FormGroup({}), - listRadio: new FormGroup({}) + listComp.group = new UntypedFormGroup({ + listCheckbox: new UntypedFormGroup({}), + listRadio: new UntypedFormGroup({}) }); listComp.model = new DynamicListRadioGroupModel(LIST_RADIO_TEST_MODEL_CONFIG, LAYOUT_TEST); modelValue = Object.assign(new VocabularyEntry(), { authority: 1, display: 'one', value: 1 }); @@ -291,9 +291,9 @@ describe('DsDynamicListComponent test suite', () => { }) class TestComponent { - group: FormGroup = new FormGroup({ - listCheckbox: new FormGroup({}), - listRadio: new FormGroup({}) + group: UntypedFormGroup = new UntypedFormGroup({ + listCheckbox: new UntypedFormGroup({}), + listRadio: new UntypedFormGroup({}) }); model = new DynamicListCheckboxGroupModel(LIST_CHECKBOX_TEST_MODEL_CONFIG, LAYOUT_TEST); diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/list/dynamic-list.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/list/dynamic-list.component.ts index 88158f9414..aa62e5b40d 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/list/dynamic-list.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/list/dynamic-list.component.ts @@ -1,5 +1,5 @@ import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; -import { FormGroup, ValidatorFn, ValidationErrors, AbstractControl } from '@angular/forms'; +import { UntypedFormGroup, ValidatorFn, ValidationErrors, AbstractControl } from '@angular/forms'; import { DynamicCheckboxModel, DynamicFormControlComponent, @@ -35,7 +35,7 @@ export interface ListItem { }) export class DsDynamicListComponent extends DynamicFormControlComponent implements OnInit { - @Input() group: FormGroup; + @Input() group: UntypedFormGroup; @Input() model: any; @Output() blur: EventEmitter = new EventEmitter(); @@ -108,7 +108,7 @@ export class DsDynamicListComponent extends DynamicFormControlComponent implemen */ protected setOptionsFromVocabulary() { if (this.model.vocabularyOptions.name && this.model.vocabularyOptions.name.length > 0) { - const listGroup = this.group.controls[this.model.id] as FormGroup; + const listGroup = this.group.controls[this.model.id] as UntypedFormGroup; if (this.model.repeatable && this.model.required) { listGroup.addValidators(this.hasAtLeastOneVocabularyEntry()); } diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/lookup/dynamic-lookup.component.spec.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/lookup/dynamic-lookup.component.spec.ts index 27029ff2be..2fea4fc985 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/lookup/dynamic-lookup.component.spec.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/lookup/dynamic-lookup.component.spec.ts @@ -1,6 +1,6 @@ // Load the implementations that should be tested import { ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; -import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; +import { UntypedFormControl, UntypedFormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; import { ComponentFixture, fakeAsync, inject, TestBed, tick, waitForAsync, } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; @@ -71,9 +71,9 @@ let LOOKUP_NAME_TEST_MODEL_CONFIG = { hasSelectableMetadata: false }; -let LOOKUP_TEST_GROUP = new FormGroup({ - lookup: new FormControl(), - lookupName: new FormControl() +let LOOKUP_TEST_GROUP = new UntypedFormGroup({ + lookup: new UntypedFormControl(), + lookupName: new UntypedFormControl() }); describe('Dynamic Lookup component', () => { @@ -122,9 +122,9 @@ describe('Dynamic Lookup component', () => { hasSelectableMetadata: false }; - LOOKUP_TEST_GROUP = new FormGroup({ - lookup: new FormControl(), - lookupName: new FormControl() + LOOKUP_TEST_GROUP = new UntypedFormGroup({ + lookup: new UntypedFormControl(), + lookupName: new UntypedFormControl() }); } @@ -564,7 +564,7 @@ describe('Dynamic Lookup component', () => { }) class TestComponent { - group: FormGroup = LOOKUP_TEST_GROUP; + group: UntypedFormGroup = LOOKUP_TEST_GROUP; inputLookupModelConfig = LOOKUP_TEST_MODEL_CONFIG; diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/lookup/dynamic-lookup.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/lookup/dynamic-lookup.component.ts index 3993704895..63545f45d2 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/lookup/dynamic-lookup.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/lookup/dynamic-lookup.component.ts @@ -1,5 +1,5 @@ import { ChangeDetectorRef, Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { of as observableOf, Subscription } from 'rxjs'; import { catchError, distinctUntilChanged } from 'rxjs/operators'; @@ -30,7 +30,7 @@ import { DsDynamicVocabularyComponent } from '../dynamic-vocabulary.component'; }) export class DsDynamicLookupComponent extends DsDynamicVocabularyComponent implements OnDestroy, OnInit { - @Input() group: FormGroup; + @Input() group: UntypedFormGroup; @Input() model: any; @Output() blur: EventEmitter = new EventEmitter(); diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/onebox/dynamic-onebox.component.html b/src/app/shared/form/builder/ds-dynamic-form-ui/models/onebox/dynamic-onebox.component.html index e6b0cf508f..3c19ecda13 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/onebox/dynamic-onebox.component.html +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/onebox/dynamic-onebox.component.html @@ -39,6 +39,7 @@ [ngbTypeahead]="search" [placeholder]="model.placeholder" [readonly]="model.readOnly" + [disabled]="model.readOnly" [resultTemplate]="rt" [type]="model.inputType" [(ngModel)]="currentValue" @@ -63,6 +64,7 @@ [name]="model.name" [placeholder]="model.placeholder" [readonly]="true" + [disabled]="model.readOnly" [type]="model.inputType" [value]="currentValue?.display" (focus)="onFocus($event)" diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/onebox/dynamic-onebox.component.spec.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/onebox/dynamic-onebox.component.spec.ts index cf417145a7..69520aba63 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/onebox/dynamic-onebox.component.spec.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/onebox/dynamic-onebox.component.spec.ts @@ -1,7 +1,7 @@ /* eslint-disable max-classes-per-file */ // Load the implementations that should be tested import { ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; -import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; +import { UntypedFormControl, UntypedFormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; import { ComponentFixture, fakeAsync, inject, TestBed, tick, } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { CdkTreeModule } from '@angular/cdk/tree'; @@ -47,8 +47,8 @@ export class MockNgbModalRef { } function init() { - ONEBOX_TEST_GROUP = new FormGroup({ - onebox: new FormControl(), + ONEBOX_TEST_GROUP = new UntypedFormGroup({ + onebox: new UntypedFormControl(), }); ONEBOX_TEST_MODEL_CONFIG = { @@ -457,7 +457,7 @@ describe('DsDynamicOneboxComponent test suite', () => { }) class TestComponent { - group: FormGroup = ONEBOX_TEST_GROUP; + group: UntypedFormGroup = ONEBOX_TEST_GROUP; model = new DynamicOneboxModel(ONEBOX_TEST_MODEL_CONFIG); diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/onebox/dynamic-onebox.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/onebox/dynamic-onebox.component.ts index 008328bf73..2ff4256404 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/onebox/dynamic-onebox.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/onebox/dynamic-onebox.component.ts @@ -1,5 +1,5 @@ import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { DynamicFormLayoutService, DynamicFormValidationService } from '@ng-dynamic-forms/core'; import { @@ -30,8 +30,8 @@ import { VocabularyEntry } from '../../../../../../core/submission/vocabularies/ import { PageInfo } from '../../../../../../core/shared/page-info.model'; import { DsDynamicVocabularyComponent } from '../dynamic-vocabulary.component'; import { Vocabulary } from '../../../../../../core/submission/vocabularies/models/vocabulary.model'; -import { VocabularyTreeviewComponent } from '../../../../vocabulary-treeview/vocabulary-treeview.component'; import { VocabularyEntryDetail } from '../../../../../../core/submission/vocabularies/models/vocabulary-entry-detail.model'; +import { VocabularyTreeviewModalComponent } from '../../../../vocabulary-treeview-modal/vocabulary-treeview-modal.component'; /** * Component representing a onebox input field. @@ -44,7 +44,7 @@ import { VocabularyEntryDetail } from '../../../../../../core/submission/vocabul }) export class DsDynamicOneboxComponent extends DsDynamicVocabularyComponent implements OnInit { - @Input() group: FormGroup; + @Input() group: UntypedFormGroup; @Input() model: DynamicOneboxModel; @Output() blur: EventEmitter = new EventEmitter(); @@ -216,16 +216,19 @@ export class DsDynamicOneboxComponent extends DsDynamicVocabularyComponent imple * @param event The click event fired */ openTree(event) { + if (this.model.readOnly) { + return; + } event.preventDefault(); event.stopImmediatePropagation(); this.subs.push(this.vocabulary$.pipe( map((vocabulary: Vocabulary) => vocabulary.preloadLevel), take(1) ).subscribe((preloadLevel) => { - const modalRef: NgbModalRef = this.modalService.open(VocabularyTreeviewComponent, { size: 'lg', windowClass: 'treeview' }); + const modalRef: NgbModalRef = this.modalService.open(VocabularyTreeviewModalComponent, { size: 'lg', windowClass: 'treeview' }); modalRef.componentInstance.vocabularyOptions = this.model.vocabularyOptions; modalRef.componentInstance.preloadLevel = preloadLevel; - modalRef.componentInstance.selectedItem = this.currentValue ? this.currentValue : ''; + modalRef.componentInstance.selectedItems = this.currentValue ? [this.currentValue.value] : []; modalRef.result.then((result: VocabularyEntryDetail) => { if (result) { this.currentValue = result; diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/relation-group/dynamic-relation-group.component.spec.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/relation-group/dynamic-relation-group.component.spec.ts index 733758fd27..feca7f95c6 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/relation-group/dynamic-relation-group.component.spec.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/relation-group/dynamic-relation-group.component.spec.ts @@ -1,7 +1,7 @@ // Load the implementations that should be tested import { ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { ComponentFixture, inject, TestBed, waitForAsync, } from '@angular/core/testing'; -import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; +import { UntypedFormControl, UntypedFormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { Store, StoreModule } from '@ngrx/store'; @@ -83,8 +83,8 @@ function init() { hasSelectableMetadata: false } as DynamicRelationGroupModelConfig; - FORM_GROUP_TEST_GROUP = new FormGroup({ - dc_contributor_author: new FormControl(), + FORM_GROUP_TEST_GROUP = new UntypedFormGroup({ + dc_contributor_author: new UntypedFormControl(), }); } @@ -96,9 +96,9 @@ describe('DsDynamicRelationGroupComponent test suite', () => { let groupFixture: ComponentFixture; let modelValue: any; let html; - let control1: FormControl; + let control1: UntypedFormControl; let model1: DsDynamicInputModel; - let control2: FormControl; + let control2: UntypedFormControl; let model2: DsDynamicInputModel; // waitForAsync beforeEach @@ -170,9 +170,9 @@ describe('DsDynamicRelationGroupComponent test suite', () => { groupComp.group = FORM_GROUP_TEST_GROUP; groupComp.model = new DynamicRelationGroupModel(FORM_GROUP_TEST_MODEL_CONFIG); groupFixture.detectChanges(); - control1 = service.getFormControlById('dc_contributor_author', (groupComp as any).formRef.formGroup, groupComp.formModel) as FormControl; + control1 = service.getFormControlById('dc_contributor_author', (groupComp as any).formRef.formGroup, groupComp.formModel) as UntypedFormControl; model1 = service.findById('dc_contributor_author', groupComp.formModel) as DsDynamicInputModel; - control2 = service.getFormControlById('local_contributor_affiliation', (groupComp as any).formRef.formGroup, groupComp.formModel) as FormControl; + control2 = service.getFormControlById('local_contributor_affiliation', (groupComp as any).formRef.formGroup, groupComp.formModel) as UntypedFormControl; model2 = service.findById('local_contributor_affiliation', groupComp.formModel) as DsDynamicInputModel; // spyOn(store, 'dispatch'); @@ -272,7 +272,7 @@ describe('DsDynamicRelationGroupComponent test suite', () => { groupComp.onChipSelected(0); groupFixture.detectChanges(); - control1 = service.getFormControlById('dc_contributor_author', (groupComp as any).formRef.formGroup, groupComp.formModel) as FormControl; + control1 = service.getFormControlById('dc_contributor_author', (groupComp as any).formRef.formGroup, groupComp.formModel) as UntypedFormControl; model1 = service.findById('dc_contributor_author', groupComp.formModel) as DsDynamicInputModel; control1.setValue('test author modify'); diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/relation-group/dynamic-relation-group.components.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/relation-group/dynamic-relation-group.components.ts index fd111e44c2..7fdfb61b74 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/relation-group/dynamic-relation-group.components.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/relation-group/dynamic-relation-group.components.ts @@ -1,5 +1,5 @@ import { ChangeDetectorRef, Component, EventEmitter, Input, OnDestroy, OnInit, Output, ViewChild } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { combineLatest, Observable, of as observableOf, Subscription } from 'rxjs'; import { filter, map, mergeMap, scan } from 'rxjs/operators'; @@ -43,7 +43,7 @@ import { VocabularyEntryDetail } from '../../../../../../core/submission/vocabul export class DsDynamicRelationGroupComponent extends DynamicFormControlComponent implements OnDestroy, OnInit { @Input() formId: string; - @Input() group: FormGroup; + @Input() group: UntypedFormGroup; @Input() model: DynamicRelationGroupModel; @Output() blur: EventEmitter = new EventEmitter(); diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/scrollable-dropdown/dynamic-scrollable-dropdown.component.html b/src/app/shared/form/builder/ds-dynamic-form-ui/models/scrollable-dropdown/dynamic-scrollable-dropdown.component.html index 8a4d502287..6e2d29b789 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/scrollable-dropdown/dynamic-scrollable-dropdown.component.html +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/scrollable-dropdown/dynamic-scrollable-dropdown.component.html @@ -3,8 +3,10 @@ role="combobox" [attr.aria-label]="model.label" [attr.aria-owns]="'combobox_' + id + '_listbox'"> - + + + (keydown)="selectOnKeyDown($event, sdRef)">
    { }) class TestComponent { - group: FormGroup = SD_TEST_GROUP; + group: UntypedFormGroup = SD_TEST_GROUP; model = new DynamicScrollableDropdownModel(SD_TEST_MODEL_CONFIG); diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/scrollable-dropdown/dynamic-scrollable-dropdown.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/scrollable-dropdown/dynamic-scrollable-dropdown.component.ts index 5e35df5ef7..a4ca210193 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/scrollable-dropdown/dynamic-scrollable-dropdown.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/scrollable-dropdown/dynamic-scrollable-dropdown.component.ts @@ -1,5 +1,5 @@ import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { Observable, of as observableOf } from 'rxjs'; import { catchError, distinctUntilChanged, map, tap } from 'rxjs/operators'; @@ -29,7 +29,7 @@ import { FormFieldMetadataValueObject } from '../../../models/form-field-metadat }) export class DsDynamicScrollableDropdownComponent extends DsDynamicVocabularyComponent implements OnInit { @Input() bindId = true; - @Input() group: FormGroup; + @Input() group: UntypedFormGroup; @Input() model: DynamicScrollableDropdownModel; @Output() blur: EventEmitter = new EventEmitter(); @@ -98,6 +98,23 @@ export class DsDynamicScrollableDropdownComponent extends DsDynamicVocabularyCom } } + /** + * KeyDown handler to allow toggling the dropdown via keyboard + * @param event KeyboardEvent + * @param sdRef The reference of the NgbDropdown. + */ + selectOnKeyDown(event: KeyboardEvent, sdRef: NgbDropdown) { + const keyName = event.key; + + if (keyName === ' ' || keyName === 'Enter') { + event.preventDefault(); + event.stopPropagation(); + sdRef.toggle(); + } else if (keyName === 'ArrowDown' || keyName === 'ArrowUp') { + this.openDropdown(sdRef); + } + } + /** * Loads any new entries */ diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/tag/dynamic-tag.component.spec.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/tag/dynamic-tag.component.spec.ts index 162d9c3cec..a6a4c45170 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/tag/dynamic-tag.component.spec.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/tag/dynamic-tag.component.spec.ts @@ -1,6 +1,6 @@ // Load the implementations that should be tested import { ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; -import { FormControl, FormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; +import { UntypedFormControl, UntypedFormGroup, FormsModule, ReactiveFormsModule } from '@angular/forms'; import { ComponentFixture, fakeAsync, flush, inject, TestBed, waitForAsync, } from '@angular/core/testing'; import { of as observableOf } from 'rxjs'; @@ -39,8 +39,8 @@ let TAG_TEST_GROUP; let TAG_TEST_MODEL_CONFIG; function init() { - TAG_TEST_GROUP = new FormGroup({ - tag: new FormControl(), + TAG_TEST_GROUP = new UntypedFormGroup({ + tag: new UntypedFormControl(), }); TAG_TEST_MODEL_CONFIG = { @@ -291,7 +291,7 @@ describe('DsDynamicTagComponent test suite', () => { }) class TestComponent { - group: FormGroup = TAG_TEST_GROUP; + group: UntypedFormGroup = TAG_TEST_GROUP; model = new DynamicTagModel(TAG_TEST_MODEL_CONFIG); diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/tag/dynamic-tag.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/tag/dynamic-tag.component.ts index 1c015be747..4abb68a53b 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/tag/dynamic-tag.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/tag/dynamic-tag.component.ts @@ -1,5 +1,5 @@ import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core'; -import { FormGroup } from '@angular/forms'; +import { UntypedFormGroup } from '@angular/forms'; import { DynamicFormLayoutService, DynamicFormValidationService } from '@ng-dynamic-forms/core'; import { Observable, of as observableOf } from 'rxjs'; @@ -32,7 +32,7 @@ import { DsDynamicVocabularyComponent } from '../dynamic-vocabulary.component'; export class DsDynamicTagComponent extends DsDynamicVocabularyComponent implements OnInit { @Input() bindId = true; - @Input() group: FormGroup; + @Input() group: UntypedFormGroup; @Input() model: DynamicTagModel; @Output() blur: EventEmitter = new EventEmitter(); diff --git a/src/app/shared/form/builder/form-builder.service.spec.ts b/src/app/shared/form/builder/form-builder.service.spec.ts index 7d1a9a3986..fd3588e73e 100644 --- a/src/app/shared/form/builder/form-builder.service.spec.ts +++ b/src/app/shared/form/builder/form-builder.service.spec.ts @@ -1,8 +1,8 @@ import { inject, TestBed } from '@angular/core/testing'; import { - FormArray, - FormControl, - FormGroup, + UntypedFormArray, + UntypedFormControl, + UntypedFormGroup, NG_ASYNC_VALIDATORS, NG_VALIDATORS, ReactiveFormsModule @@ -683,21 +683,21 @@ describe('FormBuilderService test suite', () => { const formGroup = service.createFormGroup(testModel); - expect(formGroup instanceof FormGroup).toBe(true); + expect(formGroup instanceof UntypedFormGroup).toBe(true); - expect(formGroup.get('testCheckbox') instanceof FormControl).toBe(true); - expect(formGroup.get('testCheckboxGroup') instanceof FormGroup).toBe(true); - expect(formGroup.get('testDatepicker') instanceof FormControl).toBe(true); - expect(formGroup.get('testFormArray') instanceof FormArray).toBe(true); - expect(formGroup.get('testInput') instanceof FormControl).toBe(true); - expect(formGroup.get('testRadioGroup') instanceof FormControl).toBe(true); - expect(formGroup.get('testSelect') instanceof FormControl).toBe(true); - expect(formGroup.get('testTextArea') instanceof FormControl).toBe(true); - expect(formGroup.get('testFileUpload') instanceof FormControl).toBe(true); - expect(formGroup.get('testEditor') instanceof FormControl).toBe(true); - expect(formGroup.get('testTimePicker') instanceof FormControl).toBe(true); - expect(formGroup.get('testRating') instanceof FormControl).toBe(true); - expect(formGroup.get('testColorPicker') instanceof FormControl).toBe(true); + expect(formGroup.get('testCheckbox') instanceof UntypedFormControl).toBe(true); + expect(formGroup.get('testCheckboxGroup') instanceof UntypedFormGroup).toBe(true); + expect(formGroup.get('testDatepicker') instanceof UntypedFormControl).toBe(true); + expect(formGroup.get('testFormArray') instanceof UntypedFormArray).toBe(true); + expect(formGroup.get('testInput') instanceof UntypedFormControl).toBe(true); + expect(formGroup.get('testRadioGroup') instanceof UntypedFormControl).toBe(true); + expect(formGroup.get('testSelect') instanceof UntypedFormControl).toBe(true); + expect(formGroup.get('testTextArea') instanceof UntypedFormControl).toBe(true); + expect(formGroup.get('testFileUpload') instanceof UntypedFormControl).toBe(true); + expect(formGroup.get('testEditor') instanceof UntypedFormControl).toBe(true); + expect(formGroup.get('testTimePicker') instanceof UntypedFormControl).toBe(true); + expect(formGroup.get('testRating') instanceof UntypedFormControl).toBe(true); + expect(formGroup.get('testColorPicker') instanceof UntypedFormControl).toBe(true); }); it('should throw when unknown DynamicFormControlModel id is specified in JSON', () => { @@ -720,7 +720,7 @@ describe('FormBuilderService test suite', () => { it('should add a form control to an existing form group', () => { const formGroup = service.createFormGroup(testModel); - const nestedFormGroup = formGroup.controls.testFormGroup as FormGroup; + const nestedFormGroup = formGroup.controls.testFormGroup as UntypedFormGroup; const nestedFormGroupModel = testModel[7] as DynamicFormGroupModel; const newModel1 = new DynamicInputModel({ id: 'newInput1' }); const newModel2 = new DynamicInputModel({ id: 'newInput2' }); @@ -731,14 +731,14 @@ describe('FormBuilderService test suite', () => { expect(formGroup.controls[newModel1.id]).toBeTruthy(); expect(testModel[testModel.length - 1] === newModel1).toBe(true); - expect((formGroup.controls.testFormGroup as FormGroup).controls[newModel2.id]).toBeTruthy(); + expect((formGroup.controls.testFormGroup as UntypedFormGroup).controls[newModel2.id]).toBeTruthy(); expect(nestedFormGroupModel.get(nestedFormGroupModel.group.length - 1) === newModel2).toBe(true); }); it('should insert a form control to an existing form group', () => { const formGroup = service.createFormGroup(testModel); - const nestedFormGroup = formGroup.controls.testFormGroup as FormGroup; + const nestedFormGroup = formGroup.controls.testFormGroup as UntypedFormGroup; const nestedFormGroupModel = testModel[7] as DynamicFormGroupModel; const newModel1 = new DynamicInputModel({ id: 'newInput1' }); const newModel2 = new DynamicInputModel({ id: 'newInput2' }); @@ -750,7 +750,7 @@ describe('FormBuilderService test suite', () => { expect(testModel[4] === newModel1).toBe(true); expect(service.getPath(testModel[4])).toEqual(['newInput1']); - expect((formGroup.controls.testFormGroup as FormGroup).controls[newModel2.id]).toBeTruthy(); + expect((formGroup.controls.testFormGroup as UntypedFormGroup).controls[newModel2.id]).toBeTruthy(); expect(nestedFormGroupModel.get(0) === newModel2).toBe(true); expect(service.getPath(nestedFormGroupModel.get(0))).toEqual(['testFormGroup', 'newInput2']); }); @@ -769,14 +769,14 @@ describe('FormBuilderService test suite', () => { service.moveFormGroupControl(0, 1, nestedFormGroupModel); - expect((formGroup.controls.testFormGroup as FormGroup).controls[model2.id]).toBeTruthy(); + expect((formGroup.controls.testFormGroup as UntypedFormGroup).controls[model2.id]).toBeTruthy(); expect(nestedFormGroupModel.get(1) === model2).toBe(true); }); it('should remove a form control from an existing form group', () => { const formGroup = service.createFormGroup(testModel); - const nestedFormGroup = formGroup.controls.testFormGroup as FormGroup; + const nestedFormGroup = formGroup.controls.testFormGroup as UntypedFormGroup; const nestedFormGroupModel = testModel[7] as DynamicFormGroupModel; const length = testModel.length; const size = nestedFormGroupModel.size(); @@ -810,7 +810,7 @@ describe('FormBuilderService test suite', () => { formArray = service.createFormArray(model); - expect(formArray instanceof FormArray).toBe(true); + expect(formArray instanceof UntypedFormArray).toBe(true); expect(formArray.length).toBe(model.initialCount); }); @@ -841,8 +841,8 @@ describe('FormBuilderService test suite', () => { const index = 3; const step = 1; - (formArray.at(index) as FormGroup).controls.testFormArrayGroupInput.setValue('next test value 1'); - (formArray.at(index + step) as FormGroup).controls.testFormArrayGroupInput.setValue('next test value 2'); + (formArray.at(index) as UntypedFormGroup).controls.testFormArrayGroupInput.setValue('next test value 1'); + (formArray.at(index + step) as UntypedFormGroup).controls.testFormArrayGroupInput.setValue('next test value 2'); (model.get(index).get(0) as DynamicFormValueControlModel).value = 'next test value 1'; (model.get(index + step).get(0) as DynamicFormValueControlModel).value = 'next test value 2'; @@ -851,8 +851,8 @@ describe('FormBuilderService test suite', () => { expect(formArray.length).toBe(model.initialCount); - expect((formArray.at(index) as FormGroup).controls.testFormArrayGroupInput.value).toEqual('next test value 2'); - expect((formArray.at(index + step) as FormGroup).controls.testFormArrayGroupInput.value).toEqual('next test value 1'); + expect((formArray.at(index) as UntypedFormGroup).controls.testFormArrayGroupInput.value).toEqual('next test value 2'); + expect((formArray.at(index + step) as UntypedFormGroup).controls.testFormArrayGroupInput.value).toEqual('next test value 1'); expect((model.get(index).get(0) as DynamicFormValueControlModel).value).toEqual('next test value 2'); expect((model.get(index + step).get(0) as DynamicFormValueControlModel).value).toEqual('next test value 1'); @@ -865,8 +865,8 @@ describe('FormBuilderService test suite', () => { const index = 3; const step = -1; - (formArray.at(index) as FormGroup).controls.testFormArrayGroupInput.setValue('next test value 1'); - (formArray.at(index + step) as FormGroup).controls.testFormArrayGroupInput.setValue('next test value 2'); + (formArray.at(index) as UntypedFormGroup).controls.testFormArrayGroupInput.setValue('next test value 1'); + (formArray.at(index + step) as UntypedFormGroup).controls.testFormArrayGroupInput.setValue('next test value 2'); (model.get(index).get(0) as DynamicFormValueControlModel).value = 'next test value 1'; (model.get(index + step).get(0) as DynamicFormValueControlModel).value = 'next test value 2'; @@ -875,8 +875,8 @@ describe('FormBuilderService test suite', () => { expect(formArray.length).toBe(model.initialCount); - expect((formArray.at(index) as FormGroup).controls.testFormArrayGroupInput.value).toEqual('next test value 2'); - expect((formArray.at(index + step) as FormGroup).controls.testFormArrayGroupInput.value).toEqual('next test value 1'); + expect((formArray.at(index) as UntypedFormGroup).controls.testFormArrayGroupInput.value).toEqual('next test value 2'); + expect((formArray.at(index + step) as UntypedFormGroup).controls.testFormArrayGroupInput.value).toEqual('next test value 1'); expect((model.get(index).get(0) as DynamicFormValueControlModel).value).toEqual('next test value 2'); expect((model.get(index + step).get(0) as DynamicFormValueControlModel).value).toEqual('next test value 1'); diff --git a/src/app/shared/form/builder/form-builder.service.ts b/src/app/shared/form/builder/form-builder.service.ts index b3a78d4669..cf6f38bf7b 100644 --- a/src/app/shared/form/builder/form-builder.service.ts +++ b/src/app/shared/form/builder/form-builder.service.ts @@ -1,5 +1,5 @@ import {Injectable, Optional} from '@angular/core'; -import { AbstractControl, FormControl, FormGroup } from '@angular/forms'; +import { AbstractControl, UntypedFormControl, UntypedFormGroup } from '@angular/forms'; import { DYNAMIC_FORM_CONTROL_TYPE_ARRAY, @@ -59,7 +59,7 @@ export class FormBuilderService extends DynamicFormService { /** * This map contains the active forms control groups */ - private formGroups: Map; + private formGroups: Map; /** * This is the field to use for type binding @@ -83,7 +83,7 @@ export class FormBuilderService extends DynamicFormService { } - createDynamicFormControlEvent(control: FormControl, group: FormGroup, model: DynamicFormControlModel, type: string): DynamicFormControlEvent { + createDynamicFormControlEvent(control: UntypedFormControl, group: UntypedFormGroup, model: DynamicFormControlModel, type: string): DynamicFormControlEvent { const $event = { value: (model as any).value, autoSave: false @@ -369,12 +369,12 @@ export class FormBuilderService extends DynamicFormService { return model.type === DYNAMIC_FORM_CONTROL_TYPE_INPUT; } - getFormControlById(id: string, formGroup: FormGroup, groupModel: DynamicFormControlModel[], index = 0): AbstractControl { + getFormControlById(id: string, formGroup: UntypedFormGroup, groupModel: DynamicFormControlModel[], index = 0): AbstractControl { const fieldModel = this.findById(id, groupModel, index); return isNotEmpty(fieldModel) ? formGroup.get(this.getPath(fieldModel)) : null; } - getFormControlByModel(formGroup: FormGroup, fieldModel: DynamicFormControlModel): AbstractControl { + getFormControlByModel(formGroup: UntypedFormGroup, fieldModel: DynamicFormControlModel): AbstractControl { return isNotEmpty(fieldModel) ? formGroup.get(this.getPath(fieldModel)) : null; } @@ -412,7 +412,7 @@ export class FormBuilderService extends DynamicFormService { * @param id id of model * @param formGroup FormGroup */ - addFormGroups(id: string, formGroup: FormGroup): void { + addFormGroups(id: string, formGroup: UntypedFormGroup): void { this.formGroups.set(id, formGroup); } diff --git a/src/app/shared/form/builder/models/form-field-metadata-value.model.ts b/src/app/shared/form/builder/models/form-field-metadata-value.model.ts index b58844a537..9b18084e40 100644 --- a/src/app/shared/form/builder/models/form-field-metadata-value.model.ts +++ b/src/app/shared/form/builder/models/form-field-metadata-value.model.ts @@ -11,6 +11,10 @@ export interface OtherInformation { * A class representing a specific input-form field's value */ export class FormFieldMetadataValueObject implements MetadataValueInterface { + + static readonly AUTHORITY_SPLIT: string = '::'; + static readonly AUTHORITY_GENERATE: string = 'will be generated' + FormFieldMetadataValueObject.AUTHORITY_SPLIT; + metadata?: string; value: any; display: string; @@ -58,6 +62,13 @@ export class FormFieldMetadataValueObject implements MetadataValueInterface { return isNotEmpty(this.authority); } + /** + * Returns true if this object has an authority value that needs to be generated + */ + hasAuthorityToGenerate(): boolean { + return isNotEmpty(this.authority) && this.authority.startsWith(FormFieldMetadataValueObject.AUTHORITY_GENERATE); + } + /** * Returns true if this this object has a value */ diff --git a/src/app/shared/form/builder/models/form-field.model.ts b/src/app/shared/form/builder/models/form-field.model.ts index be3150bae3..cbaf8193df 100644 --- a/src/app/shared/form/builder/models/form-field.model.ts +++ b/src/app/shared/form/builder/models/form-field.model.ts @@ -1,3 +1,4 @@ +import { SectionVisibility } from './../../../../submission/objects/section-visibility.model'; import { autoserialize } from 'cerialize'; import { LanguageCode } from './form-field-language-value.model'; @@ -124,4 +125,7 @@ export class FormFieldModel { */ @autoserialize value: any; + + @autoserialize + visibility: SectionVisibility; } diff --git a/src/app/shared/form/builder/parsers/concat-field-parser.ts b/src/app/shared/form/builder/parsers/concat-field-parser.ts index a2076484f4..e86de70c81 100644 --- a/src/app/shared/form/builder/parsers/concat-field-parser.ts +++ b/src/app/shared/form/builder/parsers/concat-field-parser.ts @@ -83,6 +83,8 @@ export class ConcatFieldParser extends FieldParser { input1ModelConfig.required = true; } + concatGroup.disabled = input1ModelConfig.readOnly; + if (isNotEmpty(this.firstPlaceholder)) { input1ModelConfig.placeholder = this.firstPlaceholder; } diff --git a/src/app/shared/form/builder/parsers/field-parser.ts b/src/app/shared/form/builder/parsers/field-parser.ts index c64de0e3ff..7ea55d4454 100644 --- a/src/app/shared/form/builder/parsers/field-parser.ts +++ b/src/app/shared/form/builder/parsers/field-parser.ts @@ -1,3 +1,5 @@ +import { SectionVisibility } from './../../../../submission/objects/section-visibility.model'; +import { VisibilityType } from './../../../../submission/sections/visibility-type'; import { Inject, InjectionToken } from '@angular/core'; import uniqueId from 'lodash/uniqueId'; @@ -22,6 +24,7 @@ import { RelationshipOptions } from '../models/relationship-options.model'; import { VocabularyOptions } from '../../../../core/submission/vocabularies/models/vocabulary-options.model'; import { ParserType } from './parser-type'; import { isNgbDateStruct } from '../../../date.util'; +import { SubmissionScopeType } from '../../../../core/submission/submission-scope-type'; export const SUBMISSION_ID: InjectionToken = new InjectionToken('submissionId'); export const CONFIG_DATA: InjectionToken = new InjectionToken('configData'); @@ -280,8 +283,8 @@ export abstract class FieldParser { controlModel.id = (this.fieldId).replace(/\./g, '_'); // Set read only option - controlModel.readOnly = this.parserOptions.readOnly; - controlModel.disabled = this.parserOptions.readOnly; + controlModel.readOnly = this.parserOptions.readOnly || this.isFieldReadOnly(this.configData.visibility, this.configData.scope, this.parserOptions.submissionScope); + controlModel.disabled = controlModel.readOnly; if (hasValue(this.configData.selectableRelationship)) { controlModel.relationship = Object.assign(new RelationshipOptions(), this.configData.selectableRelationship); } @@ -319,6 +322,28 @@ export abstract class FieldParser { return controlModel; } + /** + * Checks if a field is read-only with the given scope. + * The field is readonly when submissionScope is WORKSPACE and the main visibility is READONLY + * or when submissionScope is WORKFLOW and the other visibility is READONLY + * @param visibility + * @param submissionScope + */ + private isFieldReadOnly(visibility: SectionVisibility, fieldScope: string, submissionScope: string) { + return isNotEmpty(submissionScope) + && isNotEmpty(fieldScope) + && isNotEmpty(visibility) + && (( + submissionScope === SubmissionScopeType.WorkspaceItem + && visibility.main === VisibilityType.READONLY + ) + || + (visibility.other === VisibilityType.READONLY + && submissionScope === SubmissionScopeType.WorkflowItem + ) + ); + } + /** * Get the type bind values from the REST data for a specific field * The return value is any[] in the method signature but in reality it's diff --git a/src/app/shared/form/builder/parsers/onebox-field-parser.ts b/src/app/shared/form/builder/parsers/onebox-field-parser.ts index 3dafa4eebd..606c41ea74 100644 --- a/src/app/shared/form/builder/parsers/onebox-field-parser.ts +++ b/src/app/shared/form/builder/parsers/onebox-field-parser.ts @@ -59,19 +59,20 @@ export class OneboxFieldParser extends FieldParser { this.setLabel(inputSelectGroup, label); inputSelectGroup.required = isNotEmpty(this.configData.mandatory); + const inputModelConfig: DsDynamicInputModelConfig = this.initModel(newId + QUALDROP_VALUE_SUFFIX, label, false, false); + inputModelConfig.hint = null; + this.setValues(inputModelConfig, fieldValue); + const selectModelConfig: DynamicSelectModelConfig = this.initModel(newId + QUALDROP_METADATA_SUFFIX, label, false, false); selectModelConfig.hint = null; this.setOptions(selectModelConfig); if (isNotEmpty(fieldValue)) { selectModelConfig.value = fieldValue.metadata; } - inputSelectGroup.group.push(new DynamicSelectModel(selectModelConfig, clsSelect)); - - const inputModelConfig: DsDynamicInputModelConfig = this.initModel(newId + QUALDROP_VALUE_SUFFIX, label, false, false); - inputModelConfig.hint = null; - this.setValues(inputModelConfig, fieldValue); + selectModelConfig.disabled = inputModelConfig.readOnly; inputSelectGroup.readOnly = selectModelConfig.disabled && inputModelConfig.readOnly; + inputSelectGroup.group.push(new DynamicSelectModel(selectModelConfig, clsSelect)); inputSelectGroup.group.push(new DsDynamicInputModel(inputModelConfig, clsInput)); return new DynamicQualdropModel(inputSelectGroup, clsGroup); diff --git a/src/app/shared/form/builder/parsers/row-parser.ts b/src/app/shared/form/builder/parsers/row-parser.ts index 2818e37b25..3f5b4a04c6 100644 --- a/src/app/shared/form/builder/parsers/row-parser.ts +++ b/src/app/shared/form/builder/parsers/row-parser.ts @@ -1,9 +1,11 @@ +import { SubmissionFieldScopeType } from './../../../../core/submission/submission-field-scope-type'; +import { SectionVisibility } from './../../../../submission/objects/section-visibility.model'; import { Injectable, Injector } from '@angular/core'; import { DYNAMIC_FORM_CONTROL_TYPE_ARRAY, DynamicFormGroupModelConfig } from '@ng-dynamic-forms/core'; import uniqueId from 'lodash/uniqueId'; -import { isEmpty } from '../../../empty.util'; +import { isEmpty, isNotEmpty } from '../../../empty.util'; import { DynamicRowGroupModel } from '../ds-dynamic-form-ui/models/ds-dynamic-row-group-model'; import { FormFieldModel } from '../models/form-field.model'; import { CONFIG_DATA, FieldParser, INIT_FORM_VALUES, PARSER_OPTIONS, SUBMISSION_ID } from './field-parser'; @@ -12,6 +14,7 @@ import { ParserOptions } from './parser-options'; import { ParserType } from './parser-type'; import { setLayout } from './parser.utils'; import { DYNAMIC_FORM_CONTROL_TYPE_RELATION_GROUP } from '../ds-dynamic-form-ui/ds-dynamic-form-constants'; +import { SubmissionScopeType } from '../../../../core/submission/submission-scope-type'; export const ROW_ID_PREFIX = 'df-row-group-config-'; @@ -118,15 +121,37 @@ export class RowParser { return parsedResult; } - checksFieldScope(fieldScope, submissionScope) { - return (isEmpty(fieldScope) || isEmpty(submissionScope) || fieldScope === submissionScope); + checksFieldScope(fieldScope, submissionScope, visibility: SectionVisibility) { + return (isEmpty(fieldScope) || !this.isHidden(visibility, fieldScope, submissionScope)); + } + + /** + * Check if the field is hidden or not. + * It is hidden when we do have the scope, + * but we do not have the visibility, + * also the field scope should be different from the submissionScope. + * @param visibility The visibility of the field + * @param scope the scope of the field + * @param submissionScope the scope of the submission + * @returns If the field is hidden or not + */ + private isHidden(visibility: SectionVisibility, scope: string, submissionScope: string): boolean { + return isNotEmpty(scope) + && ( + isEmpty(visibility) + && ( + submissionScope === SubmissionScopeType.WorkspaceItem && scope !== SubmissionFieldScopeType.WorkspaceItem + || + submissionScope === SubmissionScopeType.WorkflowItem && scope !== SubmissionFieldScopeType.WorkflowItem + ) + ); } filterScopedFields(fields: FormFieldModel[], submissionScope): FormFieldModel[] { const filteredFields: FormFieldModel[] = []; fields.forEach((field: FormFieldModel) => { // Whether field scope doesn't match the submission scope, skip it - if (this.checksFieldScope(field.scope, submissionScope)) { + if (this.checksFieldScope(field.scope, submissionScope, field.visibility)) { filteredFields.push(field); } }); diff --git a/src/app/shared/form/form.component.html b/src/app/shared/form/form.component.html index 0410cfb5dd..1b27c9d308 100644 --- a/src/app/shared/form/form.component.html +++ b/src/app/shared/form/form.component.html @@ -13,22 +13,20 @@ (ngbEvent)="onCustomEvent($event)"> -
    -
    +
    diff --git a/src/app/shared/form/form.component.ts b/src/app/shared/form/form.component.ts index 086b5e1fd8..79cf8ad2c7 100644 --- a/src/app/shared/form/form.component.ts +++ b/src/app/shared/form/form.component.ts @@ -1,6 +1,6 @@ import { distinctUntilChanged, filter, map } from 'rxjs/operators'; import { ChangeDetectorRef, Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'; -import { AbstractControl, FormArray, FormControl, FormGroup } from '@angular/forms'; +import { AbstractControl, UntypedFormArray, UntypedFormControl, UntypedFormGroup } from '@angular/forms'; import { Observable, Subscription } from 'rxjs'; import { @@ -68,7 +68,7 @@ export class FormComponent implements OnDestroy, OnInit { */ @Input() formModel: DynamicFormControlModel[]; @Input() parentFormModel: DynamicFormGroupModel | DynamicFormGroupModel[]; - @Input() formGroup: FormGroup; + @Input() formGroup: UntypedFormGroup; @Input() formLayout = null as DynamicFormLayout; /* eslint-disable @angular-eslint/no-output-rename */ @@ -122,9 +122,9 @@ export class FormComponent implements OnDestroy, OnInit { })); }*/ - private getFormGroup(): FormGroup { + private getFormGroup(): UntypedFormGroup { if (!!this.parentFormModel) { - return this.formGroup.parent as FormGroup; + return this.formGroup.parent as UntypedFormGroup; } return this.formGroup; @@ -184,7 +184,7 @@ export class FormComponent implements OnDestroy, OnInit { const { fieldIndex } = error; let field: AbstractControl; if (!!this.parentFormModel) { - field = this.formBuilderService.getFormControlById(fieldId, formGroup.parent as FormGroup, formModel, fieldIndex); + field = this.formBuilderService.getFormControlById(fieldId, formGroup.parent as UntypedFormGroup, formModel, fieldIndex); } else { field = this.formBuilderService.getFormControlById(fieldId, formGroup, formModel, fieldIndex); } @@ -207,7 +207,7 @@ export class FormComponent implements OnDestroy, OnInit { const { fieldIndex } = error; let field: AbstractControl; if (!!this.parentFormModel) { - field = this.formBuilderService.getFormControlById(fieldId, formGroup.parent as FormGroup, formModel, fieldIndex); + field = this.formBuilderService.getFormControlById(fieldId, formGroup.parent as UntypedFormGroup, formModel, fieldIndex); } else { field = this.formBuilderService.getFormControlById(fieldId, formGroup, formModel, fieldIndex); } @@ -254,7 +254,7 @@ export class FormComponent implements OnDestroy, OnInit { onBlur(event: DynamicFormControlEvent): void { this.blur.emit(event); - const control: FormControl = event.control; + const control: UntypedFormControl = event.control; const fieldIndex: number = (event.context && event.context.index) ? event.context.index : 0; if (control.valid) { this.formService.removeError(this.formId, event.model.name, fieldIndex); @@ -280,7 +280,7 @@ export class FormComponent implements OnDestroy, OnInit { this.change.emit(event); } - const control: FormControl = event.control; + const control: UntypedFormControl = event.control; const fieldIndex: number = (event.context && event.context.index) ? event.context.index : 0; if (control.valid) { this.formService.removeError(this.formId, event.model.id, fieldIndex); @@ -314,7 +314,7 @@ export class FormComponent implements OnDestroy, OnInit { } removeItem($event, arrayContext: DynamicFormArrayModel, index: number): void { - const formArrayControl = this.formGroup.get(this.formBuilderService.getPath(arrayContext)) as FormArray; + const formArrayControl = this.formGroup.get(this.formBuilderService.getPath(arrayContext)) as UntypedFormArray; const event = this.getEvent($event, arrayContext, index, 'remove'); if (this.formBuilderService.isQualdropGroup(event.model as DynamicFormControlModel)) { // In case of qualdrop value remove event must be dispatched before removing the control from array @@ -329,7 +329,7 @@ export class FormComponent implements OnDestroy, OnInit { } insertItem($event, arrayContext: DynamicFormArrayModel, index: number): void { - const formArrayControl = this.formGroup.get(this.formBuilderService.getPath(arrayContext)) as FormArray; + const formArrayControl = this.formGroup.get(this.formBuilderService.getPath(arrayContext)) as UntypedFormArray; this.formBuilderService.insertFormArrayGroup(index, formArrayControl, arrayContext); this.addArrayItem.emit(this.getEvent($event, arrayContext, index, 'add')); this.formService.changeForm(this.formId, this.formModel); @@ -344,17 +344,17 @@ export class FormComponent implements OnDestroy, OnInit { protected getEvent($event: any, arrayContext: DynamicFormArrayModel, index: number, type: string): DynamicFormControlEvent { const context = arrayContext.groups[index]; const itemGroupModel = context.context; - let group = this.formGroup.get(itemGroupModel.id) as FormGroup; + let group = this.formGroup.get(itemGroupModel.id) as UntypedFormGroup; if (isNull(group)) { for (const key of Object.keys(this.formGroup.controls)) { - group = this.formGroup.controls[key].get(itemGroupModel.id) as FormGroup; + group = this.formGroup.controls[key].get(itemGroupModel.id) as UntypedFormGroup; if (isNotNull(group)) { break; } } } const model = context.group[0] as DynamicFormControlModel; - const control = group.controls[index] as FormControl; + const control = group.controls[index] as UntypedFormControl; return { $event, context, control, group, model, type }; } } diff --git a/src/app/shared/form/form.module.ts b/src/app/shared/form/form.module.ts index de18c53363..792de6f251 100644 --- a/src/app/shared/form/form.module.ts +++ b/src/app/shared/form/form.module.ts @@ -32,7 +32,7 @@ import { NumberPickerComponent } from './number-picker/number-picker.component'; import { AuthorityConfidenceStateDirective } from './directives/authority-confidence-state.directive'; import { SortablejsModule } from 'ngx-sortablejs'; import { VocabularyTreeviewComponent } from './vocabulary-treeview/vocabulary-treeview.component'; -import { VocabularyTreeviewService } from './vocabulary-treeview/vocabulary-treeview.service'; +import { VocabularyTreeviewModalComponent } from './vocabulary-treeview-modal/vocabulary-treeview-modal.component'; import { FormBuilderService } from './builder/form-builder.service'; import { DsDynamicTypeBindRelationService } from './builder/ds-dynamic-form-ui/ds-dynamic-type-bind-relation.service'; import { FormService } from './form.service'; @@ -71,7 +71,8 @@ const COMPONENTS = [ ChipsComponent, NumberPickerComponent, VocabularyTreeviewComponent, - ThemedExternalSourceEntryImportModalComponent + VocabularyTreeviewModalComponent, + ThemedExternalSourceEntryImportModalComponent, ]; const DIRECTIVES = [ @@ -105,7 +106,6 @@ const DIRECTIVES = [ provide: DYNAMIC_FORM_CONTROL_MAP_FN, useValue: dsDynamicFormControlMapFn }, - VocabularyTreeviewService, DynamicFormLayoutService, DynamicFormService, DynamicFormValidationService, diff --git a/src/app/shared/form/form.service.spec.ts b/src/app/shared/form/form.service.spec.ts index e565c8f219..57880ffc14 100644 --- a/src/app/shared/form/form.service.spec.ts +++ b/src/app/shared/form/form.service.spec.ts @@ -1,6 +1,6 @@ import { Store, StoreModule } from '@ngrx/store'; import { inject, TestBed, waitForAsync } from '@angular/core/testing'; -import { AbstractControl, FormControl, FormGroup, Validators } from '@angular/forms'; +import { AbstractControl, UntypedFormControl, UntypedFormGroup, Validators } from '@angular/forms'; import { DynamicFormControlModel, DynamicFormGroupModel, DynamicInputModel } from '@ng-dynamic-forms/core'; @@ -22,7 +22,7 @@ describe('FormService test suite', () => { const formId = 'testForm'; let service: FormService; let builderService: FormBuilderService; - let formGroup: FormGroup; + let formGroup: UntypedFormGroup; const formModel: DynamicFormControlModel[] = [ new DynamicInputModel({ id: 'author', value: 'test' }), @@ -104,18 +104,18 @@ describe('FormService test suite', () => { .subscribe((state) => { state.forms = formState; }); - const author: AbstractControl = new FormControl('test'); - const title: AbstractControl = new FormControl(undefined, Validators.required); - const date: AbstractControl = new FormControl(undefined); - const description: AbstractControl = new FormControl(undefined); + const author: AbstractControl = new UntypedFormControl('test'); + const title: AbstractControl = new UntypedFormControl(undefined, Validators.required); + const date: AbstractControl = new UntypedFormControl(undefined); + const description: AbstractControl = new UntypedFormControl(undefined); - const addressLocation: FormGroup = new FormGroup({ - zipCode: new FormControl(undefined), - state: new FormControl(undefined), - city: new FormControl(undefined), + const addressLocation: UntypedFormGroup = new UntypedFormGroup({ + zipCode: new UntypedFormControl(undefined), + state: new UntypedFormControl(undefined), + city: new UntypedFormControl(undefined), }); - formGroup = new FormGroup({ author, title, date, description, addressLocation }); + formGroup = new UntypedFormGroup({ author, title, date, description, addressLocation }); controls = { author, title, date, description , addressLocation }; service = new FormService(builderService, store); }) diff --git a/src/app/shared/form/form.service.ts b/src/app/shared/form/form.service.ts index 2dbf78f565..bf316daaed 100644 --- a/src/app/shared/form/form.service.ts +++ b/src/app/shared/form/form.service.ts @@ -1,6 +1,6 @@ import { distinctUntilChanged, filter, map } from 'rxjs/operators'; import { Injectable } from '@angular/core'; -import { AbstractControl, FormArray, FormControl, FormGroup } from '@angular/forms'; +import { AbstractControl, UntypedFormArray, UntypedFormControl, UntypedFormGroup } from '@angular/forms'; import { Observable } from 'rxjs'; import { select, Store } from '@ngrx/store'; @@ -96,13 +96,13 @@ export class FormService { /** * Method to validate form's fields */ - public validateAllFormFields(formGroup: FormGroup | FormArray) { + public validateAllFormFields(formGroup: UntypedFormGroup | UntypedFormArray) { Object.keys(formGroup.controls).forEach((field) => { const control = formGroup.get(field); - if (control instanceof FormControl) { + if (control instanceof UntypedFormControl) { control.markAsTouched({ onlySelf: true }); control.markAsDirty({ onlySelf: true }); - } else if (control instanceof FormGroup || control instanceof FormArray) { + } else if (control instanceof UntypedFormGroup || control instanceof UntypedFormArray) { this.validateAllFormFields(control); } }); @@ -112,14 +112,14 @@ export class FormService { * Check if form group has an invalid form control * @param formGroup The form group to check */ - public hasValidationErrors(formGroup: FormGroup | FormArray): boolean { + public hasValidationErrors(formGroup: UntypedFormGroup | UntypedFormArray): boolean { let hasErrors = false; const fields: string[] = Object.keys(formGroup.controls); for (const field of fields) { const control = formGroup.get(field); - if (control instanceof FormControl) { + if (control instanceof UntypedFormControl) { hasErrors = !control.valid && control.touched; - } else if (control instanceof FormGroup || control instanceof FormArray) { + } else if (control instanceof UntypedFormGroup || control instanceof UntypedFormArray) { hasErrors = this.hasValidationErrors(control); } if (hasErrors) { @@ -162,7 +162,7 @@ export class FormService { } // if the field in question is a concat group, pass down the error to its fields - if (field instanceof FormGroup && model instanceof DynamicFormGroupModel && this.formBuilderService.isConcatGroup(model)) { + if (field instanceof UntypedFormGroup && model instanceof DynamicFormGroupModel && this.formBuilderService.isConcatGroup(model)) { model.group.forEach((subModel) => { const subField = field.controls[subModel.id]; @@ -183,7 +183,7 @@ export class FormService { } // if the field in question is a concat group, clear the error from its fields - if (field instanceof FormGroup && model instanceof DynamicFormGroupModel && this.formBuilderService.isConcatGroup(model)) { + if (field instanceof UntypedFormGroup && model instanceof DynamicFormGroupModel && this.formBuilderService.isConcatGroup(model)) { model.group.forEach((subModel) => { const subField = field.controls[subModel.id]; @@ -194,7 +194,7 @@ export class FormService { field.markAsUntouched(); } - public resetForm(formGroup: FormGroup, groupModel: DynamicFormControlModel[], formId: string) { + public resetForm(formGroup: UntypedFormGroup, groupModel: DynamicFormControlModel[], formId: string) { this.formBuilderService.clearAllModelsValue(groupModel); formGroup.reset(); this.store.dispatch(new FormChangeAction(formId, formGroup.value)); diff --git a/src/app/shared/form/number-picker/number-picker.component.ts b/src/app/shared/form/number-picker/number-picker.component.ts index 0df1e050cd..82240c41d1 100644 --- a/src/app/shared/form/number-picker/number-picker.component.ts +++ b/src/app/shared/form/number-picker/number-picker.component.ts @@ -1,5 +1,5 @@ import { ChangeDetectorRef, Component, EventEmitter, Input, OnInit, Output, SimpleChanges, } from '@angular/core'; -import { ControlValueAccessor, FormBuilder, NG_VALUE_ACCESSOR } from '@angular/forms'; +import { ControlValueAccessor, UntypedFormBuilder, NG_VALUE_ACCESSOR } from '@angular/forms'; import { isEmpty } from '../../empty.util'; @Component({ @@ -31,7 +31,7 @@ export class NumberPickerComponent implements OnInit, ControlValueAccessor { startValue: number; - constructor(private fb: FormBuilder, private cd: ChangeDetectorRef) { + constructor(private fb: UntypedFormBuilder, private cd: ChangeDetectorRef) { } ngOnInit() { diff --git a/src/app/shared/form/vocabulary-treeview-modal/vocabulary-treeview-modal.component.html b/src/app/shared/form/vocabulary-treeview-modal/vocabulary-treeview-modal.component.html new file mode 100644 index 0000000000..71eb8e1476 --- /dev/null +++ b/src/app/shared/form/vocabulary-treeview-modal/vocabulary-treeview-modal.component.html @@ -0,0 +1,16 @@ + + diff --git a/src/app/shared/form/vocabulary-treeview-modal/vocabulary-treeview-modal.component.scss b/src/app/shared/form/vocabulary-treeview-modal/vocabulary-treeview-modal.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/form/vocabulary-treeview-modal/vocabulary-treeview-modal.component.spec.ts b/src/app/shared/form/vocabulary-treeview-modal/vocabulary-treeview-modal.component.spec.ts new file mode 100644 index 0000000000..590c69a159 --- /dev/null +++ b/src/app/shared/form/vocabulary-treeview-modal/vocabulary-treeview-modal.component.spec.ts @@ -0,0 +1,33 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; + +import { VocabularyTreeviewModalComponent } from './vocabulary-treeview-modal.component'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { TranslateModule } from '@ngx-translate/core'; + +describe('VocabularyTreeviewModalComponent', () => { + let component: VocabularyTreeviewModalComponent; + let fixture: ComponentFixture; + + const modalStub = jasmine.createSpyObj('modalStub', ['close']); + + beforeEach(async () => { + await TestBed.configureTestingModule({ + imports: [ TranslateModule.forRoot() ], + declarations: [ VocabularyTreeviewModalComponent ], + providers: [ + { provide: NgbActiveModal, useValue: modalStub }, + ], + }) + .compileComponents(); + }); + + beforeEach(() => { + fixture = TestBed.createComponent(VocabularyTreeviewModalComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should create', () => { + expect(component).toBeTruthy(); + }); +}); diff --git a/src/app/shared/form/vocabulary-treeview-modal/vocabulary-treeview-modal.component.ts b/src/app/shared/form/vocabulary-treeview-modal/vocabulary-treeview-modal.component.ts new file mode 100644 index 0000000000..c6b0bf20fe --- /dev/null +++ b/src/app/shared/form/vocabulary-treeview-modal/vocabulary-treeview-modal.component.ts @@ -0,0 +1,51 @@ +import { Component, Input } from '@angular/core'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { VocabularyOptions } from '../../../core/submission/vocabularies/models/vocabulary-options.model'; +import { VocabularyEntryDetail } from '../../../core/submission/vocabularies/models/vocabulary-entry-detail.model'; + +@Component({ + selector: 'ds-vocabulary-treeview-modal', + templateUrl: './vocabulary-treeview-modal.component.html', + styleUrls: ['./vocabulary-treeview-modal.component.scss'] +}) +/** + * Component that contains a modal to display a VocabularyTreeviewComponent + */ +export class VocabularyTreeviewModalComponent { + + /** + * The {@link VocabularyOptions} object + */ + @Input() vocabularyOptions: VocabularyOptions; + + /** + * Representing how many tree level load at initialization + */ + @Input() preloadLevel = 2; + + /** + * The vocabulary entries already selected, if any + */ + @Input() selectedItems: string[] = []; + + /** + * Whether to allow selecting multiple values with checkboxes + */ + @Input() multiSelect = false; + + /** + * Initialize instance variables + * + * @param {NgbActiveModal} activeModal + */ + constructor( + public activeModal: NgbActiveModal, + ) { } + + /** + * Method called on entry select + */ + onSelect(item: VocabularyEntryDetail) { + this.activeModal.close(item); + } +} diff --git a/src/app/shared/form/vocabulary-treeview/vocabulary-treeview-node.model.ts b/src/app/shared/form/vocabulary-treeview/vocabulary-treeview-node.model.ts index c167328cab..4ac1b08425 100644 --- a/src/app/shared/form/vocabulary-treeview/vocabulary-treeview-node.model.ts +++ b/src/app/shared/form/vocabulary-treeview/vocabulary-treeview-node.model.ts @@ -21,7 +21,8 @@ export class TreeviewNode { public pageInfo: PageInfo = new PageInfo(), public loadMoreParentItem: VocabularyEntryDetail | null = null, public isSearchNode = false, - public isInInitValueHierarchy = false) { + public isInInitValueHierarchy = false, + public isSelected = false) { } updatePageInfo(pageInfo: PageInfo) { @@ -38,7 +39,8 @@ export class TreeviewFlatNode { public pageInfo: PageInfo = new PageInfo(), public loadMoreParentItem: VocabularyEntryDetail | null = null, public isSearchNode = false, - public isInInitValueHierarchy = false) { + public isInInitValueHierarchy = false, + public isSelected = false) { } } diff --git a/src/app/shared/form/vocabulary-treeview/vocabulary-treeview.component.html b/src/app/shared/form/vocabulary-treeview/vocabulary-treeview.component.html index 39c62d6e53..fb7d162008 100644 --- a/src/app/shared/form/vocabulary-treeview/vocabulary-treeview.component.html +++ b/src/app/shared/form/vocabulary-treeview/vocabulary-treeview.component.html @@ -1,77 +1,98 @@ - -