mirror of
https://github.com/DSpace/dspace-angular.git
synced 2025-10-07 10:04:11 +00:00
Merge remote-tracking branch 'upstream/main' into w2p-85451_export-search-results-as-csv
This commit is contained in:
9
.github/workflows/docker.yml
vendored
9
.github/workflows/docker.yml
vendored
@@ -31,6 +31,10 @@ jobs:
|
||||
# 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
|
||||
@@ -41,6 +45,10 @@ jobs:
|
||||
- name: Setup Docker Buildx
|
||||
uses: docker/setup-buildx-action@v1
|
||||
|
||||
# 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
|
||||
@@ -70,6 +78,7 @@ jobs:
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
platforms: ${{ env.PLATFORMS }}
|
||||
# For pull requests, we run the Docker build (to ensure no PR changes break the build),
|
||||
# but we ONLY do an image push to DockerHub if it's NOT a PR
|
||||
push: ${{ github.event_name != 'pull_request' }}
|
||||
|
@@ -25,7 +25,7 @@ services:
|
||||
### OVERRIDE default 'entrypoint' in 'docker-compose-rest.yml' ####
|
||||
# Ensure that the database is ready BEFORE starting tomcat
|
||||
# 1. While a TCP connection to dspacedb port 5432 is not available, continue to sleep
|
||||
# 2. Then, run database migration to init database tables
|
||||
# 2. Then, run database migration to init database tables (including any out-of-order ignored migrations, if any)
|
||||
# 3. (Custom for Entities) enable Entity-specific collection submission mappings in item-submission.xml
|
||||
# This 'sed' command inserts the sample configurations specific to the Entities data set, see:
|
||||
# https://github.com/DSpace/DSpace/blob/main/dspace/config/item-submission.xml#L36-L49
|
||||
@@ -35,7 +35,7 @@ services:
|
||||
- '-c'
|
||||
- |
|
||||
while (!</dev/tcp/dspacedb/5432) > /dev/null 2>&1; do sleep 1; done;
|
||||
/dspace/bin/dspace database migrate
|
||||
/dspace/bin/dspace database migrate ignored
|
||||
sed -i '/name-map collection-handle="default".*/a \\n <name-map collection-handle="123456789/3" submission-name="Publication"/> \
|
||||
<name-map collection-handle="123456789/4" submission-name="Publication"/> \
|
||||
<name-map collection-handle="123456789/281" submission-name="Publication"/> \
|
||||
|
@@ -46,14 +46,14 @@ services:
|
||||
- solr_configs:/dspace/solr
|
||||
# Ensure that the database is ready BEFORE starting tomcat
|
||||
# 1. While a TCP connection to dspacedb port 5432 is not available, continue to sleep
|
||||
# 2. Then, run database migration to init database tables
|
||||
# 2. Then, run database migration to init database tables (including any out-of-order ignored migrations, if any)
|
||||
# 3. Finally, start Tomcat
|
||||
entrypoint:
|
||||
- /bin/bash
|
||||
- '-c'
|
||||
- |
|
||||
while (!</dev/tcp/dspacedb/5432) > /dev/null 2>&1; do sleep 1; done;
|
||||
/dspace/bin/dspace database migrate
|
||||
/dspace/bin/dspace database migrate ignored
|
||||
catalina.sh run
|
||||
# DSpace database container
|
||||
# NOTE: This is customized to use our loadsql image, so that we are using a database with existing test data
|
||||
|
12
package.json
12
package.json
@@ -9,10 +9,11 @@
|
||||
"start:dev": "nodemon --exec \"cross-env NODE_ENV=development yarn run serve\"",
|
||||
"start:prod": "yarn run build:prod && cross-env NODE_ENV=production yarn run serve:ssr",
|
||||
"start:mirador:prod": "yarn run build:mirador && yarn run start:prod",
|
||||
"serve": "ng serve -c development",
|
||||
"preserve": "yarn base-href",
|
||||
"serve": "ng serve --configuration development",
|
||||
"serve:ssr": "node dist/server/main",
|
||||
"analyze": "webpack-bundle-analyzer dist/browser/stats.json",
|
||||
"build": "ng build -c development",
|
||||
"build": "ng build --configuration development",
|
||||
"build:stats": "ng build --stats-json",
|
||||
"build:prod": "yarn run build:ssr",
|
||||
"build:ssr": "ng build --configuration production && ng run dspace-angular:server:production",
|
||||
@@ -37,6 +38,7 @@
|
||||
"cypress:open": "cypress open",
|
||||
"cypress:run": "cypress run",
|
||||
"env:yaml": "ts-node --project ./tsconfig.ts-node.json scripts/env-to-yaml.ts",
|
||||
"base-href": "ts-node --project ./tsconfig.ts-node.json scripts/base-href.ts",
|
||||
"check-circ-deps": "npx madge --exclude '(bitstream|bundle|collection|config-submission-form|eperson|item|version)\\.model\\.ts$' --circular --extensions ts ./"
|
||||
},
|
||||
"browser": {
|
||||
@@ -78,6 +80,7 @@
|
||||
"@nicky-lenaers/ngx-scroll-to": "^9.0.0",
|
||||
"angular-idle-preload": "3.0.0",
|
||||
"angulartics2": "^12.0.0",
|
||||
"axios": "^0.27.2",
|
||||
"bootstrap": "4.3.1",
|
||||
"caniuse-lite": "^1.0.30001165",
|
||||
"cerialize": "0.1.18",
|
||||
@@ -104,7 +107,7 @@
|
||||
"mirador": "^3.3.0",
|
||||
"mirador-dl-plugin": "^0.13.0",
|
||||
"mirador-share-plugin": "^0.11.0",
|
||||
"moment": "^2.29.1",
|
||||
"moment": "^2.29.2",
|
||||
"morgan": "^1.10.0",
|
||||
"ng-mocks": "^13.1.1",
|
||||
"ng2-file-upload": "1.4.0",
|
||||
@@ -125,7 +128,8 @@
|
||||
"url-parse": "^1.5.6",
|
||||
"uuid": "^8.3.2",
|
||||
"webfontloader": "1.6.28",
|
||||
"zone.js": "~0.11.5"
|
||||
"zone.js": "~0.11.5",
|
||||
"ngx-ui-switch": "^11.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular-builders/custom-webpack": "~13.1.0",
|
||||
|
36
scripts/base-href.ts
Normal file
36
scripts/base-href.ts
Normal file
@@ -0,0 +1,36 @@
|
||||
import * as fs from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
import { AppConfig } from '../src/config/app-config.interface';
|
||||
import { buildAppConfig } from '../src/config/config.server';
|
||||
|
||||
/**
|
||||
* Script to set baseHref as `ui.nameSpace` for development mode. Adds `baseHref` to angular.json build options.
|
||||
*
|
||||
* Usage (see package.json):
|
||||
*
|
||||
* yarn base-href
|
||||
*/
|
||||
|
||||
const appConfig: AppConfig = buildAppConfig();
|
||||
|
||||
const angularJsonPath = join(process.cwd(), 'angular.json');
|
||||
|
||||
if (!fs.existsSync(angularJsonPath)) {
|
||||
console.error(`Error:\n${angularJsonPath} does not exist\n`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
const angularJson = require(angularJsonPath);
|
||||
|
||||
const baseHref = `${appConfig.ui.nameSpace}${appConfig.ui.nameSpace.endsWith('/') ? '' : '/'}`;
|
||||
|
||||
console.log(`Setting baseHref to ${baseHref} in angular.json`);
|
||||
|
||||
angularJson.projects['dspace-angular'].architect.build.options.baseHref = baseHref;
|
||||
|
||||
fs.writeFileSync(angularJsonPath, JSON.stringify(angularJson, null, 2) + '\n');
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
@@ -1,4 +1,5 @@
|
||||
import { projectRoot} from '../webpack/helpers';
|
||||
import { projectRoot } from '../webpack/helpers';
|
||||
|
||||
const commander = require('commander');
|
||||
const fs = require('fs');
|
||||
const JSON5 = require('json5');
|
||||
@@ -119,7 +120,7 @@ function syncFileWithSource(pathToTargetFile, pathToOutputFile) {
|
||||
outputChunks.forEach(function (chunk) {
|
||||
progressBar.increment();
|
||||
chunk.split("\n").forEach(function (line) {
|
||||
file.write(" " + line + "\n");
|
||||
file.write((line === '' ? '' : ` ${line}`) + "\n");
|
||||
});
|
||||
});
|
||||
file.write("\n}");
|
||||
@@ -192,7 +193,10 @@ function createNewChunkComparingSourceAndTarget(correspondingTargetChunk, source
|
||||
|
||||
const targetList = correspondingTargetChunk.split("\n");
|
||||
const oldKeyValueInTargetComments = getSubStringWithRegex(correspondingTargetChunk, "\\s*\\/\\/\\s*\".*");
|
||||
const keyValueTarget = targetList[targetList.length - 1];
|
||||
let keyValueTarget = targetList[targetList.length - 1];
|
||||
if (!keyValueTarget.endsWith(",")) {
|
||||
keyValueTarget = keyValueTarget + ",";
|
||||
}
|
||||
|
||||
if (oldKeyValueInTargetComments != null) {
|
||||
const oldKeyValueUncommented = getSubStringWithRegex(oldKeyValueInTargetComments[0], "\".*")[0];
|
||||
|
57
server.ts
57
server.ts
@@ -19,6 +19,7 @@ import 'zone.js/node';
|
||||
import 'reflect-metadata';
|
||||
import 'rxjs';
|
||||
|
||||
import axios from 'axios';
|
||||
import * as pem from 'pem';
|
||||
import * as https from 'https';
|
||||
import * as morgan from 'morgan';
|
||||
@@ -38,14 +39,14 @@ import { REQUEST, RESPONSE } from '@nguniversal/express-engine/tokens';
|
||||
|
||||
import { environment } from './src/environments/environment';
|
||||
import { createProxyMiddleware } from 'http-proxy-middleware';
|
||||
import { hasValue, hasNoValue } from './src/app/shared/empty.util';
|
||||
import { hasNoValue, hasValue } from './src/app/shared/empty.util';
|
||||
|
||||
import { UIServerConfig } from './src/config/ui-server-config.interface';
|
||||
|
||||
import { ServerAppModule } from './src/main.server';
|
||||
|
||||
import { buildAppConfig } from './src/config/config.server';
|
||||
import { AppConfig, APP_CONFIG } from './src/config/app-config.interface';
|
||||
import { APP_CONFIG, AppConfig } from './src/config/app-config.interface';
|
||||
import { extendEnvironmentWithAppConfig } from './src/config/config.util';
|
||||
|
||||
/*
|
||||
@@ -67,6 +68,8 @@ extendEnvironmentWithAppConfig(environment, appConfig);
|
||||
// The Express app is exported so that it can be used by serverless Functions.
|
||||
export function app() {
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
/*
|
||||
* Create a new express application
|
||||
*/
|
||||
@@ -138,7 +141,11 @@ export function app() {
|
||||
/**
|
||||
* Proxy the sitemaps
|
||||
*/
|
||||
server.use('/sitemap**', createProxyMiddleware({ target: `${environment.rest.baseUrl}/sitemaps`, changeOrigin: true }));
|
||||
router.use('/sitemap**', createProxyMiddleware({
|
||||
target: `${environment.rest.baseUrl}/sitemaps`,
|
||||
pathRewrite: path => path.replace(environment.ui.nameSpace, '/'),
|
||||
changeOrigin: true
|
||||
}));
|
||||
|
||||
/**
|
||||
* Checks if the rateLimiter property is present
|
||||
@@ -157,7 +164,7 @@ export function app() {
|
||||
* Serve static resources (images, i18n messages, …)
|
||||
* Handle pre-compressed files with [express-static-gzip](https://github.com/tkoenig89/express-static-gzip)
|
||||
*/
|
||||
server.get('*.*', cacheControl, expressStaticGzip(DIST_FOLDER, {
|
||||
router.get('*.*', cacheControl, expressStaticGzip(DIST_FOLDER, {
|
||||
index: false,
|
||||
enableBrotli: true,
|
||||
orderPreference: ['br', 'gzip'],
|
||||
@@ -166,10 +173,17 @@ export function app() {
|
||||
/*
|
||||
* Fallthrough to the IIIF viewer (must be included in the build).
|
||||
*/
|
||||
server.use('/iiif', express.static(IIIF_VIEWER, {index:false}));
|
||||
router.use('/iiif', express.static(IIIF_VIEWER, { index: false }));
|
||||
|
||||
/**
|
||||
* Checking server status
|
||||
*/
|
||||
server.get('/app/health', healthCheck);
|
||||
|
||||
// Register the ngApp callback function to handle incoming requests
|
||||
server.get('*', ngApp);
|
||||
router.get('*', ngApp);
|
||||
|
||||
server.use(environment.ui.nameSpace, router);
|
||||
|
||||
return server;
|
||||
}
|
||||
@@ -203,13 +217,25 @@ function ngApp(req, res) {
|
||||
if (hasValue(err)) {
|
||||
console.warn('Error details : ', err);
|
||||
}
|
||||
res.sendFile(DIST_FOLDER + '/index.html');
|
||||
res.render(indexHtml, {
|
||||
req,
|
||||
providers: [{
|
||||
provide: APP_BASE_HREF,
|
||||
useValue: req.baseUrl
|
||||
}]
|
||||
});
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// If preboot is disabled, just serve the client
|
||||
console.log('Universal off, serving for direct CSR');
|
||||
res.sendFile(DIST_FOLDER + '/index.html');
|
||||
res.render(indexHtml, {
|
||||
req,
|
||||
providers: [{
|
||||
provide: APP_BASE_HREF,
|
||||
useValue: req.baseUrl
|
||||
}]
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -299,6 +325,21 @@ function start() {
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* The callback function to serve health check requests
|
||||
*/
|
||||
function healthCheck(req, res) {
|
||||
const baseUrl = `${environment.rest.baseUrl}${environment.actuators.endpointPath}`;
|
||||
axios.get(baseUrl)
|
||||
.then((response) => {
|
||||
res.status(response.status).send(response.data);
|
||||
})
|
||||
.catch((error) => {
|
||||
res.status(error.response.status).send({
|
||||
error: error.message
|
||||
});
|
||||
});
|
||||
}
|
||||
// Webpack will replace 'require' with '__webpack_require__'
|
||||
// '__non_webpack_require__' is a proxy to Node 'require'
|
||||
// The below code is to ensure that the server is run only when not requiring the bundle.
|
||||
|
@@ -2,8 +2,8 @@ import { CommonModule } from '@angular/common';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
|
||||
import { FormsModule, ReactiveFormsModule, FormArray, FormControl, FormGroup,Validators, NG_VALIDATORS, NG_ASYNC_VALIDATORS } from '@angular/forms';
|
||||
import { BrowserModule } from '@angular/platform-browser';
|
||||
import { FormControl, FormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
|
||||
import { BrowserModule, By } from '@angular/platform-browser';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { Store } from '@ngrx/store';
|
||||
@@ -35,6 +35,7 @@ import { RouterMock } from '../../../shared/mocks/router.mock';
|
||||
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
|
||||
import { Operation } from 'fast-json-patch';
|
||||
import { ValidateGroupExists } from './validators/group-exists.validator';
|
||||
import { NoContent } from '../../../core/shared/NoContent.model';
|
||||
|
||||
describe('GroupFormComponent', () => {
|
||||
let component: GroupFormComponent;
|
||||
@@ -87,6 +88,9 @@ describe('GroupFormComponent', () => {
|
||||
patch(group: Group, operations: Operation[]) {
|
||||
return null;
|
||||
},
|
||||
delete(objectId: string, copyVirtualMetadata?: string[]): Observable<RemoteData<NoContent>> {
|
||||
return createSuccessfulRemoteDataObject$({});
|
||||
},
|
||||
cancelEditGroup(): void {
|
||||
this.activeGroup = null;
|
||||
},
|
||||
@@ -348,4 +352,46 @@ describe('GroupFormComponent', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
let deleteButton;
|
||||
|
||||
beforeEach(() => {
|
||||
component.initialisePage();
|
||||
|
||||
component.canEdit$ = observableOf(true);
|
||||
component.groupBeingEdited = {
|
||||
permanent: false
|
||||
} as Group;
|
||||
|
||||
fixture.detectChanges();
|
||||
deleteButton = fixture.debugElement.query(By.css('.delete-button')).nativeElement;
|
||||
|
||||
spyOn(groupsDataServiceStub, 'delete').and.callThrough();
|
||||
spyOn(groupsDataServiceStub, 'getActiveGroup').and.returnValue(observableOf({ id: 'active-group' }));
|
||||
});
|
||||
|
||||
describe('if confirmed via modal', () => {
|
||||
beforeEach(waitForAsync(() => {
|
||||
deleteButton.click();
|
||||
fixture.detectChanges();
|
||||
(document as any).querySelector('.modal-footer .confirm').click();
|
||||
}));
|
||||
|
||||
it('should call GroupDataService.delete', () => {
|
||||
expect(groupsDataServiceStub.delete).toHaveBeenCalledWith('active-group');
|
||||
});
|
||||
});
|
||||
|
||||
describe('if canceled via modal', () => {
|
||||
beforeEach(waitForAsync(() => {
|
||||
deleteButton.click();
|
||||
fixture.detectChanges();
|
||||
(document as any).querySelector('.modal-footer .cancel').click();
|
||||
}));
|
||||
|
||||
it('should not call GroupDataService.delete', () => {
|
||||
expect(groupsDataServiceStub.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@@ -426,7 +426,7 @@ export class GroupFormComponent implements OnInit, OnDestroy {
|
||||
.subscribe((rd: RemoteData<NoContent>) => {
|
||||
if (rd.hasSucceeded) {
|
||||
this.notificationsService.success(this.translateService.get(this.messagePrefix + '.notification.deleted.success', { name: group.name }));
|
||||
this.reset();
|
||||
this.onCancel();
|
||||
} else {
|
||||
this.notificationsService.error(
|
||||
this.translateService.get(this.messagePrefix + '.notification.deleted.failure.title', { name: group.name }),
|
||||
@@ -439,16 +439,6 @@ export class GroupFormComponent implements OnInit, OnDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* This method will ensure that the page gets reset and that the cache is cleared
|
||||
*/
|
||||
reset() {
|
||||
this.groupDataService.getBrowseEndpoint().pipe(take(1)).subscribe((href: string) => {
|
||||
this.requestService.removeByHrefSubstring(href);
|
||||
});
|
||||
this.onCancel();
|
||||
}
|
||||
|
||||
/**
|
||||
* Cancel the current edit when component is destroyed & unsub all subscriptions
|
||||
*/
|
||||
|
@@ -79,7 +79,7 @@
|
||||
</button>
|
||||
</ng-container>
|
||||
<button *ngIf="!groupDto.group?.permanent && groupDto.ableToDelete"
|
||||
(click)="deleteGroup(groupDto)" class="btn btn-outline-danger btn-sm"
|
||||
(click)="deleteGroup(groupDto)" class="btn btn-outline-danger btn-sm btn-delete"
|
||||
title="{{messagePrefix + 'table.edit.buttons.remove' | translate: {name: groupDto.group.name} }}">
|
||||
<i class="fas fa-trash-alt fa-fw"></i>
|
||||
</button>
|
||||
|
@@ -31,6 +31,7 @@ import { RouterMock } from '../../shared/mocks/router.mock';
|
||||
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';
|
||||
|
||||
describe('GroupRegistryComponent', () => {
|
||||
let component: GroupsRegistryComponent;
|
||||
@@ -145,7 +146,10 @@ describe('GroupRegistryComponent', () => {
|
||||
totalPages: 1,
|
||||
currentPage: 1
|
||||
}), [result]));
|
||||
}
|
||||
},
|
||||
delete(objectId: string, copyVirtualMetadata?: string[]): Observable<RemoteData<NoContent>> {
|
||||
return createSuccessfulRemoteDataObject$({});
|
||||
},
|
||||
};
|
||||
dsoDataServiceStub = {
|
||||
findByHref(href: string): Observable<RemoteData<DSpaceObject>> {
|
||||
@@ -301,4 +305,29 @@ describe('GroupRegistryComponent', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
let deleteButton;
|
||||
|
||||
beforeEach(fakeAsync(() => {
|
||||
spyOn(groupsDataServiceStub, 'delete').and.callThrough();
|
||||
|
||||
setIsAuthorized(true, true);
|
||||
|
||||
// force rerender after setup changes
|
||||
component.search({ query: '' });
|
||||
tick();
|
||||
fixture.detectChanges();
|
||||
|
||||
// only mockGroup[0] is deletable, so we should only get one button
|
||||
deleteButton = fixture.debugElement.query(By.css('.btn-delete')).nativeElement;
|
||||
}));
|
||||
|
||||
it('should call GroupDataService.delete', () => {
|
||||
deleteButton.click();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(groupsDataServiceStub.delete).toHaveBeenCalledWith(mockGroups[0].id);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@@ -9,7 +9,7 @@ import {
|
||||
of as observableOf,
|
||||
Subscription
|
||||
} from 'rxjs';
|
||||
import { catchError, map, switchMap, take, tap } from 'rxjs/operators';
|
||||
import { catchError, map, switchMap, tap } from 'rxjs/operators';
|
||||
import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service';
|
||||
import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service';
|
||||
import { FeatureID } from '../../core/data/feature-authorization/feature-id';
|
||||
@@ -199,7 +199,6 @@ export class GroupsRegistryComponent implements OnInit, OnDestroy {
|
||||
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.reset();
|
||||
} else {
|
||||
this.notificationsService.error(
|
||||
this.translateService.get(this.messagePrefix + 'notification.deleted.failure.title', { name: group.group.name }),
|
||||
@@ -209,17 +208,6 @@ export class GroupsRegistryComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This method will set everything to stale, which will cause the lists on this page to update.
|
||||
*/
|
||||
reset() {
|
||||
this.groupService.getBrowseEndpoint().pipe(
|
||||
take(1)
|
||||
).subscribe((href: string) => {
|
||||
this.requestService.setStaleByHrefSubstring(href);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the members (epersons embedded value of a group)
|
||||
* @param group
|
||||
|
@@ -128,7 +128,6 @@ export class MetadataRegistryComponent {
|
||||
* Delete all the selected metadata schemas
|
||||
*/
|
||||
deleteSchemas() {
|
||||
this.registryService.clearMetadataSchemaRequests().subscribe();
|
||||
this.registryService.getSelectedMetadataSchemas().pipe(take(1)).subscribe(
|
||||
(schemas) => {
|
||||
const tasks$ = [];
|
||||
@@ -148,7 +147,6 @@ export class MetadataRegistryComponent {
|
||||
}
|
||||
this.registryService.deselectAllMetadataSchema();
|
||||
this.registryService.cancelEditMetadataSchema();
|
||||
this.forceUpdateSchemas();
|
||||
});
|
||||
}
|
||||
);
|
||||
|
@@ -174,15 +174,12 @@ export class MetadataSchemaComponent implements OnInit {
|
||||
const failedResponses = responses.filter((response: RemoteData<NoContent>) => response.hasFailed);
|
||||
if (successResponses.length > 0) {
|
||||
this.showNotification(true, successResponses.length);
|
||||
this.registryService.clearMetadataFieldRequests();
|
||||
|
||||
}
|
||||
if (failedResponses.length > 0) {
|
||||
this.showNotification(false, failedResponses.length);
|
||||
}
|
||||
this.registryService.deselectAllMetadataField();
|
||||
this.registryService.cancelEditMetadataField();
|
||||
this.forceUpdateFields();
|
||||
});
|
||||
}
|
||||
);
|
||||
|
@@ -18,8 +18,8 @@ import { ItemAdminSearchResultGridElementComponent } from './item-admin-search-r
|
||||
import { createSuccessfulRemoteDataObject$ } from '../../../../../shared/remote-data.utils';
|
||||
import { getMockThemeService } from '../../../../../shared/mocks/theme-service.mock';
|
||||
import { ThemeService } from '../../../../../shared/theme-support/theme.service';
|
||||
import { AccessStatusDataService } from 'src/app/core/data/access-status-data.service';
|
||||
import { AccessStatusObject } from 'src/app/shared/object-list/access-status-badge/access-status.model';
|
||||
import { AccessStatusDataService } from '../../../../../core/data/access-status-data.service';
|
||||
import { AccessStatusObject } from '../../../../../shared/object-list/access-status-badge/access-status.model';
|
||||
|
||||
describe('ItemAdminSearchResultGridElementComponent', () => {
|
||||
let component: ItemAdminSearchResultGridElementComponent;
|
||||
|
@@ -122,3 +122,5 @@ export const REQUEST_COPY_MODULE_PATH = 'request-a-copy';
|
||||
export function getRequestCopyModulePath() {
|
||||
return `/${REQUEST_COPY_MODULE_PATH}`;
|
||||
}
|
||||
|
||||
export const HEALTH_PAGE_PATH = 'health';
|
||||
|
@@ -3,13 +3,16 @@ import { RouterModule, NoPreloading } from '@angular/router';
|
||||
import { AuthBlockingGuard } from './core/auth/auth-blocking.guard';
|
||||
|
||||
import { AuthenticatedGuard } from './core/auth/authenticated.guard';
|
||||
import { SiteAdministratorGuard } from './core/data/feature-authorization/feature-authorization-guard/site-administrator.guard';
|
||||
import {
|
||||
SiteAdministratorGuard
|
||||
} from './core/data/feature-authorization/feature-authorization-guard/site-administrator.guard';
|
||||
import {
|
||||
ACCESS_CONTROL_MODULE_PATH,
|
||||
ADMIN_MODULE_PATH,
|
||||
BITSTREAM_MODULE_PATH,
|
||||
FORBIDDEN_PATH,
|
||||
FORGOT_PASSWORD_PATH,
|
||||
HEALTH_PAGE_PATH,
|
||||
INFO_MODULE_PATH,
|
||||
INTERNAL_SERVER_ERROR,
|
||||
LEGACY_BITSTREAM_MODULE_PATH,
|
||||
@@ -27,8 +30,12 @@ import { EndUserAgreementCurrentUserGuard } from './core/end-user-agreement/end-
|
||||
import { SiteRegisterGuard } from './core/data/feature-authorization/feature-authorization-guard/site-register.guard';
|
||||
import { ThemedPageNotFoundComponent } from './pagenotfound/themed-pagenotfound.component';
|
||||
import { ThemedForbiddenComponent } from './forbidden/themed-forbidden.component';
|
||||
import { GroupAdministratorGuard } from './core/data/feature-authorization/feature-authorization-guard/group-administrator.guard';
|
||||
import { ThemedPageInternalServerErrorComponent } from './page-internal-server-error/themed-page-internal-server-error.component';
|
||||
import {
|
||||
GroupAdministratorGuard
|
||||
} from './core/data/feature-authorization/feature-authorization-guard/group-administrator.guard';
|
||||
import {
|
||||
ThemedPageInternalServerErrorComponent
|
||||
} from './page-internal-server-error/themed-page-internal-server-error.component';
|
||||
import { ServerCheckGuard } from './core/server-check/server-check.guard';
|
||||
import { MenuResolver } from './menu.resolver';
|
||||
|
||||
@@ -210,6 +217,11 @@ import { MenuResolver } from './menu.resolver';
|
||||
loadChildren: () => import('./statistics-page/statistics-page-routing.module')
|
||||
.then((m) => m.StatisticsPageRoutingModule)
|
||||
},
|
||||
{
|
||||
path: HEALTH_PAGE_PATH,
|
||||
loadChildren: () => import('./health-page/health-page.module')
|
||||
.then((m) => m.HealthPageModule)
|
||||
},
|
||||
{
|
||||
path: ACCESS_CONTROL_MODULE_PATH,
|
||||
loadChildren: () => import('./access-control/access-control.module').then((m) => m.AccessControlModule),
|
||||
|
@@ -187,7 +187,7 @@ describe('App component', () => {
|
||||
link.setAttribute('rel', 'stylesheet');
|
||||
link.setAttribute('type', 'text/css');
|
||||
link.setAttribute('class', 'theme-css');
|
||||
link.setAttribute('href', '/custom-theme.css');
|
||||
link.setAttribute('href', 'custom-theme.css');
|
||||
|
||||
expect(headSpy.appendChild).toHaveBeenCalledWith(link);
|
||||
});
|
||||
|
@@ -12,6 +12,7 @@ import {
|
||||
} from '@angular/core';
|
||||
import {
|
||||
ActivatedRouteSnapshot,
|
||||
ActivationEnd,
|
||||
NavigationCancel,
|
||||
NavigationEnd,
|
||||
NavigationStart, ResolveEnd,
|
||||
@@ -196,15 +197,45 @@ export class AppComponent implements OnInit, AfterViewInit {
|
||||
}
|
||||
|
||||
ngAfterViewInit() {
|
||||
let resolveEndFound = false;
|
||||
let updatingTheme = false;
|
||||
let snapshot: ActivatedRouteSnapshot;
|
||||
|
||||
this.router.events.subscribe((event) => {
|
||||
if (event instanceof NavigationStart) {
|
||||
resolveEndFound = false;
|
||||
updatingTheme = false;
|
||||
this.distinctNext(this.isRouteLoading$, true);
|
||||
} else if (event instanceof ResolveEnd) {
|
||||
resolveEndFound = true;
|
||||
const activatedRouteSnapShot: ActivatedRouteSnapshot = event.state.root;
|
||||
this.themeService.updateThemeOnRouteChange$(event.urlAfterRedirects, activatedRouteSnapShot).pipe(
|
||||
// this is the earliest point where we have all the information we need
|
||||
// to update the theme, but this event is not emitted on first load
|
||||
this.updateTheme(event.urlAfterRedirects, event.state.root);
|
||||
updatingTheme = true;
|
||||
} else if (!updatingTheme && event instanceof ActivationEnd) {
|
||||
// if there was no ResolveEnd, keep track of the snapshot...
|
||||
snapshot = event.snapshot;
|
||||
} else if (event instanceof NavigationEnd) {
|
||||
if (!updatingTheme) {
|
||||
// ...and use it to update the theme on NavigationEnd instead
|
||||
this.updateTheme(event.urlAfterRedirects, snapshot);
|
||||
updatingTheme = true;
|
||||
}
|
||||
this.distinctNext(this.isRouteLoading$, false);
|
||||
} else if (event instanceof NavigationCancel) {
|
||||
if (!updatingTheme) {
|
||||
this.distinctNext(this.isThemeLoading$, false);
|
||||
}
|
||||
this.distinctNext(this.isRouteLoading$, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the theme according to the current route, if applicable.
|
||||
* @param urlAfterRedirects the current URL after redirects
|
||||
* @param snapshot the current route snapshot
|
||||
* @private
|
||||
*/
|
||||
private updateTheme(urlAfterRedirects: string, snapshot: ActivatedRouteSnapshot): void {
|
||||
this.themeService.updateThemeOnRouteChange$(urlAfterRedirects, snapshot).pipe(
|
||||
switchMap((changed) => {
|
||||
if (changed) {
|
||||
return this.isThemeCSSLoading$;
|
||||
@@ -215,16 +246,6 @@ export class AppComponent implements OnInit, AfterViewInit {
|
||||
).subscribe((changed) => {
|
||||
this.distinctNext(this.isThemeLoading$, changed);
|
||||
});
|
||||
} else if (
|
||||
event instanceof NavigationEnd ||
|
||||
event instanceof NavigationCancel
|
||||
) {
|
||||
if (!resolveEndFound) {
|
||||
this.distinctNext(this.isThemeLoading$, false);
|
||||
}
|
||||
this.distinctNext(this.isRouteLoading$, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@HostListener('window:resize', ['$event'])
|
||||
@@ -268,7 +289,7 @@ export class AppComponent implements OnInit, AfterViewInit {
|
||||
link.setAttribute('rel', 'stylesheet');
|
||||
link.setAttribute('type', 'text/css');
|
||||
link.setAttribute('class', 'theme-css');
|
||||
link.setAttribute('href', `/${encodeURIComponent(themeName)}-theme.css`);
|
||||
link.setAttribute('href', `${encodeURIComponent(themeName)}-theme.css`);
|
||||
// wait for the new css to download before removing the old one to prevent a
|
||||
// flash of unstyled content
|
||||
link.onload = () => {
|
||||
|
@@ -1,4 +1,4 @@
|
||||
import { APP_BASE_HREF, CommonModule } from '@angular/common';
|
||||
import { APP_BASE_HREF, CommonModule, DOCUMENT } from '@angular/common';
|
||||
import { HTTP_INTERCEPTORS, HttpClientModule } from '@angular/common/http';
|
||||
import { APP_INITIALIZER, NgModule } from '@angular/core';
|
||||
import { AbstractControl } from '@angular/forms';
|
||||
@@ -42,9 +42,11 @@ export function getConfig() {
|
||||
return environment;
|
||||
}
|
||||
|
||||
export function getBase(appConfig: AppConfig) {
|
||||
return appConfig.ui.nameSpace;
|
||||
}
|
||||
const getBaseHref = (document: Document, appConfig: AppConfig): string => {
|
||||
const baseTag = document.querySelector('head > base');
|
||||
baseTag.setAttribute('href', `${appConfig.ui.nameSpace}${appConfig.ui.nameSpace.endsWith('/') ? '' : '/'}`);
|
||||
return baseTag.getAttribute('href');
|
||||
};
|
||||
|
||||
export function getMetaReducers(appConfig: AppConfig): MetaReducer<AppState>[] {
|
||||
return appConfig.debug ? [...appMetaReducers, ...debugMetaReducers] : appMetaReducers;
|
||||
@@ -84,8 +86,8 @@ const PROVIDERS = [
|
||||
},
|
||||
{
|
||||
provide: APP_BASE_HREF,
|
||||
useFactory: getBase,
|
||||
deps: [APP_CONFIG]
|
||||
useFactory: getBaseHref,
|
||||
deps: [DOCUMENT, APP_CONFIG]
|
||||
},
|
||||
{
|
||||
provide: USER_PROVIDED_META_REDUCERS,
|
||||
|
@@ -5,7 +5,6 @@ import { NotificationsService } from '../../shared/notifications/notifications.s
|
||||
import { CollectionDataService } from '../../core/data/collection-data.service';
|
||||
import { Collection } from '../../core/shared/collection.model';
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
import { RequestService } from '../../core/data/request.service';
|
||||
|
||||
/**
|
||||
* Component that represents the page where a user can delete an existing Collection
|
||||
@@ -24,8 +23,7 @@ export class DeleteCollectionPageComponent extends DeleteComColPageComponent<Col
|
||||
protected route: ActivatedRoute,
|
||||
protected notifications: NotificationsService,
|
||||
protected translate: TranslateService,
|
||||
protected requestService: RequestService
|
||||
) {
|
||||
super(dsoDataService, router, route, notifications, translate, requestService);
|
||||
super(dsoDataService, router, route, notifications, translate);
|
||||
}
|
||||
}
|
||||
|
@@ -12,7 +12,6 @@ import { NotificationsService } from '../../../shared/notifications/notification
|
||||
import { Item } from '../../../core/shared/item.model';
|
||||
import { ItemTemplateDataService } from '../../../core/data/item-template-data.service';
|
||||
import { Collection } from '../../../core/shared/collection.model';
|
||||
import { ObjectCacheService } from '../../../core/cache/object-cache.service';
|
||||
import { RequestService } from '../../../core/data/request.service';
|
||||
import { createSuccessfulRemoteDataObject, createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
|
||||
import { getCollectionItemTemplateRoute } from '../../collection-page-routing-paths';
|
||||
@@ -49,9 +48,6 @@ describe('CollectionMetadataComponent', () => {
|
||||
success: {},
|
||||
error: {}
|
||||
});
|
||||
const objectCache = jasmine.createSpyObj('objectCache', {
|
||||
remove: {}
|
||||
});
|
||||
const requestService = jasmine.createSpyObj('requestService', {
|
||||
setStaleByHrefSubstring: {}
|
||||
});
|
||||
@@ -65,8 +61,7 @@ describe('CollectionMetadataComponent', () => {
|
||||
{ provide: ItemTemplateDataService, useValue: itemTemplateServiceStub },
|
||||
{ provide: ActivatedRoute, useValue: { parent: { data: observableOf({ dso: createSuccessfulRemoteDataObject(collection) }) } } },
|
||||
{ provide: NotificationsService, useValue: notificationsService },
|
||||
{ provide: ObjectCacheService, useValue: objectCache },
|
||||
{ provide: RequestService, useValue: requestService }
|
||||
{ provide: RequestService, useValue: requestService },
|
||||
],
|
||||
schemas: [NO_ERRORS_SCHEMA]
|
||||
}).compileComponents();
|
||||
@@ -95,20 +90,18 @@ describe('CollectionMetadataComponent', () => {
|
||||
});
|
||||
|
||||
describe('deleteItemTemplate', () => {
|
||||
describe('when delete returns a success', () => {
|
||||
beforeEach(() => {
|
||||
(itemTemplateService.deleteByCollectionID as jasmine.Spy).and.returnValue(observableOf(true));
|
||||
comp.deleteItemTemplate();
|
||||
});
|
||||
|
||||
it('should display a success notification', () => {
|
||||
expect(notificationsService.success).toHaveBeenCalled();
|
||||
it('should call ItemTemplateService.deleteByCollectionID', () => {
|
||||
expect(itemTemplateService.deleteByCollectionID).toHaveBeenCalledWith(template, 'collection-id');
|
||||
});
|
||||
|
||||
it('should reset related object and request cache', () => {
|
||||
expect(requestService.setStaleByHrefSubstring).toHaveBeenCalledWith(collectionTemplateHref);
|
||||
expect(requestService.setStaleByHrefSubstring).toHaveBeenCalledWith(template.self);
|
||||
expect(requestService.setStaleByHrefSubstring).toHaveBeenCalledWith(collection.self);
|
||||
describe('when delete returns a success', () => {
|
||||
it('should display a success notification', () => {
|
||||
expect(notificationsService.success).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
|
@@ -8,10 +8,9 @@ import { combineLatest as combineLatestObservable, Observable } from 'rxjs';
|
||||
import { RemoteData } from '../../../core/data/remote-data';
|
||||
import { Item } from '../../../core/shared/item.model';
|
||||
import { getFirstSucceededRemoteDataPayload } from '../../../core/shared/operators';
|
||||
import { switchMap, tap } from 'rxjs/operators';
|
||||
import { switchMap } from 'rxjs/operators';
|
||||
import { NotificationsService } from '../../../shared/notifications/notifications.service';
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
import { ObjectCacheService } from '../../../core/cache/object-cache.service';
|
||||
import { RequestService } from '../../../core/data/request.service';
|
||||
import { getCollectionItemTemplateRoute } from '../../collection-page-routing-paths';
|
||||
|
||||
@@ -38,8 +37,7 @@ export class CollectionMetadataComponent extends ComcolMetadataComponent<Collect
|
||||
protected route: ActivatedRoute,
|
||||
protected notificationsService: NotificationsService,
|
||||
protected translate: TranslateService,
|
||||
protected objectCache: ObjectCacheService,
|
||||
protected requestService: RequestService
|
||||
protected requestService: RequestService,
|
||||
) {
|
||||
super(collectionDataService, router, route, notificationsService, translate);
|
||||
}
|
||||
@@ -93,23 +91,9 @@ export class CollectionMetadataComponent extends ComcolMetadataComponent<Collect
|
||||
getFirstSucceededRemoteDataPayload(),
|
||||
)),
|
||||
);
|
||||
const templateHref$ = collection$.pipe(
|
||||
switchMap((collection) => this.itemTemplateService.getCollectionEndpoint(collection.id)),
|
||||
);
|
||||
|
||||
combineLatestObservable(collection$, template$, templateHref$).pipe(
|
||||
switchMap(([collection, template, templateHref]) => {
|
||||
return this.itemTemplateService.deleteByCollectionID(template, collection.uuid).pipe(
|
||||
tap((success: boolean) => {
|
||||
if (success) {
|
||||
this.objectCache.remove(templateHref);
|
||||
this.objectCache.remove(template.self);
|
||||
this.requestService.setStaleByHrefSubstring(template.self);
|
||||
this.requestService.setStaleByHrefSubstring(templateHref);
|
||||
this.requestService.setStaleByHrefSubstring(collection.self);
|
||||
}
|
||||
})
|
||||
);
|
||||
combineLatestObservable(collection$, template$).pipe(
|
||||
switchMap(([collection, template]) => {
|
||||
return this.itemTemplateService.deleteByCollectionID(template, collection.uuid);
|
||||
})
|
||||
).subscribe((success: boolean) => {
|
||||
if (success) {
|
||||
|
@@ -13,6 +13,8 @@ import { RouterTestingModule } from '@angular/router/testing';
|
||||
import { createSuccessfulRemoteDataObject, createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
|
||||
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
|
||||
import { ComcolModule } from '../../../shared/comcol/comcol.module';
|
||||
import { NotificationsService } from '../../../shared/notifications/notifications.service';
|
||||
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
|
||||
|
||||
describe('CollectionRolesComponent', () => {
|
||||
|
||||
@@ -79,6 +81,7 @@ describe('CollectionRolesComponent', () => {
|
||||
{ provide: ActivatedRoute, useValue: route },
|
||||
{ provide: RequestService, useValue: requestService },
|
||||
{ provide: GroupDataService, useValue: groupDataService },
|
||||
{ provide: NotificationsService, useClass: NotificationsServiceStub }
|
||||
],
|
||||
schemas: [NO_ERRORS_SCHEMA]
|
||||
}).compileComponents();
|
||||
|
@@ -5,7 +5,6 @@ import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { DeleteComColPageComponent } from '../../shared/comcol/comcol-forms/delete-comcol-page/delete-comcol-page.component';
|
||||
import { NotificationsService } from '../../shared/notifications/notifications.service';
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
import { RequestService } from '../../core/data/request.service';
|
||||
|
||||
/**
|
||||
* Component that represents the page where a user can delete an existing Community
|
||||
@@ -24,9 +23,8 @@ export class DeleteCommunityPageComponent extends DeleteComColPageComponent<Comm
|
||||
protected route: ActivatedRoute,
|
||||
protected notifications: NotificationsService,
|
||||
protected translate: TranslateService,
|
||||
protected requestService: RequestService
|
||||
) {
|
||||
super(dsoDataService, router, route, notifications, translate, requestService);
|
||||
super(dsoDataService, router, route, notifications, translate);
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -13,6 +13,8 @@ import { RouterTestingModule } from '@angular/router/testing';
|
||||
import { createSuccessfulRemoteDataObject, createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
|
||||
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
|
||||
import { ComcolModule } from '../../../shared/comcol/comcol.module';
|
||||
import { NotificationsService } from '../../../shared/notifications/notifications.service';
|
||||
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
|
||||
|
||||
describe('CommunityRolesComponent', () => {
|
||||
|
||||
@@ -64,6 +66,7 @@ describe('CommunityRolesComponent', () => {
|
||||
{ provide: ActivatedRoute, useValue: route },
|
||||
{ provide: RequestService, useValue: requestService },
|
||||
{ provide: GroupDataService, useValue: groupDataService },
|
||||
{ provide: NotificationsService, useClass: NotificationsServiceStub }
|
||||
],
|
||||
schemas: [NO_ERRORS_SCHEMA]
|
||||
}).compileComponents();
|
||||
|
@@ -377,25 +377,25 @@ describe('AuthService test', () => {
|
||||
it('should redirect to reload with redirect url', () => {
|
||||
authService.navigateToRedirectUrl('/collection/123');
|
||||
// Reload with redirect URL set to /collection/123
|
||||
expect(hardRedirectService.redirect).toHaveBeenCalledWith(jasmine.stringMatching(new RegExp('/reload/[0-9]*\\?redirect=' + encodeURIComponent('/collection/123'))));
|
||||
expect(hardRedirectService.redirect).toHaveBeenCalledWith(jasmine.stringMatching(new RegExp('reload/[0-9]*\\?redirect=' + encodeURIComponent('/collection/123'))));
|
||||
});
|
||||
|
||||
it('should redirect to reload with /home', () => {
|
||||
authService.navigateToRedirectUrl('/home');
|
||||
// Reload with redirect URL set to /home
|
||||
expect(hardRedirectService.redirect).toHaveBeenCalledWith(jasmine.stringMatching(new RegExp('/reload/[0-9]*\\?redirect=' + encodeURIComponent('/home'))));
|
||||
expect(hardRedirectService.redirect).toHaveBeenCalledWith(jasmine.stringMatching(new RegExp('reload/[0-9]*\\?redirect=' + encodeURIComponent('/home'))));
|
||||
});
|
||||
|
||||
it('should redirect to regular reload and not to /login', () => {
|
||||
authService.navigateToRedirectUrl('/login');
|
||||
// Reload without a redirect URL
|
||||
expect(hardRedirectService.redirect).toHaveBeenCalledWith(jasmine.stringMatching(new RegExp('/reload/[0-9]*(?!\\?)$')));
|
||||
expect(hardRedirectService.redirect).toHaveBeenCalledWith(jasmine.stringMatching(new RegExp('reload/[0-9]*(?!\\?)$')));
|
||||
});
|
||||
|
||||
it('should redirect to regular reload when no redirect url is found', () => {
|
||||
authService.navigateToRedirectUrl(undefined);
|
||||
// Reload without a redirect URL
|
||||
expect(hardRedirectService.redirect).toHaveBeenCalledWith(jasmine.stringMatching(new RegExp('/reload/[0-9]*(?!\\?)$')));
|
||||
expect(hardRedirectService.redirect).toHaveBeenCalledWith(jasmine.stringMatching(new RegExp('reload/[0-9]*(?!\\?)$')));
|
||||
});
|
||||
|
||||
describe('impersonate', () => {
|
||||
|
@@ -468,8 +468,8 @@ export class AuthService {
|
||||
*/
|
||||
public navigateToRedirectUrl(redirectUrl: string) {
|
||||
// Don't do redirect if already on reload url
|
||||
if (!hasValue(redirectUrl) || !redirectUrl.includes('/reload/')) {
|
||||
let url = `/reload/${new Date().getTime()}`;
|
||||
if (!hasValue(redirectUrl) || !redirectUrl.includes('reload/')) {
|
||||
let url = `reload/${new Date().getTime()}`;
|
||||
if (isNotEmpty(redirectUrl) && !redirectUrl.startsWith(LOGIN_ROUTE)) {
|
||||
url += `?redirect=${encodeURIComponent(redirectUrl)}`;
|
||||
}
|
||||
|
@@ -78,6 +78,7 @@ describe(`DSONameService`, () => {
|
||||
});
|
||||
|
||||
describe(`factories.Person`, () => {
|
||||
describe(`with person.familyName and person.givenName`, () => {
|
||||
beforeEach(() => {
|
||||
spyOn(mockPerson, 'firstMetadataValue').and.returnValues(...mockPersonName.split(', '));
|
||||
});
|
||||
@@ -87,6 +88,22 @@ describe(`DSONameService`, () => {
|
||||
expect(result).toBe(mockPersonName);
|
||||
expect(mockPerson.firstMetadataValue).toHaveBeenCalledWith('person.familyName');
|
||||
expect(mockPerson.firstMetadataValue).toHaveBeenCalledWith('person.givenName');
|
||||
expect(mockPerson.firstMetadataValue).not.toHaveBeenCalledWith('dc.title');
|
||||
});
|
||||
});
|
||||
|
||||
describe(`without person.familyName and person.givenName`, () => {
|
||||
beforeEach(() => {
|
||||
spyOn(mockPerson, 'firstMetadataValue').and.returnValues(undefined, undefined, mockPersonName);
|
||||
});
|
||||
|
||||
it(`should return dc.title`, () => {
|
||||
const result = (service as any).factories.Person(mockPerson);
|
||||
expect(result).toBe(mockPersonName);
|
||||
expect(mockPerson.firstMetadataValue).toHaveBeenCalledWith('person.familyName');
|
||||
expect(mockPerson.firstMetadataValue).toHaveBeenCalledWith('person.givenName');
|
||||
expect(mockPerson.firstMetadataValue).toHaveBeenCalledWith('dc.title');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
@@ -1,5 +1,5 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { hasValue } from '../../shared/empty.util';
|
||||
import { hasValue, isEmpty } from '../../shared/empty.util';
|
||||
import { DSpaceObject } from '../shared/dspace-object.model';
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
|
||||
@@ -27,7 +27,13 @@ export class DSONameService {
|
||||
*/
|
||||
private readonly factories = {
|
||||
Person: (dso: DSpaceObject): string => {
|
||||
return `${dso.firstMetadataValue('person.familyName')}, ${dso.firstMetadataValue('person.givenName')}`;
|
||||
const familyName = dso.firstMetadataValue('person.familyName');
|
||||
const givenName = dso.firstMetadataValue('person.givenName');
|
||||
if (isEmpty(familyName) && isEmpty(givenName)) {
|
||||
return dso.firstMetadataValue('dc.title') || dso.name;
|
||||
} else {
|
||||
return `${familyName}, ${givenName}`;
|
||||
}
|
||||
},
|
||||
OrgUnit: (dso: DSpaceObject): string => {
|
||||
return dso.firstMetadataValue('organization.legalName');
|
||||
|
@@ -41,7 +41,7 @@ describe('objectCacheReducer', () => {
|
||||
alternativeLinks: [altLink1, altLink2],
|
||||
timeCompleted: new Date().getTime(),
|
||||
msToLive: 900000,
|
||||
requestUUID: requestUUID1,
|
||||
requestUUIDs: [requestUUID1],
|
||||
patches: [],
|
||||
isDirty: false,
|
||||
},
|
||||
@@ -55,7 +55,7 @@ describe('objectCacheReducer', () => {
|
||||
alternativeLinks: [altLink3, altLink4],
|
||||
timeCompleted: new Date().getTime(),
|
||||
msToLive: 900000,
|
||||
requestUUID: selfLink2,
|
||||
requestUUIDs: [selfLink2],
|
||||
patches: [],
|
||||
isDirty: false
|
||||
}
|
||||
|
10
src/app/core/cache/object-cache.reducer.ts
vendored
10
src/app/core/cache/object-cache.reducer.ts
vendored
@@ -63,9 +63,11 @@ export class ObjectCacheEntry implements CacheEntry {
|
||||
msToLive: number;
|
||||
|
||||
/**
|
||||
* The UUID of the request that caused this entry to be added
|
||||
* The UUIDs of the requests that caused this entry to be added
|
||||
* New UUIDs should be added to the front of the array
|
||||
* to make retrieving the latest UUID easier.
|
||||
*/
|
||||
requestUUID: string;
|
||||
requestUUIDs: string[];
|
||||
|
||||
/**
|
||||
* An array of patches that were made on the client side to this entry, but haven't been sent to the server yet
|
||||
@@ -156,11 +158,11 @@ function addToObjectCache(state: ObjectCacheState, action: AddToObjectCacheActio
|
||||
data: action.payload.objectToCache,
|
||||
timeCompleted: action.payload.timeCompleted,
|
||||
msToLive: action.payload.msToLive,
|
||||
requestUUID: action.payload.requestUUID,
|
||||
requestUUIDs: [action.payload.requestUUID, ...(existing.requestUUIDs || [])],
|
||||
isDirty: isNotEmpty(existing.patches),
|
||||
patches: existing.patches || [],
|
||||
alternativeLinks: [...(existing.alternativeLinks || []), ...newAltLinks]
|
||||
}
|
||||
} as ObjectCacheEntry
|
||||
});
|
||||
}
|
||||
|
||||
|
48
src/app/core/cache/object-cache.service.spec.ts
vendored
48
src/app/core/cache/object-cache.service.spec.ts
vendored
@@ -211,8 +211,8 @@ describe('ObjectCacheService', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('has', () => {
|
||||
|
||||
describe('hasByHref', () => {
|
||||
describe('with requestUUID not specified', () => {
|
||||
describe('getByHref emits an object', () => {
|
||||
beforeEach(() => {
|
||||
spyOn(service, 'getByHref').and.returnValue(observableOf(cacheEntry));
|
||||
@@ -234,6 +234,50 @@ describe('ObjectCacheService', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('with requestUUID specified', () => {
|
||||
describe('getByHref emits an object that includes the specified requestUUID', () => {
|
||||
beforeEach(() => {
|
||||
spyOn(service, 'getByHref').and.returnValue(observableOf(Object.assign(cacheEntry, {
|
||||
requestUUIDs: [
|
||||
'something',
|
||||
'something-else',
|
||||
'specific-request',
|
||||
]
|
||||
})));
|
||||
});
|
||||
|
||||
it('should return true', () => {
|
||||
expect(service.hasByHref(selfLink, 'specific-request')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getByHref emits an object that doesn\'t include the specified requestUUID', () => {
|
||||
beforeEach(() => {
|
||||
spyOn(service, 'getByHref').and.returnValue(observableOf(Object.assign(cacheEntry, {
|
||||
requestUUIDs: [
|
||||
'something',
|
||||
'something-else',
|
||||
]
|
||||
})));
|
||||
});
|
||||
|
||||
it('should return true', () => {
|
||||
expect(service.hasByHref(selfLink, 'specific-request')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getByHref emits nothing', () => {
|
||||
beforeEach(() => {
|
||||
spyOn(service, 'getByHref').and.returnValue(empty());
|
||||
});
|
||||
|
||||
it('should return false', () => {
|
||||
expect(service.hasByHref(selfLink, 'specific-request')).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('getBySelfLink', () => {
|
||||
it('should return the entry returned by the select method', () => {
|
||||
const state = Object.assign({}, initialState, {
|
||||
|
4
src/app/core/cache/object-cache.service.ts
vendored
4
src/app/core/cache/object-cache.service.ts
vendored
@@ -197,7 +197,7 @@ export class ObjectCacheService {
|
||||
*/
|
||||
getRequestUUIDBySelfLink(selfLink: string): Observable<string> {
|
||||
return this.getByHref(selfLink).pipe(
|
||||
map((entry: ObjectCacheEntry) => entry.requestUUID),
|
||||
map((entry: ObjectCacheEntry) => entry.requestUUIDs[0]),
|
||||
distinctUntilChanged());
|
||||
}
|
||||
|
||||
@@ -282,7 +282,7 @@ export class ObjectCacheService {
|
||||
let result = false;
|
||||
this.getByHref(href).subscribe((entry: ObjectCacheEntry) => {
|
||||
if (isNotEmpty(requestUUID)) {
|
||||
result = entry.requestUUID === requestUUID;
|
||||
result = entry.requestUUIDs.includes(requestUUID);
|
||||
} else {
|
||||
result = true;
|
||||
}
|
||||
|
@@ -166,6 +166,9 @@ import { SubmissionAccessesModel } from './config/models/config-submission-acces
|
||||
import { AccessStatusObject } from '../shared/object-list/access-status-badge/access-status.model';
|
||||
import { AccessStatusDataService } from './data/access-status-data.service';
|
||||
import { LinkHeadService } from './services/link-head.service';
|
||||
import { ResearcherProfileService } from './profile/researcher-profile.service';
|
||||
import { ProfileClaimService } from '../profile-page/profile-claim/profile-claim.service';
|
||||
import { ResearcherProfile } from './profile/model/researcher-profile.model';
|
||||
|
||||
/**
|
||||
* When not in production, endpoint responses can be mocked for testing purposes
|
||||
@@ -292,6 +295,8 @@ const PROVIDERS = [
|
||||
SequenceService,
|
||||
GroupDataService,
|
||||
FeedbackDataService,
|
||||
ResearcherProfileService,
|
||||
ProfileClaimService
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -352,7 +357,8 @@ export const models =
|
||||
Root,
|
||||
SearchConfig,
|
||||
SubmissionAccessesModel,
|
||||
AccessStatusObject
|
||||
AccessStatusObject,
|
||||
ResearcherProfile
|
||||
];
|
||||
|
||||
@NgModule({
|
||||
|
@@ -37,7 +37,12 @@ describe('BitstreamFormatDataService', () => {
|
||||
}
|
||||
} as Store<CoreState>;
|
||||
|
||||
const objectCache = {} as ObjectCacheService;
|
||||
const requestUUIDs = ['some', 'uuid'];
|
||||
|
||||
const objectCache = jasmine.createSpyObj('objectCache', {
|
||||
getByHref: observableOf({ requestUUIDs })
|
||||
}) as ObjectCacheService;
|
||||
|
||||
const halEndpointService = {
|
||||
getEndpoint(linkPath: string): Observable<string> {
|
||||
return cold('a', { a: bitstreamFormatsEndpoint });
|
||||
@@ -76,6 +81,7 @@ describe('BitstreamFormatDataService', () => {
|
||||
send: {},
|
||||
getByHref: observableOf(responseCacheEntry),
|
||||
getByUUID: cold('a', { a: responseCacheEntry }),
|
||||
setStaleByUUID: observableOf(true),
|
||||
generateRequestId: 'request-id',
|
||||
removeByHrefSubstring: {}
|
||||
});
|
||||
@@ -96,6 +102,7 @@ describe('BitstreamFormatDataService', () => {
|
||||
send: {},
|
||||
getByHref: observableOf(responseCacheEntry),
|
||||
getByUUID: cold('a', { a: responseCacheEntry }),
|
||||
setStaleByUUID: observableOf(true),
|
||||
generateRequestId: 'request-id',
|
||||
removeByHrefSubstring: {}
|
||||
});
|
||||
@@ -118,6 +125,7 @@ describe('BitstreamFormatDataService', () => {
|
||||
send: {},
|
||||
getByHref: observableOf(responseCacheEntry),
|
||||
getByUUID: cold('a', { a: responseCacheEntry }),
|
||||
setStaleByUUID: observableOf(true),
|
||||
generateRequestId: 'request-id',
|
||||
removeByHrefSubstring: {}
|
||||
});
|
||||
@@ -139,6 +147,7 @@ describe('BitstreamFormatDataService', () => {
|
||||
send: {},
|
||||
getByHref: observableOf(responseCacheEntry),
|
||||
getByUUID: cold('a', { a: responseCacheEntry }),
|
||||
setStaleByUUID: observableOf(true),
|
||||
generateRequestId: 'request-id',
|
||||
removeByHrefSubstring: {}
|
||||
});
|
||||
@@ -163,6 +172,7 @@ describe('BitstreamFormatDataService', () => {
|
||||
send: {},
|
||||
getByHref: observableOf(responseCacheEntry),
|
||||
getByUUID: cold('a', { a: responseCacheEntry }),
|
||||
setStaleByUUID: observableOf(true),
|
||||
generateRequestId: 'request-id',
|
||||
removeByHrefSubstring: {}
|
||||
});
|
||||
@@ -186,6 +196,7 @@ describe('BitstreamFormatDataService', () => {
|
||||
send: {},
|
||||
getByHref: observableOf(responseCacheEntry),
|
||||
getByUUID: cold('a', { a: responseCacheEntry }),
|
||||
setStaleByUUID: observableOf(true),
|
||||
generateRequestId: 'request-id',
|
||||
removeByHrefSubstring: {}
|
||||
});
|
||||
@@ -209,6 +220,7 @@ describe('BitstreamFormatDataService', () => {
|
||||
send: {},
|
||||
getByHref: observableOf(responseCacheEntry),
|
||||
getByUUID: cold('a', { a: responseCacheEntry }),
|
||||
setStaleByUUID: observableOf(true),
|
||||
generateRequestId: 'request-id',
|
||||
removeByHrefSubstring: {}
|
||||
});
|
||||
@@ -231,6 +243,7 @@ describe('BitstreamFormatDataService', () => {
|
||||
send: {},
|
||||
getByHref: observableOf(responseCacheEntry),
|
||||
getByUUID: cold('a', { a: responseCacheEntry }),
|
||||
setStaleByUUID: observableOf(true),
|
||||
generateRequestId: 'request-id',
|
||||
removeByHrefSubstring: {}
|
||||
});
|
||||
@@ -253,6 +266,7 @@ describe('BitstreamFormatDataService', () => {
|
||||
send: {},
|
||||
getByHref: observableOf(responseCacheEntry),
|
||||
getByUUID: cold('a', { a: responseCacheEntry }),
|
||||
setStaleByUUID: observableOf(true),
|
||||
generateRequestId: 'request-id',
|
||||
removeByHrefSubstring: {}
|
||||
});
|
||||
@@ -273,6 +287,7 @@ describe('BitstreamFormatDataService', () => {
|
||||
send: {},
|
||||
getByHref: observableOf(responseCacheEntry),
|
||||
getByUUID: hot('a', { a: responseCacheEntry }),
|
||||
setStaleByUUID: observableOf(true),
|
||||
generateRequestId: 'request-id',
|
||||
removeByHrefSubstring: {}
|
||||
});
|
||||
|
@@ -22,6 +22,7 @@ import {
|
||||
import { BitstreamDataService } from './bitstream-data.service';
|
||||
import { CoreState } from '../core-state.model';
|
||||
import { FindListOptions } from './find-list-options.model';
|
||||
import { Bitstream } from '../shared/bitstream.model';
|
||||
|
||||
const LINK_NAME = 'test';
|
||||
|
||||
@@ -244,4 +245,75 @@ describe('ComColDataService', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteLogo', () => {
|
||||
let dso;
|
||||
|
||||
beforeEach(() => {
|
||||
dso = {
|
||||
_links: {
|
||||
logo: {
|
||||
href: 'logo-href'
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
describe('when DSO has no logo', () => {
|
||||
beforeEach(() => {
|
||||
dso.logo = undefined;
|
||||
});
|
||||
|
||||
it('should return a failed RD', (done) => {
|
||||
service.deleteLogo(dso).subscribe(rd => {
|
||||
expect(rd.hasFailed).toBeTrue();
|
||||
expect(bitstreamDataService.deleteByHref).not.toHaveBeenCalled();
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('when DSO has a logo', () => {
|
||||
let logo;
|
||||
|
||||
beforeEach(() => {
|
||||
logo = Object.assign(new Bitstream, {
|
||||
id: 'logo-id',
|
||||
_links: {
|
||||
self: {
|
||||
href: 'logo-href',
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('that can be retrieved', () => {
|
||||
beforeEach(() => {
|
||||
dso.logo = createSuccessfulRemoteDataObject$(logo);
|
||||
});
|
||||
|
||||
it('should call BitstreamDataService.deleteByHref', (done) => {
|
||||
service.deleteLogo(dso).subscribe(rd => {
|
||||
expect(rd.hasSucceeded).toBeTrue();
|
||||
expect(bitstreamDataService.deleteByHref).toHaveBeenCalledWith('logo-href');
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('that cannot be retrieved', () => {
|
||||
beforeEach(() => {
|
||||
dso.logo = createFailedRemoteDataObject$(logo);
|
||||
});
|
||||
|
||||
it('should not call BitstreamDataService.deleteByHref', (done) => {
|
||||
service.deleteLogo(dso).subscribe(rd => {
|
||||
expect(rd.hasFailed).toBeTrue();
|
||||
expect(bitstreamDataService.deleteByHref).not.toHaveBeenCalled();
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@@ -11,7 +11,11 @@ import { ObjectCacheService } from '../cache/object-cache.service';
|
||||
import { DSpaceObject } from '../shared/dspace-object.model';
|
||||
import { HALEndpointService } from '../shared/hal-endpoint.service';
|
||||
import { Item } from '../shared/item.model';
|
||||
import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
|
||||
import {
|
||||
createFailedRemoteDataObject,
|
||||
createSuccessfulRemoteDataObject,
|
||||
createSuccessfulRemoteDataObject$,
|
||||
} from '../../shared/remote-data.utils';
|
||||
import { ChangeAnalyzer } from './change-analyzer';
|
||||
import { DataService } from './data.service';
|
||||
import { PatchRequest } from './request.models';
|
||||
@@ -25,9 +29,12 @@ import { RemoteData } from './remote-data';
|
||||
import { RequestEntryState } from './request-entry-state.model';
|
||||
import { CoreState } from '../core-state.model';
|
||||
import { FindListOptions } from './find-list-options.model';
|
||||
import { fakeAsync, tick } from '@angular/core/testing';
|
||||
|
||||
const endpoint = 'https://rest.api/core';
|
||||
|
||||
const BOOLEAN = { f: false, t: true };
|
||||
|
||||
class TestService extends DataService<any> {
|
||||
|
||||
constructor(
|
||||
@@ -86,6 +93,9 @@ describe('DataService', () => {
|
||||
},
|
||||
getObjectBySelfLink: () => {
|
||||
/* empty */
|
||||
},
|
||||
getByHref: () => {
|
||||
/* empty */
|
||||
}
|
||||
} as any;
|
||||
store = {} as Store<CoreState>;
|
||||
@@ -833,4 +843,149 @@ describe('DataService', () => {
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
describe('invalidateByHref', () => {
|
||||
let getByHrefSpy: jasmine.Spy;
|
||||
|
||||
beforeEach(() => {
|
||||
getByHrefSpy = spyOn(objectCache, 'getByHref').and.returnValue(observableOf({
|
||||
requestUUIDs: ['request1', 'request2', 'request3']
|
||||
}));
|
||||
|
||||
});
|
||||
|
||||
it('should call setStaleByUUID for every request associated with this DSO', (done) => {
|
||||
service.invalidateByHref('some-href').subscribe((ok) => {
|
||||
expect(ok).toBeTrue();
|
||||
expect(getByHrefSpy).toHaveBeenCalledWith('some-href');
|
||||
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request1');
|
||||
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request2');
|
||||
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request3');
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should call setStaleByUUID even if not subscribing to returned Observable', fakeAsync(() => {
|
||||
service.invalidateByHref('some-href');
|
||||
tick();
|
||||
|
||||
expect(getByHrefSpy).toHaveBeenCalledWith('some-href');
|
||||
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request1');
|
||||
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request2');
|
||||
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request3');
|
||||
}));
|
||||
|
||||
it('should return an Observable that only emits true once all requests are stale', () => {
|
||||
testScheduler.run(({ cold, expectObservable }) => {
|
||||
requestService.setStaleByUUID.and.callFake((uuid) => {
|
||||
switch (uuid) { // fake requests becoming stale at different times
|
||||
case 'request1':
|
||||
return cold('--(t|)', BOOLEAN);
|
||||
case 'request2':
|
||||
return cold('----(t|)', BOOLEAN);
|
||||
case 'request3':
|
||||
return cold('------(t|)', BOOLEAN);
|
||||
}
|
||||
});
|
||||
|
||||
const done$ = service.invalidateByHref('some-href');
|
||||
|
||||
// emit true as soon as the final request is stale
|
||||
expectObservable(done$).toBe('------(t|)', BOOLEAN);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
let MOCK_SUCCEEDED_RD;
|
||||
let MOCK_FAILED_RD;
|
||||
|
||||
let invalidateByHrefSpy: jasmine.Spy;
|
||||
let buildFromRequestUUIDSpy: jasmine.Spy;
|
||||
let getIDHrefObsSpy: jasmine.Spy;
|
||||
let deleteByHrefSpy: jasmine.Spy;
|
||||
|
||||
beforeEach(() => {
|
||||
invalidateByHrefSpy = spyOn(service, 'invalidateByHref').and.returnValue(observableOf(true));
|
||||
buildFromRequestUUIDSpy = spyOn(rdbService, 'buildFromRequestUUID').and.callThrough();
|
||||
getIDHrefObsSpy = spyOn(service, 'getIDHrefObs').and.callThrough();
|
||||
deleteByHrefSpy = spyOn(service, 'deleteByHref').and.callThrough();
|
||||
|
||||
MOCK_SUCCEEDED_RD = createSuccessfulRemoteDataObject({});
|
||||
MOCK_FAILED_RD = createFailedRemoteDataObject('something went wrong');
|
||||
});
|
||||
|
||||
it('should retrieve href by ID and call deleteByHref', () => {
|
||||
getIDHrefObsSpy.and.returnValue(observableOf('some-href'));
|
||||
buildFromRequestUUIDSpy.and.returnValue(createSuccessfulRemoteDataObject$({}));
|
||||
|
||||
service.delete('some-id', ['a', 'b', 'c']).subscribe(rd => {
|
||||
expect(getIDHrefObsSpy).toHaveBeenCalledWith('some-id');
|
||||
expect(deleteByHrefSpy).toHaveBeenCalledWith('some-href', ['a', 'b', 'c']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteByHref', () => {
|
||||
it('should call invalidateByHref if the DELETE request succeeds', (done) => {
|
||||
buildFromRequestUUIDSpy.and.returnValue(observableOf(MOCK_SUCCEEDED_RD));
|
||||
|
||||
service.deleteByHref('some-href').subscribe(rd => {
|
||||
expect(rd).toBe(MOCK_SUCCEEDED_RD);
|
||||
expect(invalidateByHrefSpy).toHaveBeenCalled();
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should call invalidateByHref even if not subscribing to returned Observable', fakeAsync(() => {
|
||||
buildFromRequestUUIDSpy.and.returnValue(observableOf(MOCK_SUCCEEDED_RD));
|
||||
|
||||
service.deleteByHref('some-href');
|
||||
tick();
|
||||
|
||||
expect(invalidateByHrefSpy).toHaveBeenCalled();
|
||||
}));
|
||||
|
||||
it('should not call invalidateByHref if the DELETE request fails', (done) => {
|
||||
buildFromRequestUUIDSpy.and.returnValue(observableOf(MOCK_FAILED_RD));
|
||||
|
||||
service.deleteByHref('some-href').subscribe(rd => {
|
||||
expect(rd).toBe(MOCK_FAILED_RD);
|
||||
expect(invalidateByHrefSpy).not.toHaveBeenCalled();
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should wait for invalidateByHref before emitting', () => {
|
||||
testScheduler.run(({ cold, expectObservable }) => {
|
||||
buildFromRequestUUIDSpy.and.returnValue(
|
||||
cold('(r|)', { r: MOCK_SUCCEEDED_RD}) // RD emits right away
|
||||
);
|
||||
invalidateByHrefSpy.and.returnValue(
|
||||
cold('----(t|)', BOOLEAN) // but we pretend that setting requests to stale takes longer
|
||||
);
|
||||
|
||||
const done$ = service.deleteByHref('some-href');
|
||||
expectObservable(done$).toBe(
|
||||
'----(r|)', { r: MOCK_SUCCEEDED_RD} // ...and expect the returned Observable to wait until that's done
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('should wait for the DELETE request to resolve before emitting', () => {
|
||||
testScheduler.run(({ cold, expectObservable }) => {
|
||||
buildFromRequestUUIDSpy.and.returnValue(
|
||||
cold('----(r|)', { r: MOCK_SUCCEEDED_RD}) // the request takes a while
|
||||
);
|
||||
invalidateByHrefSpy.and.returnValue(
|
||||
cold('(t|)', BOOLEAN) // but we pretend that setting to stale happens sooner
|
||||
); // e.g.: maybe already stale before this call?
|
||||
|
||||
const done$ = service.deleteByHref('some-href');
|
||||
expectObservable(done$).toBe(
|
||||
'----(r|)', { r: MOCK_SUCCEEDED_RD} // ...and expect the returned Observable to wait for the request
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@@ -1,18 +1,19 @@
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { Store } from '@ngrx/store';
|
||||
import { Operation } from 'fast-json-patch';
|
||||
import { Observable, of as observableOf } from 'rxjs';
|
||||
import { AsyncSubject, combineLatest, from as observableFrom, Observable, of as observableOf } from 'rxjs';
|
||||
import {
|
||||
distinctUntilChanged,
|
||||
filter,
|
||||
find,
|
||||
map,
|
||||
mergeMap,
|
||||
skipWhile,
|
||||
switchMap,
|
||||
take,
|
||||
takeWhile,
|
||||
switchMap,
|
||||
tap,
|
||||
skipWhile,
|
||||
toArray
|
||||
} from 'rxjs/operators';
|
||||
import { hasValue, isNotEmpty, isNotEmptyOperator } from '../../shared/empty.util';
|
||||
import { NotificationOptions } from '../../shared/notifications/models/notification-options.model';
|
||||
@@ -21,22 +22,17 @@ import { FollowLinkConfig } from '../../shared/utils/follow-link-config.model';
|
||||
import { getClassForType } from '../cache/builders/build-decorators';
|
||||
import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service';
|
||||
import { RequestParam } from '../cache/models/request-param.model';
|
||||
import { ObjectCacheEntry } from '../cache/object-cache.reducer';
|
||||
import { ObjectCacheService } from '../cache/object-cache.service';
|
||||
import { DSpaceSerializer } from '../dspace-rest/dspace.serializer';
|
||||
import { DSpaceObject } from '../shared/dspace-object.model';
|
||||
import { HALEndpointService } from '../shared/hal-endpoint.service';
|
||||
import { getRemoteDataPayload, getFirstSucceededRemoteData, } from '../shared/operators';
|
||||
import { getFirstCompletedRemoteData, getFirstSucceededRemoteData, getRemoteDataPayload } from '../shared/operators';
|
||||
import { URLCombiner } from '../url-combiner/url-combiner';
|
||||
import { ChangeAnalyzer } from './change-analyzer';
|
||||
import { PaginatedList } from './paginated-list.model';
|
||||
import { RemoteData } from './remote-data';
|
||||
import {
|
||||
CreateRequest,
|
||||
GetRequest,
|
||||
PatchRequest,
|
||||
PutRequest,
|
||||
DeleteRequest
|
||||
} from './request.models';
|
||||
import { CreateRequest, DeleteRequest, GetRequest, PatchRequest, PutRequest } from './request.models';
|
||||
import { RequestService } from './request.service';
|
||||
import { RestRequestMethod } from './rest-request-method';
|
||||
import { UpdateDataService } from './update-data.service';
|
||||
@@ -168,7 +164,7 @@ export abstract class DataService<T extends CacheableObject> implements UpdateDa
|
||||
* @return {Observable<string>}
|
||||
* Return an observable that emits created HREF
|
||||
*/
|
||||
protected buildHrefWithParams(href: string, params: RequestParam[], ...linksToFollow: FollowLinkConfig<T>[]): string {
|
||||
buildHrefWithParams(href: string, params: RequestParam[], ...linksToFollow: FollowLinkConfig<T>[]): string {
|
||||
|
||||
let args = [];
|
||||
if (hasValue(params)) {
|
||||
@@ -579,6 +575,38 @@ export abstract class DataService<T extends CacheableObject> implements UpdateDa
|
||||
return result$;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate an existing DSpaceObject by marking all requests it is included in as stale
|
||||
* @param objectId The id of the object to be invalidated
|
||||
* @return An Observable that will emit `true` once all requests are stale
|
||||
*/
|
||||
invalidate(objectId: string): Observable<boolean> {
|
||||
return this.getIDHrefObs(objectId).pipe(
|
||||
switchMap((href: string) => this.invalidateByHref(href))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate an existing DSpaceObject by marking all requests it is included in as stale
|
||||
* @param href The self link of the object to be invalidated
|
||||
* @return An Observable that will emit `true` once all requests are stale
|
||||
*/
|
||||
invalidateByHref(href: string): Observable<boolean> {
|
||||
const done$ = new AsyncSubject<boolean>();
|
||||
|
||||
this.objectCache.getByHref(href).pipe(
|
||||
switchMap((oce: ObjectCacheEntry) => observableFrom(oce.requestUUIDs).pipe(
|
||||
mergeMap((requestUUID: string) => this.requestService.setStaleByUUID(requestUUID)),
|
||||
toArray(),
|
||||
)),
|
||||
).subscribe(() => {
|
||||
done$.next(true);
|
||||
done$.complete();
|
||||
});
|
||||
|
||||
return done$;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete an existing DSpace Object on the server
|
||||
* @param objectId The id of the object to be removed
|
||||
@@ -600,6 +628,7 @@ export abstract class DataService<T extends CacheableObject> implements UpdateDa
|
||||
* metadata should be saved as real metadata
|
||||
* @return A RemoteData observable with an empty payload, but still representing the state of the request: statusCode,
|
||||
* errorMessage, timeCompleted, etc
|
||||
* Only emits once all request related to the DSO has been invalidated.
|
||||
*/
|
||||
deleteByHref(href: string, copyVirtualMetadata?: string[]): Observable<RemoteData<NoContent>> {
|
||||
const requestId = this.requestService.generateRequestId();
|
||||
@@ -618,7 +647,27 @@ export abstract class DataService<T extends CacheableObject> implements UpdateDa
|
||||
}
|
||||
this.requestService.send(request);
|
||||
|
||||
return this.rdbService.buildFromRequestUUID(requestId);
|
||||
const response$ = this.rdbService.buildFromRequestUUID(requestId);
|
||||
|
||||
const invalidated$ = new AsyncSubject<boolean>();
|
||||
response$.pipe(
|
||||
getFirstCompletedRemoteData(),
|
||||
switchMap((rd: RemoteData<NoContent>) => {
|
||||
if (rd.hasSucceeded) {
|
||||
return this.invalidateByHref(href);
|
||||
} else {
|
||||
return [true];
|
||||
}
|
||||
})
|
||||
).subscribe(() => {
|
||||
invalidated$.next(true);
|
||||
invalidated$.complete();
|
||||
});
|
||||
|
||||
return combineLatest([response$, invalidated$]).pipe(
|
||||
filter(([_, invalidated]) => invalidated),
|
||||
map(([response, _]) => response),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@@ -65,9 +65,13 @@ export class AuthorizationDataService extends DataService<Authorization> {
|
||||
* @param ePersonUuid UUID of the {@link EPerson} to search {@link Authorization}s for.
|
||||
* If not provided, the UUID of the currently authenticated {@link EPerson} will be used.
|
||||
* @param featureId ID of the {@link Feature} to check {@link Authorization} for
|
||||
* @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's
|
||||
* no valid cached version. Defaults to true
|
||||
* @param reRequestOnStale Whether or not the request should automatically be re-
|
||||
* requested after the response becomes stale
|
||||
*/
|
||||
isAuthorized(featureId?: FeatureID, objectUrl?: string, ePersonUuid?: string): Observable<boolean> {
|
||||
return this.searchByObject(featureId, objectUrl, ePersonUuid, {}, true, true, followLink('feature')).pipe(
|
||||
isAuthorized(featureId?: FeatureID, objectUrl?: string, ePersonUuid?: string, useCachedVersionIfAvailable = true, reRequestOnStale = true): Observable<boolean> {
|
||||
return this.searchByObject(featureId, objectUrl, ePersonUuid, {}, useCachedVersionIfAvailable, reRequestOnStale, followLink('feature')).pipe(
|
||||
getFirstCompletedRemoteData(),
|
||||
map((authorizationRD) => {
|
||||
if (authorizationRD.statusCode !== 401 && hasValue(authorizationRD.payload) && isNotEmpty(authorizationRD.payload.page)) {
|
||||
|
@@ -28,4 +28,5 @@ export enum FeatureID {
|
||||
CanCreateVersion = 'canCreateVersion',
|
||||
CanViewUsageStatistics = 'canViewUsageStatistics',
|
||||
CanSendFeedback = 'canSendFeedback',
|
||||
CanClaimItem = 'canClaimItem',
|
||||
}
|
||||
|
@@ -8,7 +8,7 @@ import { defaultUUID, getMockUUIDService } from '../../shared/mocks/uuid.service
|
||||
import { ObjectCacheService } from '../cache/object-cache.service';
|
||||
import { coreReducers} from '../core.reducers';
|
||||
import { UUIDService } from '../shared/uuid.service';
|
||||
import { RequestConfigureAction, RequestExecuteAction } from './request.actions';
|
||||
import { RequestConfigureAction, RequestExecuteAction, RequestStaleAction } from './request.actions';
|
||||
import {
|
||||
DeleteRequest,
|
||||
GetRequest,
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
PutRequest
|
||||
} from './request.models';
|
||||
import { RequestService } from './request.service';
|
||||
import { TestBed, waitForAsync } from '@angular/core/testing';
|
||||
import { fakeAsync, TestBed, waitForAsync } from '@angular/core/testing';
|
||||
import { storeModuleConfig } from '../../app.reducer';
|
||||
import { MockStore, provideMockStore } from '@ngrx/store/testing';
|
||||
import { RequestEntryState } from './request-entry-state.model';
|
||||
@@ -426,7 +426,7 @@ describe('RequestService', () => {
|
||||
describe('and it is cached', () => {
|
||||
describe('in the ObjectCache', () => {
|
||||
beforeEach(() => {
|
||||
(objectCache.getByHref as any).and.returnValue(observableOf({ requestUUID: 'some-uuid' }));
|
||||
(objectCache.getByHref as any).and.returnValue(observableOf({ requestUUIDs: ['some-uuid'] }));
|
||||
spyOn(serviceAsAny, 'hasByHref').and.returnValue(false);
|
||||
spyOn(serviceAsAny, 'hasByUUID').and.returnValue(true);
|
||||
});
|
||||
@@ -596,4 +596,33 @@ describe('RequestService', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('setStaleByUUID', () => {
|
||||
let dispatchSpy: jasmine.Spy;
|
||||
let getByUUIDSpy: jasmine.Spy;
|
||||
|
||||
beforeEach(() => {
|
||||
dispatchSpy = spyOn(store, 'dispatch');
|
||||
getByUUIDSpy = spyOn(service, 'getByUUID').and.callThrough();
|
||||
});
|
||||
|
||||
it('should dispatch a RequestStaleAction', () => {
|
||||
service.setStaleByUUID('something');
|
||||
const firstAction = dispatchSpy.calls.argsFor(0)[0];
|
||||
expect(firstAction).toBeInstanceOf(RequestStaleAction);
|
||||
expect(firstAction.payload).toEqual({ uuid: 'something' });
|
||||
});
|
||||
|
||||
it('should return an Observable that emits true as soon as the request is stale', fakeAsync(() => {
|
||||
dispatchSpy.and.callFake(() => { /* empty */ }); // don't actually set as stale
|
||||
getByUUIDSpy.and.returnValue(cold('a-b--c--d-', { // but fake the state in the cache
|
||||
a: { state: RequestEntryState.ResponsePending },
|
||||
b: { state: RequestEntryState.Success },
|
||||
c: { state: RequestEntryState.SuccessStale },
|
||||
d: { state: RequestEntryState.Error },
|
||||
}));
|
||||
|
||||
const done$ = service.setStaleByUUID('something');
|
||||
expect(done$).toBeObservable(cold('-----(t|)', { t: true }));
|
||||
}));
|
||||
});
|
||||
});
|
||||
|
@@ -311,6 +311,21 @@ export class RequestService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark a request as stale
|
||||
* @param uuid the UUID of the request
|
||||
* @return an Observable that will emit true once the Request becomes stale
|
||||
*/
|
||||
setStaleByUUID(uuid: string): Observable<boolean> {
|
||||
this.store.dispatch(new RequestStaleAction(uuid));
|
||||
|
||||
return this.getByUUID(uuid).pipe(
|
||||
map((request: RequestEntry) => isStale(request.state)),
|
||||
filter((stale: boolean) => stale),
|
||||
take(1),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a GET request is in the cache or if it's still pending
|
||||
* @param {GetRequest} request The request to check
|
||||
@@ -339,7 +354,7 @@ export class RequestService {
|
||||
.subscribe((entry: ObjectCacheEntry) => {
|
||||
// if the object cache has a match, check if the request that the object came with is
|
||||
// still valid
|
||||
inObjCache = this.hasByUUID(entry.requestUUID);
|
||||
inObjCache = this.hasByUUID(entry.requestUUIDs[0]);
|
||||
}).unsubscribe();
|
||||
|
||||
// we should send the request if it isn't cached
|
||||
|
@@ -21,7 +21,7 @@ import { EPersonDataService } from './eperson-data.service';
|
||||
import { EPerson } from './models/eperson.model';
|
||||
import { EPersonMock, EPersonMock2 } from '../../shared/testing/eperson.mock';
|
||||
import { HALEndpointServiceStub } from '../../shared/testing/hal-endpoint-service.stub';
|
||||
import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
|
||||
import { createNoContentRemoteDataObject$, createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
|
||||
import { getMockRemoteDataBuildServiceHrefMap } from '../../shared/mocks/remote-data-build.service.mock';
|
||||
import { TranslateLoaderMock } from '../../shared/mocks/translate-loader.mock';
|
||||
import { getMockRequestService } from '../../shared/mocks/request.service.mock';
|
||||
@@ -287,13 +287,12 @@ describe('EPersonDataService', () => {
|
||||
|
||||
describe('deleteEPerson', () => {
|
||||
beforeEach(() => {
|
||||
spyOn(service, 'findById').and.returnValue(createSuccessfulRemoteDataObject$(EPersonMock));
|
||||
spyOn(service, 'delete').and.returnValue(createNoContentRemoteDataObject$());
|
||||
service.deleteEPerson(EPersonMock).subscribe();
|
||||
});
|
||||
|
||||
it('should send DeleteRequest', () => {
|
||||
const expected = new DeleteRequest(requestService.generateRequestId(), epersonsEndpoint + '/' + EPersonMock.uuid);
|
||||
expect(requestService.send).toHaveBeenCalledWith(expected);
|
||||
it('should call DataService.delete with the EPerson\'s UUID', () => {
|
||||
expect(service.delete).toHaveBeenCalledWith(EPersonMock.id);
|
||||
});
|
||||
});
|
||||
|
||||
|
@@ -192,7 +192,7 @@ export class LocaleService {
|
||||
this.routeService.getCurrentUrl().pipe(take(1)).subscribe((currentURL) => {
|
||||
// Hard redirect to the reload page with a unique number behind it
|
||||
// so that all state is definitely lost
|
||||
this._window.nativeWindow.location.href = `/reload/${new Date().getTime()}?redirect=` + encodeURIComponent(currentURL);
|
||||
this._window.nativeWindow.location.href = `reload/${new Date().getTime()}?redirect=` + encodeURIComponent(currentURL);
|
||||
});
|
||||
|
||||
}
|
||||
|
61
src/app/core/profile/model/researcher-profile.model.ts
Normal file
61
src/app/core/profile/model/researcher-profile.model.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { Observable } from 'rxjs';
|
||||
import { autoserialize, deserialize, deserializeAs } from 'cerialize';
|
||||
|
||||
import { link, typedObject } from '../../cache/builders/build-decorators';
|
||||
import { HALLink } from '../../shared/hal-link.model';
|
||||
import { ResourceType } from '../../shared/resource-type';
|
||||
import { excludeFromEquals } from '../../utilities/equals.decorators';
|
||||
import { RESEARCHER_PROFILE } from './researcher-profile.resource-type';
|
||||
import { CacheableObject } from '../../cache/cacheable-object.model';
|
||||
import { RemoteData } from '../../data/remote-data';
|
||||
import { ITEM } from '../../shared/item.resource-type';
|
||||
import { Item } from '../../shared/item.model';
|
||||
|
||||
/**
|
||||
* Class the represents a Researcher Profile.
|
||||
*/
|
||||
@typedObject
|
||||
export class ResearcherProfile extends CacheableObject {
|
||||
|
||||
static type = RESEARCHER_PROFILE;
|
||||
|
||||
/**
|
||||
* The object type
|
||||
*/
|
||||
@excludeFromEquals
|
||||
@autoserialize
|
||||
type: ResourceType;
|
||||
|
||||
/**
|
||||
* The identifier of this Researcher Profile
|
||||
*/
|
||||
@autoserialize
|
||||
id: string;
|
||||
|
||||
@deserializeAs('id')
|
||||
uuid: string;
|
||||
|
||||
/**
|
||||
* The visibility of this Researcher Profile
|
||||
*/
|
||||
@autoserialize
|
||||
visible: boolean;
|
||||
|
||||
/**
|
||||
* The {@link HALLink}s for this Researcher Profile
|
||||
*/
|
||||
@deserialize
|
||||
_links: {
|
||||
self: HALLink,
|
||||
item: HALLink,
|
||||
eperson: HALLink
|
||||
};
|
||||
|
||||
/**
|
||||
* The related person Item
|
||||
* Will be undefined unless the item {@link HALLink} has been resolved.
|
||||
*/
|
||||
@link(ITEM)
|
||||
item?: Observable<RemoteData<Item>>;
|
||||
|
||||
}
|
@@ -0,0 +1,9 @@
|
||||
import { ResourceType } from '../../shared/resource-type';
|
||||
|
||||
/**
|
||||
* The resource type for ResearcherProfile
|
||||
*
|
||||
* Needs to be in a separate file to prevent circular
|
||||
* dependencies in webpack.
|
||||
*/
|
||||
export const RESEARCHER_PROFILE = new ResourceType('profile');
|
296
src/app/core/profile/researcher-profile.service.spec.ts
Normal file
296
src/app/core/profile/researcher-profile.service.spec.ts
Normal file
@@ -0,0 +1,296 @@
|
||||
import { HttpClient, HttpHeaders } from '@angular/common/http';
|
||||
|
||||
import { cold, getTestScheduler, hot } from 'jasmine-marbles';
|
||||
import { of as observableOf } from 'rxjs';
|
||||
import { TestScheduler } from 'rxjs/testing';
|
||||
|
||||
import { NotificationsService } from '../../shared/notifications/notifications.service';
|
||||
import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service';
|
||||
import { ObjectCacheService } from '../cache/object-cache.service';
|
||||
import { HALEndpointService } from '../shared/hal-endpoint.service';
|
||||
import { RequestService } from '../data/request.service';
|
||||
import { PageInfo } from '../shared/page-info.model';
|
||||
import { buildPaginatedList } from '../data/paginated-list.model';
|
||||
import {
|
||||
createNoContentRemoteDataObject$,
|
||||
createSuccessfulRemoteDataObject,
|
||||
createSuccessfulRemoteDataObject$
|
||||
} from '../../shared/remote-data.utils';
|
||||
import { RestResponse } from '../cache/response.models';
|
||||
import { RequestEntry } from '../data/request-entry.model';
|
||||
import { ResearcherProfileService } from './researcher-profile.service';
|
||||
import { RouterMock } from '../../shared/mocks/router.mock';
|
||||
import { ResearcherProfile } from './model/researcher-profile.model';
|
||||
import { Item } from '../shared/item.model';
|
||||
import { ReplaceOperation } from 'fast-json-patch';
|
||||
import { HttpOptions } from '../dspace-rest/dspace-rest.service';
|
||||
import { PostRequest } from '../data/request.models';
|
||||
import { followLink } from '../../shared/utils/follow-link-config.model';
|
||||
|
||||
describe('ResearcherProfileService', () => {
|
||||
let scheduler: TestScheduler;
|
||||
let service: ResearcherProfileService;
|
||||
let serviceAsAny: any;
|
||||
let requestService: RequestService;
|
||||
let rdbService: RemoteDataBuildService;
|
||||
let objectCache: ObjectCacheService;
|
||||
let halService: HALEndpointService;
|
||||
let responseCacheEntry: RequestEntry;
|
||||
|
||||
const researcherProfileId = 'beef9946-rt56-479e-8f11-b90cbe9f7241';
|
||||
const itemId = 'beef9946-rt56-479e-8f11-b90cbe9f7241';
|
||||
const researcherProfileItem: Item = Object.assign(new Item(), {
|
||||
id: itemId,
|
||||
_links: {
|
||||
self: {
|
||||
href: `https://rest.api/rest/api/items/${itemId}`
|
||||
},
|
||||
}
|
||||
});
|
||||
const researcherProfile: ResearcherProfile = Object.assign(new ResearcherProfile(), {
|
||||
id: researcherProfileId,
|
||||
visible: false,
|
||||
type: 'profile',
|
||||
_links: {
|
||||
item: {
|
||||
href: `https://rest.api/rest/api/profiles/${researcherProfileId}/item`
|
||||
},
|
||||
self: {
|
||||
href: `https://rest.api/rest/api/profiles/${researcherProfileId}`
|
||||
},
|
||||
}
|
||||
});
|
||||
|
||||
const researcherProfilePatched: ResearcherProfile = Object.assign(new ResearcherProfile(), {
|
||||
id: researcherProfileId,
|
||||
visible: true,
|
||||
type: 'profile',
|
||||
_links: {
|
||||
item: {
|
||||
href: `https://rest.api/rest/api/profiles/${researcherProfileId}/item`
|
||||
},
|
||||
self: {
|
||||
href: `https://rest.api/rest/api/profiles/${researcherProfileId}`
|
||||
},
|
||||
}
|
||||
});
|
||||
|
||||
const researcherProfileId2 = 'agbf9946-f4ce-479e-8f11-b90cbe9f7241';
|
||||
const anotherResearcherProfile: ResearcherProfile = Object.assign(new ResearcherProfile(), {
|
||||
id: researcherProfileId2,
|
||||
visible: false,
|
||||
type: 'profile',
|
||||
_links: {
|
||||
self: {
|
||||
href: `https://rest.api/rest/api/profiles/${researcherProfileId2}`
|
||||
},
|
||||
}
|
||||
});
|
||||
const endpointURL = `https://rest.api/rest/api/profiles`;
|
||||
const endpointURLWithEmbed = 'https://rest.api/rest/api/profiles?embed=item';
|
||||
const sourceUri = `https://rest.api/rest/api/external-source/profile`;
|
||||
const requestURL = `https://rest.api/rest/api/profiles/${researcherProfileId}`;
|
||||
const requestUUID = '8b3c613a-5a4b-438b-9686-be1d5b4a1c5a';
|
||||
|
||||
const pageInfo = new PageInfo();
|
||||
const array = [researcherProfile, anotherResearcherProfile];
|
||||
const paginatedList = buildPaginatedList(pageInfo, array);
|
||||
const researcherProfileRD = createSuccessfulRemoteDataObject(researcherProfile);
|
||||
const paginatedListRD = createSuccessfulRemoteDataObject(paginatedList);
|
||||
|
||||
beforeEach(() => {
|
||||
scheduler = getTestScheduler();
|
||||
|
||||
halService = jasmine.createSpyObj('halService', {
|
||||
getEndpoint: cold('a', { a: endpointURL })
|
||||
});
|
||||
|
||||
responseCacheEntry = new RequestEntry();
|
||||
responseCacheEntry.request = { href: 'https://rest.api/' } as any;
|
||||
responseCacheEntry.response = new RestResponse(true, 200, 'Success');
|
||||
|
||||
requestService = jasmine.createSpyObj('requestService', {
|
||||
generateRequestId: requestUUID,
|
||||
send: true,
|
||||
removeByHrefSubstring: {},
|
||||
getByHref: observableOf(responseCacheEntry),
|
||||
getByUUID: observableOf(responseCacheEntry),
|
||||
setStaleByHrefSubstring: jasmine.createSpy('setStaleByHrefSubstring')
|
||||
});
|
||||
rdbService = jasmine.createSpyObj('rdbService', {
|
||||
buildSingle: hot('a|', {
|
||||
a: researcherProfileRD
|
||||
}),
|
||||
buildList: hot('a|', {
|
||||
a: paginatedListRD
|
||||
}),
|
||||
buildFromRequestUUID: hot('a|', {
|
||||
a: researcherProfileRD
|
||||
})
|
||||
});
|
||||
objectCache = {} as ObjectCacheService;
|
||||
const notificationsService = {} as NotificationsService;
|
||||
const http = {} as HttpClient;
|
||||
const comparator = {} as any;
|
||||
const routerStub: any = new RouterMock();
|
||||
const itemService = jasmine.createSpyObj('ItemService', {
|
||||
findByHref: jasmine.createSpy('findByHref')
|
||||
});
|
||||
|
||||
service = new ResearcherProfileService(
|
||||
requestService,
|
||||
rdbService,
|
||||
objectCache,
|
||||
halService,
|
||||
notificationsService,
|
||||
http,
|
||||
routerStub,
|
||||
comparator,
|
||||
itemService
|
||||
);
|
||||
serviceAsAny = service;
|
||||
|
||||
spyOn((service as any).dataService, 'create').and.callThrough();
|
||||
spyOn((service as any).dataService, 'delete').and.callThrough();
|
||||
spyOn((service as any).dataService, 'update').and.callThrough();
|
||||
spyOn((service as any).dataService, 'findById').and.callThrough();
|
||||
spyOn((service as any).dataService, 'findByHref').and.callThrough();
|
||||
spyOn((service as any).dataService, 'searchBy').and.callThrough();
|
||||
spyOn((service as any).dataService, 'getLinkPath').and.returnValue(observableOf(endpointURL));
|
||||
|
||||
});
|
||||
|
||||
describe('findById', () => {
|
||||
it('should proxy the call to dataservice.findById with eperson UUID', () => {
|
||||
scheduler.schedule(() => service.findById(researcherProfileId));
|
||||
scheduler.flush();
|
||||
|
||||
expect((service as any).dataService.findById).toHaveBeenCalledWith(researcherProfileId, true, true);
|
||||
});
|
||||
|
||||
it('should return a ResearcherProfile object with the given id', () => {
|
||||
const result = service.findById(researcherProfileId);
|
||||
const expected = cold('a|', {
|
||||
a: researcherProfileRD
|
||||
});
|
||||
expect(result).toBeObservable(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('create', () => {
|
||||
it('should proxy the call to dataservice.create with eperson UUID', () => {
|
||||
scheduler.schedule(() => service.create());
|
||||
scheduler.flush();
|
||||
|
||||
expect((service as any).dataService.create).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should return the RemoteData<ResearcherProfile> created', () => {
|
||||
const result = service.create();
|
||||
const expected = cold('a|', {
|
||||
a: researcherProfileRD
|
||||
});
|
||||
expect(result).toBeObservable(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete', () => {
|
||||
it('should proxy the call to dataservice.delete', () => {
|
||||
scheduler.schedule(() => service.delete(researcherProfile));
|
||||
scheduler.flush();
|
||||
|
||||
expect((service as any).dataService.delete).toHaveBeenCalledWith(researcherProfile.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findRelatedItemId', () => {
|
||||
describe('with a related item', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
(service as any).itemService.findByHref.and.returnValue(createSuccessfulRemoteDataObject$(researcherProfileItem));
|
||||
});
|
||||
|
||||
it('should proxy the call to dataservice.findById with eperson UUID', () => {
|
||||
scheduler.schedule(() => service.findRelatedItemId(researcherProfile));
|
||||
scheduler.flush();
|
||||
|
||||
expect((service as any).itemService.findByHref).toHaveBeenCalledWith(researcherProfile._links.item.href, false);
|
||||
});
|
||||
|
||||
it('should return a ResearcherProfile object with the given id', () => {
|
||||
const result = service.findRelatedItemId(researcherProfile);
|
||||
const expected = cold('(a|)', {
|
||||
a: itemId
|
||||
});
|
||||
expect(result).toBeObservable(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('without a related item', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
(service as any).itemService.findByHref.and.returnValue(createNoContentRemoteDataObject$());
|
||||
});
|
||||
|
||||
it('should proxy the call to dataservice.findById with eperson UUID', () => {
|
||||
scheduler.schedule(() => service.findRelatedItemId(researcherProfile));
|
||||
scheduler.flush();
|
||||
|
||||
expect((service as any).itemService.findByHref).toHaveBeenCalledWith(researcherProfile._links.item.href, false);
|
||||
});
|
||||
|
||||
it('should not return a ResearcherProfile object with the given id', () => {
|
||||
const result = service.findRelatedItemId(researcherProfile);
|
||||
const expected = cold('(a|)', {
|
||||
a: null
|
||||
});
|
||||
expect(result).toBeObservable(expected);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('setVisibility', () => {
|
||||
let patchSpy;
|
||||
beforeEach(() => {
|
||||
spyOn((service as any).dataService, 'patch').and.returnValue(createSuccessfulRemoteDataObject$(researcherProfilePatched));
|
||||
spyOn((service as any), 'findById').and.returnValue(createSuccessfulRemoteDataObject$(researcherProfilePatched));
|
||||
});
|
||||
|
||||
it('should proxy the call to dataservice.patch', () => {
|
||||
const replaceOperation: ReplaceOperation<boolean> = {
|
||||
path: '/visible',
|
||||
op: 'replace',
|
||||
value: true
|
||||
};
|
||||
|
||||
scheduler.schedule(() => service.setVisibility(researcherProfile, true));
|
||||
scheduler.flush();
|
||||
|
||||
expect((service as any).dataService.patch).toHaveBeenCalledWith(researcherProfile, [replaceOperation]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('createFromExternalSource', () => {
|
||||
let patchSpy;
|
||||
beforeEach(() => {
|
||||
spyOn((service as any).dataService, 'patch').and.returnValue(createSuccessfulRemoteDataObject$(researcherProfilePatched));
|
||||
spyOn((service as any), 'findById').and.returnValue(createSuccessfulRemoteDataObject$(researcherProfilePatched));
|
||||
});
|
||||
|
||||
it('should proxy the call to dataservice.patch', () => {
|
||||
const options: HttpOptions = Object.create({});
|
||||
let headers = new HttpHeaders();
|
||||
headers = headers.append('Content-Type', 'text/uri-list');
|
||||
options.headers = headers;
|
||||
const request = new PostRequest(requestUUID, endpointURLWithEmbed, sourceUri, options);
|
||||
|
||||
scheduler.schedule(() => service.createFromExternalSource(sourceUri));
|
||||
scheduler.flush();
|
||||
|
||||
expect((service as any).requestService.send).toHaveBeenCalledWith(request);
|
||||
expect((service as any).rdbService.buildFromRequestUUID).toHaveBeenCalledWith(requestUUID, followLink('item'));
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
});
|
167
src/app/core/profile/researcher-profile.service.ts
Normal file
167
src/app/core/profile/researcher-profile.service.ts
Normal file
@@ -0,0 +1,167 @@
|
||||
/* eslint-disable max-classes-per-file */
|
||||
import { HttpClient, HttpHeaders } from '@angular/common/http';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
|
||||
import { Store } from '@ngrx/store';
|
||||
import { ReplaceOperation } from 'fast-json-patch';
|
||||
import { Observable } from 'rxjs';
|
||||
import { find, map } from 'rxjs/operators';
|
||||
|
||||
import { NotificationsService } from '../../shared/notifications/notifications.service';
|
||||
import { dataService } from '../cache/builders/build-decorators';
|
||||
import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service';
|
||||
import { ObjectCacheService } from '../cache/object-cache.service';
|
||||
import { DataService } from '../data/data.service';
|
||||
import { DefaultChangeAnalyzer } from '../data/default-change-analyzer.service';
|
||||
import { ItemDataService } from '../data/item-data.service';
|
||||
import { RemoteData } from '../data/remote-data';
|
||||
import { RequestService } from '../data/request.service';
|
||||
import { HALEndpointService } from '../shared/hal-endpoint.service';
|
||||
import { NoContent } from '../shared/NoContent.model';
|
||||
import { getAllCompletedRemoteData, getFirstCompletedRemoteData } from '../shared/operators';
|
||||
import { ResearcherProfile } from './model/researcher-profile.model';
|
||||
import { RESEARCHER_PROFILE } from './model/researcher-profile.resource-type';
|
||||
import { HttpOptions } from '../dspace-rest/dspace-rest.service';
|
||||
import { PostRequest } from '../data/request.models';
|
||||
import { hasValue } from '../../shared/empty.util';
|
||||
import { CoreState } from '../core-state.model';
|
||||
import { followLink, FollowLinkConfig } from '../../shared/utils/follow-link-config.model';
|
||||
import { Item } from '../shared/item.model';
|
||||
|
||||
/**
|
||||
* A private DataService implementation to delegate specific methods to.
|
||||
*/
|
||||
class ResearcherProfileServiceImpl extends DataService<ResearcherProfile> {
|
||||
protected linkPath = 'profiles';
|
||||
|
||||
constructor(
|
||||
protected requestService: RequestService,
|
||||
protected rdbService: RemoteDataBuildService,
|
||||
protected store: Store<CoreState>,
|
||||
protected objectCache: ObjectCacheService,
|
||||
protected halService: HALEndpointService,
|
||||
protected notificationsService: NotificationsService,
|
||||
protected http: HttpClient,
|
||||
protected comparator: DefaultChangeAnalyzer<ResearcherProfile>) {
|
||||
super();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* A service that provides methods to make REST requests with researcher profile endpoint.
|
||||
*/
|
||||
@Injectable()
|
||||
@dataService(RESEARCHER_PROFILE)
|
||||
export class ResearcherProfileService {
|
||||
|
||||
dataService: ResearcherProfileServiceImpl;
|
||||
|
||||
responseMsToLive: number = 10 * 1000;
|
||||
|
||||
constructor(
|
||||
protected requestService: RequestService,
|
||||
protected rdbService: RemoteDataBuildService,
|
||||
protected objectCache: ObjectCacheService,
|
||||
protected halService: HALEndpointService,
|
||||
protected notificationsService: NotificationsService,
|
||||
protected http: HttpClient,
|
||||
protected router: Router,
|
||||
protected comparator: DefaultChangeAnalyzer<ResearcherProfile>,
|
||||
protected itemService: ItemDataService) {
|
||||
|
||||
this.dataService = new ResearcherProfileServiceImpl(requestService, rdbService, null, objectCache, halService,
|
||||
notificationsService, http, comparator);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the researcher profile with the given uuid.
|
||||
*
|
||||
* @param uuid the profile uuid
|
||||
* @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's
|
||||
* no valid cached version. Defaults to true
|
||||
* @param reRequestOnStale Whether or not the request should automatically be re-
|
||||
* requested after the response becomes stale
|
||||
* @param linksToFollow List of {@link FollowLinkConfig} that indicate which
|
||||
* {@link HALLink}s should be automatically resolved
|
||||
*/
|
||||
public findById(uuid: string, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<ResearcherProfile>[]): Observable<RemoteData<ResearcherProfile>> {
|
||||
return this.dataService.findById(uuid, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow).pipe(
|
||||
getAllCompletedRemoteData(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new researcher profile for the current user.
|
||||
*/
|
||||
public create(): Observable<RemoteData<ResearcherProfile>> {
|
||||
return this.dataService.create(new ResearcherProfile());
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a researcher profile.
|
||||
*
|
||||
* @param researcherProfile the profile to delete
|
||||
*/
|
||||
public delete(researcherProfile: ResearcherProfile): Observable<boolean> {
|
||||
return this.dataService.delete(researcherProfile.id).pipe(
|
||||
getFirstCompletedRemoteData(),
|
||||
map((response: RemoteData<NoContent>) => response.isSuccess)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the item id related to the given researcher profile.
|
||||
*
|
||||
* @param researcherProfile the profile to find for
|
||||
*/
|
||||
public findRelatedItemId(researcherProfile: ResearcherProfile): Observable<string> {
|
||||
const relatedItem$ = researcherProfile.item ? researcherProfile.item : this.itemService.findByHref(researcherProfile._links.item.href, false);
|
||||
return relatedItem$.pipe(
|
||||
getFirstCompletedRemoteData(),
|
||||
map((itemRD: RemoteData<Item>) => (itemRD.hasSucceeded && itemRD.payload) ? itemRD.payload.id : null)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the visibility of the given researcher profile setting the given value.
|
||||
*
|
||||
* @param researcherProfile the profile to update
|
||||
* @param visible the visibility value to set
|
||||
*/
|
||||
public setVisibility(researcherProfile: ResearcherProfile, visible: boolean): Observable<RemoteData<ResearcherProfile>> {
|
||||
const replaceOperation: ReplaceOperation<boolean> = {
|
||||
path: '/visible',
|
||||
op: 'replace',
|
||||
value: visible
|
||||
};
|
||||
|
||||
return this.dataService.patch(researcherProfile, [replaceOperation]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a researcher profile starting from an external source URI
|
||||
* @param sourceUri URI of source item of researcher profile.
|
||||
*/
|
||||
public createFromExternalSource(sourceUri: string): Observable<RemoteData<ResearcherProfile>> {
|
||||
const options: HttpOptions = Object.create({});
|
||||
let headers = new HttpHeaders();
|
||||
headers = headers.append('Content-Type', 'text/uri-list');
|
||||
options.headers = headers;
|
||||
|
||||
const requestId = this.requestService.generateRequestId();
|
||||
const href$ = this.halService.getEndpoint(this.dataService.getLinkPath());
|
||||
|
||||
href$.pipe(
|
||||
find((href: string) => hasValue(href)),
|
||||
map((href: string) => this.dataService.buildHrefWithParams(href, [], followLink('item')))
|
||||
).subscribe((endpoint: string) => {
|
||||
const request = new PostRequest(requestId, endpoint, sourceUri, options);
|
||||
this.requestService.send(request);
|
||||
});
|
||||
|
||||
return this.rdbService.buildFromRequestUUID(requestId, followLink('item'));
|
||||
}
|
||||
}
|
@@ -386,6 +386,10 @@ describe('RegistryService', () => {
|
||||
result = registryService.deleteMetadataSchema(mockSchemasList[0].id);
|
||||
});
|
||||
|
||||
it('should defer to MetadataSchemaDataService.delete', () => {
|
||||
expect(metadataSchemaService.delete).toHaveBeenCalledWith(`${mockSchemasList[0].id}`);
|
||||
});
|
||||
|
||||
it('should return a successful response', () => {
|
||||
result.subscribe((response: RemoteData<NoContent>) => {
|
||||
expect(response.hasSucceeded).toBe(true);
|
||||
@@ -400,6 +404,10 @@ describe('RegistryService', () => {
|
||||
result = registryService.deleteMetadataField(mockFieldsList[0].id);
|
||||
});
|
||||
|
||||
it('should defer to MetadataFieldDataService.delete', () => {
|
||||
expect(metadataFieldService.delete).toHaveBeenCalledWith(`${mockFieldsList[0].id}`);
|
||||
});
|
||||
|
||||
it('should return a successful response', () => {
|
||||
result.subscribe((response: RemoteData<NoContent>) => {
|
||||
expect(response.hasSucceeded).toBe(true);
|
||||
|
@@ -1,13 +1,17 @@
|
||||
import { ReloadGuard } from './reload.guard';
|
||||
import { Router } from '@angular/router';
|
||||
import { AppConfig } from '../../../config/app-config.interface';
|
||||
import { DefaultAppConfig } from '../../../config/default-app-config';
|
||||
import { ReloadGuard } from './reload.guard';
|
||||
|
||||
describe('ReloadGuard', () => {
|
||||
let guard: ReloadGuard;
|
||||
let router: Router;
|
||||
let appConfig: AppConfig;
|
||||
|
||||
beforeEach(() => {
|
||||
router = jasmine.createSpyObj('router', ['parseUrl', 'createUrlTree']);
|
||||
guard = new ReloadGuard(router);
|
||||
appConfig = new DefaultAppConfig();
|
||||
guard = new ReloadGuard(router, appConfig);
|
||||
});
|
||||
|
||||
describe('canActivate', () => {
|
||||
@@ -27,7 +31,7 @@ describe('ReloadGuard', () => {
|
||||
|
||||
it('should create a UrlTree with the redirect URL', () => {
|
||||
guard.canActivate(route, undefined);
|
||||
expect(router.parseUrl).toHaveBeenCalledWith(redirectUrl);
|
||||
expect(router.parseUrl).toHaveBeenCalledWith(redirectUrl.substring(1));
|
||||
});
|
||||
});
|
||||
|
||||
|
@@ -1,5 +1,6 @@
|
||||
import { Inject, Injectable } from '@angular/core';
|
||||
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot, UrlTree } from '@angular/router';
|
||||
import { Injectable } from '@angular/core';
|
||||
import { AppConfig, APP_CONFIG } from '../../../config/app-config.interface';
|
||||
import { isNotEmpty } from '../../shared/empty.util';
|
||||
|
||||
/**
|
||||
@@ -8,7 +9,10 @@ import { isNotEmpty } from '../../shared/empty.util';
|
||||
*/
|
||||
@Injectable()
|
||||
export class ReloadGuard implements CanActivate {
|
||||
constructor(private router: Router) {
|
||||
constructor(
|
||||
private router: Router,
|
||||
@Inject(APP_CONFIG) private appConfig: AppConfig,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -18,7 +22,10 @@ export class ReloadGuard implements CanActivate {
|
||||
*/
|
||||
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): UrlTree {
|
||||
if (isNotEmpty(route.queryParams.redirect)) {
|
||||
return this.router.parseUrl(route.queryParams.redirect);
|
||||
const url = route.queryParams.redirect.startsWith(this.appConfig.ui.nameSpace)
|
||||
? route.queryParams.redirect.substring(this.appConfig.ui.nameSpace.length)
|
||||
: route.queryParams.redirect;
|
||||
return this.router.parseUrl(url);
|
||||
} else {
|
||||
return this.router.createUrlTree(['home']);
|
||||
}
|
||||
|
@@ -19,6 +19,8 @@ import { createSuccessfulRemoteDataObject } from '../../shared/remote-data.utils
|
||||
import { RestResponse } from '../cache/response.models';
|
||||
import { RequestEntry } from '../data/request-entry.model';
|
||||
import { FindListOptions } from '../data/find-list-options.model';
|
||||
import { EPersonDataService } from '../eperson/eperson-data.service';
|
||||
import { GroupDataService } from '../eperson/group-data.service';
|
||||
|
||||
describe('ResourcePolicyService', () => {
|
||||
let scheduler: TestScheduler;
|
||||
@@ -28,6 +30,8 @@ describe('ResourcePolicyService', () => {
|
||||
let objectCache: ObjectCacheService;
|
||||
let halService: HALEndpointService;
|
||||
let responseCacheEntry: RequestEntry;
|
||||
let ePersonService: EPersonDataService;
|
||||
let groupService: GroupDataService;
|
||||
|
||||
const resourcePolicy: any = {
|
||||
id: '1',
|
||||
@@ -88,6 +92,8 @@ describe('ResourcePolicyService', () => {
|
||||
const resourcePolicyRD = createSuccessfulRemoteDataObject(resourcePolicy);
|
||||
const paginatedListRD = createSuccessfulRemoteDataObject(paginatedList);
|
||||
|
||||
const ePersonEndpoint = 'EPERSON_EP';
|
||||
|
||||
beforeEach(() => {
|
||||
scheduler = getTestScheduler();
|
||||
|
||||
@@ -105,6 +111,7 @@ describe('ResourcePolicyService', () => {
|
||||
removeByHrefSubstring: {},
|
||||
getByHref: observableOf(responseCacheEntry),
|
||||
getByUUID: observableOf(responseCacheEntry),
|
||||
setStaleByHrefSubstring: {},
|
||||
});
|
||||
rdbService = jasmine.createSpyObj('rdbService', {
|
||||
buildSingle: hot('a|', {
|
||||
@@ -117,6 +124,11 @@ describe('ResourcePolicyService', () => {
|
||||
a: resourcePolicyRD
|
||||
})
|
||||
});
|
||||
ePersonService = jasmine.createSpyObj('ePersonService', {
|
||||
getBrowseEndpoint: hot('a', {
|
||||
a: ePersonEndpoint
|
||||
}),
|
||||
});
|
||||
objectCache = {} as ObjectCacheService;
|
||||
const notificationsService = {} as NotificationsService;
|
||||
const http = {} as HttpClient;
|
||||
@@ -129,7 +141,9 @@ describe('ResourcePolicyService', () => {
|
||||
halService,
|
||||
notificationsService,
|
||||
http,
|
||||
comparator
|
||||
comparator,
|
||||
ePersonService,
|
||||
groupService
|
||||
);
|
||||
|
||||
spyOn((service as any).dataService, 'create').and.callThrough();
|
||||
@@ -320,4 +334,17 @@ describe('ResourcePolicyService', () => {
|
||||
expect(result).toBeObservable(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateTarget', () => {
|
||||
it('should create a new PUT request for eperson', () => {
|
||||
const targetType = 'eperson';
|
||||
|
||||
const result = service.updateTarget(resourcePolicyId, requestURL, epersonUUID, targetType);
|
||||
const expected = cold('a|', {
|
||||
a: resourcePolicyRD
|
||||
});
|
||||
expect(result).toBeObservable(expected);
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
@@ -1,6 +1,6 @@
|
||||
/* eslint-disable max-classes-per-file */
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
import { HttpClient, HttpHeaders } from '@angular/common/http';
|
||||
|
||||
import { Store } from '@ngrx/store';
|
||||
import { Observable } from 'rxjs';
|
||||
@@ -23,11 +23,19 @@ import { PaginatedList } from '../data/paginated-list.model';
|
||||
import { ActionType } from './models/action-type.model';
|
||||
import { RequestParam } from '../cache/models/request-param.model';
|
||||
import { isNotEmpty } from '../../shared/empty.util';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { map, take } from 'rxjs/operators';
|
||||
import { NoContent } from '../shared/NoContent.model';
|
||||
import { getFirstCompletedRemoteData } from '../shared/operators';
|
||||
import { CoreState } from '../core-state.model';
|
||||
import { FindListOptions } from '../data/find-list-options.model';
|
||||
import { HttpOptions } from '../dspace-rest/dspace-rest.service';
|
||||
import { PutRequest } from '../data/request.models';
|
||||
import { GenericConstructor } from '../shared/generic-constructor';
|
||||
import { ResponseParsingService } from '../data/parsing.service';
|
||||
import { StatusCodeOnlyResponseParsingService } from '../data/status-code-only-response-parsing.service';
|
||||
import { HALLink } from '../shared/hal-link.model';
|
||||
import { EPersonDataService } from '../eperson/eperson-data.service';
|
||||
import { GroupDataService } from '../eperson/group-data.service';
|
||||
|
||||
|
||||
/**
|
||||
@@ -44,7 +52,8 @@ class DataServiceImpl extends DataService<ResourcePolicy> {
|
||||
protected halService: HALEndpointService,
|
||||
protected notificationsService: NotificationsService,
|
||||
protected http: HttpClient,
|
||||
protected comparator: ChangeAnalyzer<ResourcePolicy>) {
|
||||
protected comparator: ChangeAnalyzer<ResourcePolicy>,
|
||||
) {
|
||||
super();
|
||||
}
|
||||
|
||||
@@ -68,7 +77,10 @@ export class ResourcePolicyService {
|
||||
protected halService: HALEndpointService,
|
||||
protected notificationsService: NotificationsService,
|
||||
protected http: HttpClient,
|
||||
protected comparator: DefaultChangeAnalyzer<ResourcePolicy>) {
|
||||
protected comparator: DefaultChangeAnalyzer<ResourcePolicy>,
|
||||
protected ePersonService: EPersonDataService,
|
||||
protected groupService: GroupDataService,
|
||||
) {
|
||||
this.dataService = new DataServiceImpl(requestService, rdbService, null, objectCache, halService, notificationsService, http, comparator);
|
||||
}
|
||||
|
||||
@@ -221,4 +233,44 @@ export class ResourcePolicyService {
|
||||
return this.dataService.searchBy(this.searchByResourceMethod, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow);
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the target of the resource policy
|
||||
* @param resourcePolicyId the ID of the resource policy
|
||||
* @param resourcePolicyHref the link to the resource policy
|
||||
* @param targetUUID the UUID of the target to which the permission is being granted
|
||||
* @param targetType the type of the target (eperson or group) to which the permission is being granted
|
||||
*/
|
||||
updateTarget(resourcePolicyId: string, resourcePolicyHref: string, targetUUID: string, targetType: string): Observable<RemoteData<any>> {
|
||||
|
||||
const targetService = targetType === 'eperson' ? this.ePersonService : this.groupService;
|
||||
|
||||
const targetEndpoint$ = targetService.getBrowseEndpoint().pipe(
|
||||
take(1),
|
||||
map((endpoint: string) =>`${endpoint}/${targetUUID}`),
|
||||
);
|
||||
|
||||
const options: HttpOptions = Object.create({});
|
||||
let headers = new HttpHeaders();
|
||||
headers = headers.append('Content-Type', 'text/uri-list');
|
||||
options.headers = headers;
|
||||
|
||||
const requestId = this.requestService.generateRequestId();
|
||||
|
||||
this.requestService.setStaleByHrefSubstring(`${this.dataService.getLinkPath()}/${resourcePolicyId}/${targetType}`);
|
||||
|
||||
targetEndpoint$.subscribe((targetEndpoint) => {
|
||||
const resourceEndpoint = resourcePolicyHref + '/' + targetType;
|
||||
const request = new PutRequest(requestId, resourceEndpoint, targetEndpoint, options);
|
||||
Object.assign(request, {
|
||||
getResponseParser(): GenericConstructor<ResponseParsingService> {
|
||||
return StatusCodeOnlyResponseParsingService;
|
||||
}
|
||||
});
|
||||
this.requestService.send(request);
|
||||
});
|
||||
|
||||
return this.rdbService.buildFromRequestUUID(requestId);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -0,0 +1,89 @@
|
||||
/**
|
||||
* An interface to represent an access condition.
|
||||
*/
|
||||
export class SherpaPoliciesDetailsObject {
|
||||
|
||||
/**
|
||||
* The sherpa policies error
|
||||
*/
|
||||
error: boolean;
|
||||
|
||||
/**
|
||||
* The sherpa policies journal details
|
||||
*/
|
||||
journals: Journal[];
|
||||
|
||||
/**
|
||||
* The sherpa policies message
|
||||
*/
|
||||
message: string;
|
||||
|
||||
/**
|
||||
* The sherpa policies metadata
|
||||
*/
|
||||
metadata: Metadata;
|
||||
|
||||
}
|
||||
|
||||
|
||||
export interface Metadata {
|
||||
id: number;
|
||||
uri: string;
|
||||
dateCreated: string;
|
||||
dateModified: string;
|
||||
inDOAJ: boolean;
|
||||
publiclyVisible: boolean;
|
||||
}
|
||||
|
||||
|
||||
export interface Journal {
|
||||
titles: string[];
|
||||
url: string;
|
||||
issns: string[];
|
||||
romeoPub: string;
|
||||
zetoPub: string;
|
||||
inDOAJ: boolean;
|
||||
publisher: Publisher;
|
||||
publishers: Publisher[];
|
||||
policies: Policy[];
|
||||
}
|
||||
|
||||
export interface Publisher {
|
||||
name: string;
|
||||
relationshipType: string;
|
||||
country: string;
|
||||
uri: string;
|
||||
identifier: string;
|
||||
paidAccessDescription: string;
|
||||
paidAccessUrl: string;
|
||||
publicationCount: number;
|
||||
}
|
||||
|
||||
export interface Policy {
|
||||
id: number;
|
||||
openAccessPermitted: boolean;
|
||||
uri: string;
|
||||
internalMoniker: string;
|
||||
permittedVersions: PermittedVersions[];
|
||||
urls: any;
|
||||
publicationCount: number;
|
||||
preArchiving: string;
|
||||
postArchiving: string;
|
||||
pubArchiving: string;
|
||||
openAccessProhibited: boolean;
|
||||
}
|
||||
|
||||
export interface PermittedVersions {
|
||||
articleVersion: string;
|
||||
option: number;
|
||||
conditions: string[];
|
||||
prerequisites: string[];
|
||||
locations: string[];
|
||||
licenses: string[];
|
||||
embargo: Embargo;
|
||||
}
|
||||
|
||||
export interface Embargo {
|
||||
units: any;
|
||||
amount: any;
|
||||
}
|
@@ -0,0 +1,22 @@
|
||||
import { SherpaPoliciesDetailsObject } from './sherpa-policies-details.model';
|
||||
|
||||
/**
|
||||
* An interface to represent the submission's item accesses condition.
|
||||
*/
|
||||
export interface WorkspaceitemSectionSherpaPoliciesObject {
|
||||
|
||||
/**
|
||||
* The access condition id
|
||||
*/
|
||||
id: string;
|
||||
|
||||
/**
|
||||
* The sherpa policies retrievalTime
|
||||
*/
|
||||
retrievalTime: string;
|
||||
|
||||
/**
|
||||
* The sherpa policies details
|
||||
*/
|
||||
sherpaResponse: SherpaPoliciesDetailsObject;
|
||||
}
|
@@ -3,6 +3,7 @@ import { WorkspaceitemSectionFormObject } from './workspaceitem-section-form.mod
|
||||
import { WorkspaceitemSectionLicenseObject } from './workspaceitem-section-license.model';
|
||||
import { WorkspaceitemSectionUploadObject } from './workspaceitem-section-upload.model';
|
||||
import { WorkspaceitemSectionCcLicenseObject } from './workspaceitem-section-cc-license.model';
|
||||
import { WorkspaceitemSectionSherpaPoliciesObject } from './workspaceitem-section-sherpa-policies.model';
|
||||
|
||||
/**
|
||||
* An interface to represent submission's section object.
|
||||
@@ -21,4 +22,5 @@ export type WorkspaceitemSectionDataType
|
||||
| WorkspaceitemSectionLicenseObject
|
||||
| WorkspaceitemSectionCcLicenseObject
|
||||
| WorkspaceitemSectionAccessesObject
|
||||
| WorkspaceitemSectionSherpaPoliciesObject
|
||||
| string;
|
||||
|
@@ -7,13 +7,11 @@
|
||||
class="lead"
|
||||
[innerHTML]="firstMetadataValue('organization.legalName')"></span>
|
||||
<span class="text-muted">
|
||||
<ds-truncatable-part [id]="dso.id" [minLines]="3">
|
||||
<span *ngIf="dso.allMetadata(['dc.description']).length > 0"
|
||||
class="item-list-org-unit-description">
|
||||
<ds-truncatable-part [id]="dso.id" [minLines]="3"><span
|
||||
[innerHTML]="firstMetadataValue('dc.description')"></span>
|
||||
</ds-truncatable-part>
|
||||
</span>
|
||||
</ds-truncatable-part>
|
||||
</span>
|
||||
</ds-truncatable>
|
||||
|
@@ -5,7 +5,7 @@
|
||||
[innerHTML]="name"></a>
|
||||
<span *ngIf="linkType == linkTypes.None"
|
||||
class="lead"
|
||||
[innerHTML]="firstMetadataValue('person.familyName') + ', ' + firstMetadataValue('person.givenName')"></span>
|
||||
[innerHTML]="name"></span>
|
||||
<span class="text-muted">
|
||||
<ds-truncatable-part [id]="dso.id" [minLines]="1">
|
||||
<span *ngIf="dso.allMetadata(['person.jobTitle']).length > 0"
|
||||
|
@@ -1,7 +1,13 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { listableObjectComponent } from '../../../../../shared/object-collection/shared/listable-object/listable-object.decorator';
|
||||
import {
|
||||
listableObjectComponent
|
||||
} from '../../../../../shared/object-collection/shared/listable-object/listable-object.decorator';
|
||||
import { ViewMode } from '../../../../../core/shared/view-mode.model';
|
||||
import { ItemSearchResultListElementComponent } from '../../../../../shared/object-list/search-result-list-element/item-search-result/item-types/item/item-search-result-list-element.component';
|
||||
import {
|
||||
ItemSearchResultListElementComponent
|
||||
} from '../../../../../shared/object-list/search-result-list-element/item-search-result/item-types/item/item-search-result-list-element.component';
|
||||
import { TruncatableService } from '../../../../../shared/truncatable/truncatable.service';
|
||||
import { DSONameService } from '../../../../../core/breadcrumbs/dso-name.service';
|
||||
|
||||
@listableObjectComponent('PersonSearchResult', ViewMode.ListElement)
|
||||
@Component({
|
||||
@@ -14,9 +20,14 @@ import { ItemSearchResultListElementComponent } from '../../../../../shared/obje
|
||||
*/
|
||||
export class PersonSearchResultListElementComponent extends ItemSearchResultListElementComponent {
|
||||
|
||||
public constructor(protected truncatableService: TruncatableService, protected dsoNameService: DSONameService) {
|
||||
super(truncatableService, dsoNameService);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the person name
|
||||
*/
|
||||
get name() {
|
||||
return this.value ?
|
||||
this.value :
|
||||
this.firstMetadataValue('person.familyName') + ', ' + this.firstMetadataValue('person.givenName');
|
||||
return this.dsoNameService.getName(this.dso);
|
||||
}
|
||||
}
|
||||
|
@@ -1,9 +1,10 @@
|
||||
<div class="d-flex flex-row">
|
||||
<h2 class="item-page-title-field mr-auto">
|
||||
{{'person.page.titleprefix' | translate}}<ds-metadata-values [mdValues]="[object?.firstMetadata('person.familyName'), object?.firstMetadata('person.givenName')]" [separator]="', '"></ds-metadata-values>
|
||||
{{'person.page.titleprefix' | translate}}<ds-metadata-values [mdValues]="getTitleMetadataValues()" [separator]="', '"></ds-metadata-values>
|
||||
</h2>
|
||||
<div class="pl-2 space-children-mr">
|
||||
<ds-dso-page-edit-button [pageRoute]="itemPageRoute" [dso]="object" [tooltipMsg]="'person.page.edit'"></ds-dso-page-edit-button>
|
||||
<ds-person-page-claim-button [object]="object"></ds-person-page-claim-button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
@@ -19,18 +20,10 @@
|
||||
[fields]="['person.email']"
|
||||
[label]="'person.page.email'">
|
||||
</ds-generic-item-page-field>
|
||||
<!--<ds-generic-item-page-field [item]="object"-->
|
||||
<!--[fields]="['person.identifier.orcid']"-->
|
||||
<!--[label]="'person.page.orcid'">-->
|
||||
<!--</ds-generic-item-page-field>-->
|
||||
<ds-generic-item-page-field [item]="object"
|
||||
[fields]="['person.birthDate']"
|
||||
[label]="'person.page.birthdate'">
|
||||
</ds-generic-item-page-field>
|
||||
<!--<ds-generic-item-page-field [item]="object"-->
|
||||
<!--[fields]="['person.identifier.staffid']"-->
|
||||
<!--[label]="'person.page.staffid'">-->
|
||||
<!--</ds-generic-item-page-field>-->
|
||||
</div>
|
||||
<div class="col-xs-12 col-md-6">
|
||||
<ds-related-items
|
||||
@@ -55,6 +48,10 @@
|
||||
[fields]="['person.givenName']"
|
||||
[label]="'person.page.firstname'">
|
||||
</ds-generic-item-page-field>
|
||||
<ds-generic-item-page-field [item]="object"
|
||||
[fields]="['dc.title']"
|
||||
[label]="'person.page.name'">
|
||||
</ds-generic-item-page-field>
|
||||
<div>
|
||||
<a class="btn btn-outline-primary" [routerLink]="[itemPageRoute + '/full']">
|
||||
{{"item.page.link.full" | translate}}
|
||||
|
@@ -17,24 +17,12 @@ const mockItem: Item = Object.assign(new Item(), {
|
||||
value: 'fake@email.com'
|
||||
}
|
||||
],
|
||||
// 'person.identifier.orcid': [
|
||||
// {
|
||||
// language: 'en_US',
|
||||
// value: 'ORCID-1'
|
||||
// }
|
||||
// ],
|
||||
'person.birthDate': [
|
||||
{
|
||||
language: 'en_US',
|
||||
value: '1993'
|
||||
}
|
||||
],
|
||||
// 'person.identifier.staffid': [
|
||||
// {
|
||||
// language: 'en_US',
|
||||
// value: '1'
|
||||
// }
|
||||
// ],
|
||||
'person.jobTitle': [
|
||||
{
|
||||
language: 'en_US',
|
||||
@@ -54,7 +42,50 @@ const mockItem: Item = Object.assign(new Item(), {
|
||||
}
|
||||
]
|
||||
},
|
||||
relationships: createRelationshipsObservable()
|
||||
relationships: createRelationshipsObservable(),
|
||||
_links: {
|
||||
self : {
|
||||
href: 'item-href'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
describe('PersonComponent', getItemPageFieldsTest(mockItem, PersonComponent));
|
||||
const mockItemWithTitle: Item = Object.assign(new Item(), {
|
||||
bundles: createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), [])),
|
||||
metadata: {
|
||||
'person.email': [
|
||||
{
|
||||
language: 'en_US',
|
||||
value: 'fake@email.com'
|
||||
}
|
||||
],
|
||||
'person.birthDate': [
|
||||
{
|
||||
language: 'en_US',
|
||||
value: '1993'
|
||||
}
|
||||
],
|
||||
'person.jobTitle': [
|
||||
{
|
||||
language: 'en_US',
|
||||
value: 'Developer'
|
||||
}
|
||||
],
|
||||
'dc.title': [
|
||||
{
|
||||
language: 'en_US',
|
||||
value: 'Doe, John'
|
||||
}
|
||||
]
|
||||
},
|
||||
relationships: createRelationshipsObservable(),
|
||||
_links: {
|
||||
self : {
|
||||
href: 'item-href'
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
describe('PersonComponent with family and given names', getItemPageFieldsTest(mockItem, PersonComponent));
|
||||
|
||||
describe('PersonComponent with dc.title', getItemPageFieldsTest(mockItemWithTitle, PersonComponent));
|
||||
|
@@ -1,7 +1,10 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { ItemComponent } from '../../../../item-page/simple/item-types/shared/item.component';
|
||||
import { ViewMode } from '../../../../core/shared/view-mode.model';
|
||||
import { listableObjectComponent } from '../../../../shared/object-collection/shared/listable-object/listable-object.decorator';
|
||||
import {
|
||||
listableObjectComponent
|
||||
} from '../../../../shared/object-collection/shared/listable-object/listable-object.decorator';
|
||||
import { MetadataValue } from '../../../../core/shared/metadata.models';
|
||||
|
||||
@listableObjectComponent('Person', ViewMode.StandalonePage)
|
||||
@Component({
|
||||
@@ -13,4 +16,24 @@ import { listableObjectComponent } from '../../../../shared/object-collection/sh
|
||||
* The component for displaying metadata and relations of an item of the type Person
|
||||
*/
|
||||
export class PersonComponent extends ItemComponent {
|
||||
|
||||
/**
|
||||
* Returns the metadata values to be used for the page title.
|
||||
*/
|
||||
getTitleMetadataValues(): MetadataValue[] {
|
||||
const metadataValues = [];
|
||||
const familyName = this.object?.firstMetadata('person.familyName');
|
||||
const givenName = this.object?.firstMetadata('person.givenName');
|
||||
const title = this.object?.firstMetadata('dc.title');
|
||||
if (familyName) {
|
||||
metadataValues.push(familyName);
|
||||
}
|
||||
if (givenName) {
|
||||
metadataValues.push(givenName);
|
||||
}
|
||||
if (metadataValues.length === 0 && title) {
|
||||
metadataValues.push(title);
|
||||
}
|
||||
return metadataValues;
|
||||
}
|
||||
}
|
||||
|
@@ -0,0 +1,27 @@
|
||||
<div *ngFor="let entry of healthInfoComponent | dsObjNgFor" data-test="collapse">
|
||||
<div *ngIf="entry && !isPlainProperty(entry.value)" class="mb-3 border-bottom">
|
||||
<div class="w-100 d-flex justify-content-between collapse-toggle" (click)="collapse.toggle()">
|
||||
<button type="button" class="btn btn-link p-0" (click)="$event.preventDefault()" [attr.aria-expanded]="!collapse.collapsed"
|
||||
aria-controls="collapseExample">
|
||||
{{ entry.key | titlecase }}
|
||||
</button>
|
||||
<div class="d-inline-block">
|
||||
<span *ngIf="collapse.collapsed" class="fas fa-chevron-down"></span>
|
||||
<span *ngIf="!collapse.collapsed" class="fas fa-chevron-up"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div #collapse="ngbCollapse" [ngbCollapse]="isCollapsed">
|
||||
<div class="card border-0">
|
||||
<div class="card-body">
|
||||
<ds-health-info-component [healthInfoComponent]="entry.value"
|
||||
[healthInfoComponentName]="entry.key"
|
||||
[isNested]="true"
|
||||
data-test="info-component"></ds-health-info-component>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<ng-container *ngIf="entry && isPlainProperty(entry.value)">
|
||||
<p data-test="property"> <span class="font-weight-bold">{{ getPropertyLabel(entry.key) | titlecase }}</span> : {{entry.value}}</p>
|
||||
</ng-container>
|
||||
</div>
|
@@ -0,0 +1,3 @@
|
||||
.collapse-toggle {
|
||||
cursor: pointer;
|
||||
}
|
@@ -0,0 +1,82 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
|
||||
|
||||
import { NgbCollapseModule } from '@ng-bootstrap/ng-bootstrap';
|
||||
|
||||
import { HealthInfoComponentComponent } from './health-info-component.component';
|
||||
import { HealthInfoComponentOne, HealthInfoComponentTwo } from '../../../shared/mocks/health-endpoint.mocks';
|
||||
import { ObjNgFor } from '../../../shared/utils/object-ngfor.pipe';
|
||||
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
|
||||
import { TranslateLoaderMock } from '../../../shared/mocks/translate-loader.mock';
|
||||
|
||||
describe('HealthInfoComponentComponent', () => {
|
||||
let component: HealthInfoComponentComponent;
|
||||
let fixture: ComponentFixture<HealthInfoComponentComponent>;
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [
|
||||
CommonModule,
|
||||
NgbCollapseModule,
|
||||
NoopAnimationsModule,
|
||||
TranslateModule.forRoot({
|
||||
loader: {
|
||||
provide: TranslateLoader,
|
||||
useClass: TranslateLoaderMock
|
||||
}
|
||||
})
|
||||
],
|
||||
declarations: [
|
||||
HealthInfoComponentComponent,
|
||||
ObjNgFor
|
||||
]
|
||||
})
|
||||
.compileComponents();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(HealthInfoComponentComponent);
|
||||
component = fixture.componentInstance;
|
||||
});
|
||||
|
||||
describe('when has nested components', () => {
|
||||
beforeEach(() => {
|
||||
component.healthInfoComponentName = 'App';
|
||||
component.healthInfoComponent = HealthInfoComponentOne;
|
||||
component.isCollapsed = false;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should display property', () => {
|
||||
const properties = fixture.debugElement.queryAll(By.css('[data-test="property"]'));
|
||||
expect(properties.length).toBe(14);
|
||||
const components = fixture.debugElement.queryAll(By.css('[data-test="info-component"]'));
|
||||
expect(components.length).toBe(4);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe('when has plain properties', () => {
|
||||
beforeEach(() => {
|
||||
component.healthInfoComponentName = 'Java';
|
||||
component.healthInfoComponent = HealthInfoComponentTwo;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should display property', () => {
|
||||
const property = fixture.debugElement.queryAll(By.css('[data-test="property"]'));
|
||||
expect(property.length).toBe(1);
|
||||
});
|
||||
|
||||
});
|
||||
});
|
@@ -0,0 +1,46 @@
|
||||
import { Component, Input } from '@angular/core';
|
||||
|
||||
import { HealthInfoComponent } from '../../models/health-component.model';
|
||||
import { HealthComponentComponent } from '../../health-panel/health-component/health-component.component';
|
||||
|
||||
/**
|
||||
* Shows a health info object
|
||||
*/
|
||||
@Component({
|
||||
selector: 'ds-health-info-component',
|
||||
templateUrl: './health-info-component.component.html',
|
||||
styleUrls: ['./health-info-component.component.scss']
|
||||
})
|
||||
export class HealthInfoComponentComponent extends HealthComponentComponent {
|
||||
|
||||
/**
|
||||
* The HealthInfoComponent object to display
|
||||
*/
|
||||
@Input() healthInfoComponent: HealthInfoComponent|string;
|
||||
|
||||
/**
|
||||
* The HealthInfoComponent object name
|
||||
*/
|
||||
@Input() healthInfoComponentName: string;
|
||||
|
||||
/**
|
||||
* A boolean representing if div should start collapsed
|
||||
*/
|
||||
@Input() isNested = false;
|
||||
|
||||
/**
|
||||
* A boolean representing if div should start collapsed
|
||||
*/
|
||||
public isCollapsed = false;
|
||||
|
||||
/**
|
||||
* Check if the HealthInfoComponent is has only string property or contains object
|
||||
*
|
||||
* @param entry The HealthInfoComponent to check
|
||||
* @return boolean
|
||||
*/
|
||||
isPlainProperty(entry: HealthInfoComponent | string): boolean {
|
||||
return typeof entry === 'string';
|
||||
}
|
||||
|
||||
}
|
25
src/app/health-page/health-info/health-info.component.html
Normal file
25
src/app/health-page/health-info/health-info.component.html
Normal file
@@ -0,0 +1,25 @@
|
||||
<ng-container *ngIf="healthInfoResponse">
|
||||
<ngb-accordion #acc="ngbAccordion" [activeIds]="activeId">
|
||||
<ngb-panel [id]="entry.key" *ngFor="let entry of healthInfoResponse | dsObjNgFor">
|
||||
<ng-template ngbPanelHeader>
|
||||
<div class="w-100 d-flex justify-content-between collapse-toggle" ngbPanelToggle (click)="acc.toggle(entry.key)" data-test="info-component">
|
||||
<button type="button" class="btn btn-link p-0" (click)="$event.preventDefault()" [attr.aria-expanded]="!acc.isExpanded(entry.key)"
|
||||
aria-controls="collapsePanels">
|
||||
{{ getPanelLabel(entry.key) | titlecase }}
|
||||
</button>
|
||||
<div class="text-right d-flex">
|
||||
<ds-health-status [status]="entry.value?.status"></ds-health-status>
|
||||
<div class="ml-3 d-inline-block">
|
||||
<span *ngIf="acc.isExpanded(entry.key)" class="fas fa-chevron-up fa-fw"></span>
|
||||
<span *ngIf="!acc.isExpanded(entry.key)" class="fas fa-chevron-down fa-fw"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ng-template>
|
||||
<ng-template ngbPanelContent>
|
||||
<ds-health-info-component [healthInfoComponentName]="entry.key"
|
||||
[healthInfoComponent]="entry.value"></ds-health-info-component>
|
||||
</ng-template>
|
||||
</ngb-panel>
|
||||
</ngb-accordion>
|
||||
</ng-container>
|
@@ -0,0 +1,3 @@
|
||||
.collapse-toggle {
|
||||
cursor: pointer;
|
||||
}
|
@@ -0,0 +1,51 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { HealthInfoComponent } from './health-info.component';
|
||||
import { HealthInfoResponseObj } from '../../shared/mocks/health-endpoint.mocks';
|
||||
import { ObjNgFor } from '../../shared/utils/object-ngfor.pipe';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { NgbAccordionModule } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
|
||||
import { TranslateLoaderMock } from '../../shared/mocks/translate-loader.mock';
|
||||
|
||||
describe('HealthInfoComponent', () => {
|
||||
let component: HealthInfoComponent;
|
||||
let fixture: ComponentFixture<HealthInfoComponent>;
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [
|
||||
NgbAccordionModule,
|
||||
TranslateModule.forRoot({
|
||||
loader: {
|
||||
provide: TranslateLoader,
|
||||
useClass: TranslateLoaderMock
|
||||
}
|
||||
})
|
||||
],
|
||||
declarations: [
|
||||
HealthInfoComponent,
|
||||
ObjNgFor
|
||||
],
|
||||
schemas: [NO_ERRORS_SCHEMA]
|
||||
})
|
||||
.compileComponents();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(HealthInfoComponent);
|
||||
component = fixture.componentInstance;
|
||||
component.healthInfoResponse = HealthInfoResponseObj;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should create info component properly', () => {
|
||||
const components = fixture.debugElement.queryAll(By.css('[data-test="info-component"]'));
|
||||
expect(components.length).toBe(3);
|
||||
});
|
||||
});
|
46
src/app/health-page/health-info/health-info.component.ts
Normal file
46
src/app/health-page/health-info/health-info.component.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
import { Component, Input, OnInit } from '@angular/core';
|
||||
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
|
||||
import { HealthInfoResponse } from '../models/health-component.model';
|
||||
|
||||
/**
|
||||
* A component to render a "health-info component" object.
|
||||
*
|
||||
* Note that the word "component" in "health-info component" doesn't refer to Angular use of the term
|
||||
* but rather to the components used in the response of the health endpoint of Spring's Actuator
|
||||
* API.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'ds-health-info',
|
||||
templateUrl: './health-info.component.html',
|
||||
styleUrls: ['./health-info.component.scss']
|
||||
})
|
||||
export class HealthInfoComponent implements OnInit {
|
||||
|
||||
@Input() healthInfoResponse: HealthInfoResponse;
|
||||
|
||||
/**
|
||||
* The first active panel id
|
||||
*/
|
||||
activeId: string;
|
||||
|
||||
constructor(private translate: TranslateService) {
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.activeId = Object.keys(this.healthInfoResponse)[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Return translated label if exist for the given property
|
||||
*
|
||||
* @param panelKey
|
||||
*/
|
||||
public getPanelLabel(panelKey: string): string {
|
||||
const translationKey = `health-page.section-info.${panelKey}.title`;
|
||||
const translation = this.translate.instant(translationKey);
|
||||
|
||||
return (translation === translationKey) ? panelKey : translation;
|
||||
}
|
||||
}
|
27
src/app/health-page/health-page.component.html
Normal file
27
src/app/health-page/health-page.component.html
Normal file
@@ -0,0 +1,27 @@
|
||||
<div class="container" *ngIf="(healthResponseInitialised | async) && (healthInfoResponseInitialised | async)">
|
||||
<h2>{{'health-page.heading' | translate}}</h2>
|
||||
<div *ngIf="(healthResponse | async) && (healthInfoResponse | async)">
|
||||
<ul ngbNav #nav="ngbNav" [activeId]="'status'" class="nav-tabs">
|
||||
<li [ngbNavItem]="'status'">
|
||||
<a ngbNavLink>{{'health-page.status-tab' | translate}}</a>
|
||||
<ng-template ngbNavContent>
|
||||
<div id="status">
|
||||
<ds-health-panel [healthResponse]="(healthResponse | async)"></ds-health-panel>
|
||||
</div>
|
||||
</ng-template>
|
||||
</li>
|
||||
<li [ngbNavItem]="'info'">
|
||||
<a ngbNavLink>{{'health-page.info-tab' | translate}}</a>
|
||||
<ng-template ngbNavContent>
|
||||
<div id="info">
|
||||
<ds-health-info [healthInfoResponse]="(healthInfoResponse | async)"></ds-health-info>
|
||||
</div>
|
||||
</ng-template>
|
||||
</li>
|
||||
</ul>
|
||||
<div [ngbNavOutlet]="nav" class="mt-2"></div>
|
||||
</div>
|
||||
<ds-alert *ngIf="!(healthResponse | async) || !(healthInfoResponse | async)" [type]="'alert-danger'" [content]="'health-page.error.msg'"></ds-alert>
|
||||
</div>
|
||||
|
||||
|
0
src/app/health-page/health-page.component.scss
Normal file
0
src/app/health-page/health-page.component.scss
Normal file
72
src/app/health-page/health-page.component.spec.ts
Normal file
72
src/app/health-page/health-page.component.spec.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { By } from '@angular/platform-browser';
|
||||
|
||||
import { of } from 'rxjs';
|
||||
import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
|
||||
|
||||
import { HealthPageComponent } from './health-page.component';
|
||||
import { HealthService } from './health.service';
|
||||
import { HealthInfoResponseObj, HealthResponseObj } from '../shared/mocks/health-endpoint.mocks';
|
||||
import { RawRestResponse } from '../core/dspace-rest/raw-rest-response.model';
|
||||
import { TranslateLoaderMock } from '../shared/mocks/translate-loader.mock';
|
||||
|
||||
describe('HealthPageComponent', () => {
|
||||
let component: HealthPageComponent;
|
||||
let fixture: ComponentFixture<HealthPageComponent>;
|
||||
|
||||
const healthService = jasmine.createSpyObj('healthDataService', {
|
||||
getHealth: jasmine.createSpy('getHealth'),
|
||||
getInfo: jasmine.createSpy('getInfo'),
|
||||
});
|
||||
|
||||
const healthRestResponse$ = of({
|
||||
payload: HealthResponseObj,
|
||||
statusCode: 200,
|
||||
statusText: 'OK'
|
||||
} as RawRestResponse);
|
||||
|
||||
const healthInfoRestResponse$ = of({
|
||||
payload: HealthInfoResponseObj,
|
||||
statusCode: 200,
|
||||
statusText: 'OK'
|
||||
} as RawRestResponse);
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [
|
||||
CommonModule,
|
||||
NgbNavModule,
|
||||
TranslateModule.forRoot({
|
||||
loader: {
|
||||
provide: TranslateLoader,
|
||||
useClass: TranslateLoaderMock
|
||||
}
|
||||
})
|
||||
],
|
||||
declarations: [ HealthPageComponent ],
|
||||
providers: [
|
||||
{ provide: HealthService, useValue: healthService }
|
||||
]
|
||||
})
|
||||
.compileComponents();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(HealthPageComponent);
|
||||
component = fixture.componentInstance;
|
||||
healthService.getHealth.and.returnValue(healthRestResponse$);
|
||||
healthService.getInfo.and.returnValue(healthInfoRestResponse$);
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should create nav items properly', () => {
|
||||
const navItems = fixture.debugElement.queryAll(By.css('li.nav-item'));
|
||||
expect(navItems.length).toBe(2);
|
||||
});
|
||||
});
|
66
src/app/health-page/health-page.component.ts
Normal file
66
src/app/health-page/health-page.component.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
|
||||
import { BehaviorSubject } from 'rxjs';
|
||||
import { take } from 'rxjs/operators';
|
||||
|
||||
import { HealthService } from './health.service';
|
||||
import { HealthInfoResponse, HealthResponse } from './models/health-component.model';
|
||||
|
||||
@Component({
|
||||
selector: 'ds-health-page',
|
||||
templateUrl: './health-page.component.html',
|
||||
styleUrls: ['./health-page.component.scss']
|
||||
})
|
||||
export class HealthPageComponent implements OnInit {
|
||||
|
||||
/**
|
||||
* Health info endpoint response
|
||||
*/
|
||||
healthInfoResponse: BehaviorSubject<HealthInfoResponse> = new BehaviorSubject<HealthInfoResponse>(null);
|
||||
|
||||
/**
|
||||
* Health endpoint response
|
||||
*/
|
||||
healthResponse: BehaviorSubject<HealthResponse> = new BehaviorSubject<HealthResponse>(null);
|
||||
|
||||
/**
|
||||
* Represent if the response from health status endpoint is already retrieved or not
|
||||
*/
|
||||
healthResponseInitialised: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
|
||||
|
||||
/**
|
||||
* Represent if the response from health info endpoint is already retrieved or not
|
||||
*/
|
||||
healthInfoResponseInitialised: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
|
||||
|
||||
constructor(private healthDataService: HealthService) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieve responses from rest
|
||||
*/
|
||||
ngOnInit(): void {
|
||||
this.healthDataService.getHealth().pipe(take(1)).subscribe({
|
||||
next: (data: any) => {
|
||||
this.healthResponse.next(data.payload);
|
||||
this.healthResponseInitialised.next(true);
|
||||
},
|
||||
error: () => {
|
||||
this.healthResponse.next(null);
|
||||
this.healthResponseInitialised.next(true);
|
||||
}
|
||||
});
|
||||
|
||||
this.healthDataService.getInfo().pipe(take(1)).subscribe({
|
||||
next: (data: any) => {
|
||||
this.healthInfoResponse.next(data.payload);
|
||||
this.healthInfoResponseInitialised.next(true);
|
||||
},
|
||||
error: () => {
|
||||
this.healthInfoResponse.next(null);
|
||||
this.healthInfoResponseInitialised.next(true);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
}
|
35
src/app/health-page/health-page.module.ts
Normal file
35
src/app/health-page/health-page.module.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { NgModule } from '@angular/core';
|
||||
|
||||
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
|
||||
import { HealthPageRoutingModule } from './health-page.routing.module';
|
||||
import { HealthPanelComponent } from './health-panel/health-panel.component';
|
||||
import { HealthStatusComponent } from './health-panel/health-status/health-status.component';
|
||||
import { SharedModule } from '../shared/shared.module';
|
||||
import { HealthPageComponent } from './health-page.component';
|
||||
import { HealthComponentComponent } from './health-panel/health-component/health-component.component';
|
||||
import { HealthInfoComponent } from './health-info/health-info.component';
|
||||
import { HealthInfoComponentComponent } from './health-info/health-info-component/health-info-component.component';
|
||||
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
CommonModule,
|
||||
HealthPageRoutingModule,
|
||||
NgbModule,
|
||||
SharedModule,
|
||||
TranslateModule
|
||||
],
|
||||
declarations: [
|
||||
HealthPageComponent,
|
||||
HealthPanelComponent,
|
||||
HealthStatusComponent,
|
||||
HealthComponentComponent,
|
||||
HealthInfoComponent,
|
||||
HealthInfoComponentComponent,
|
||||
]
|
||||
})
|
||||
export class HealthPageModule {
|
||||
}
|
28
src/app/health-page/health-page.routing.module.ts
Normal file
28
src/app/health-page/health-page.routing.module.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { RouterModule } from '@angular/router';
|
||||
import { NgModule } from '@angular/core';
|
||||
|
||||
import { I18nBreadcrumbResolver } from '../core/breadcrumbs/i18n-breadcrumb.resolver';
|
||||
import { HealthPageComponent } from './health-page.component';
|
||||
import {
|
||||
SiteAdministratorGuard
|
||||
} from '../core/data/feature-authorization/feature-authorization-guard/site-administrator.guard';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
RouterModule.forChild([
|
||||
{
|
||||
path: '',
|
||||
resolve: { breadcrumb: I18nBreadcrumbResolver },
|
||||
data: {
|
||||
breadcrumbKey: 'health',
|
||||
title: 'health-page.title',
|
||||
},
|
||||
canActivate: [SiteAdministratorGuard],
|
||||
component: HealthPageComponent
|
||||
}
|
||||
])
|
||||
]
|
||||
})
|
||||
export class HealthPageRoutingModule {
|
||||
|
||||
}
|
@@ -0,0 +1,30 @@
|
||||
<ng-container *ngIf="healthComponent?.components">
|
||||
<div *ngFor="let entry of healthComponent?.components | dsObjNgFor" class="mb-3 border-bottom" data-test="collapse">
|
||||
<div class="w-100 d-flex justify-content-between collapse-toggle" (click)="collapse.toggle()">
|
||||
<button type="button" class="btn btn-link p-0" (click)="$event.preventDefault()" [attr.aria-expanded]="!collapse.collapsed"
|
||||
aria-controls="collapseExample">
|
||||
{{ entry.key | titlecase }}
|
||||
</button>
|
||||
<div class="d-inline-block">
|
||||
<span *ngIf="collapse.collapsed" class="fas fa-chevron-down"></span>
|
||||
<span *ngIf="!collapse.collapsed" class="fas fa-chevron-up"></span>
|
||||
</div>
|
||||
</div>
|
||||
<div #collapse="ngbCollapse" [ngbCollapse]="isCollapsed">
|
||||
<div class="card border-0">
|
||||
<div class="card-body">
|
||||
<ds-health-component [healthComponent]="entry.value"
|
||||
[healthComponentName]="entry.key"></ds-health-component>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
<ng-container *ngIf="healthComponent?.details">
|
||||
<div *ngFor="let item of healthComponent?.details | dsObjNgFor" data-test="details">
|
||||
<p data-test="property"><span class="font-weight-bold">{{ getPropertyLabel(item.key) | titlecase }}</span> : {{item.value}}</p>
|
||||
</div>
|
||||
</ng-container>
|
||||
<ng-container *ngIf="!healthComponent?.details && !healthComponent?.components">
|
||||
<ds-alert [content]="'health-page.section.no-issues'" [type]="AlertTypeEnum.Info"></ds-alert>
|
||||
</ng-container>
|
@@ -0,0 +1,3 @@
|
||||
.collapse-toggle {
|
||||
cursor: pointer;
|
||||
}
|
@@ -0,0 +1,85 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
|
||||
import { NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
|
||||
import { NgbCollapseModule } from '@ng-bootstrap/ng-bootstrap';
|
||||
|
||||
import { HealthComponentComponent } from './health-component.component';
|
||||
import { HealthComponentOne, HealthComponentTwo } from '../../../shared/mocks/health-endpoint.mocks';
|
||||
import { ObjNgFor } from '../../../shared/utils/object-ngfor.pipe';
|
||||
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
|
||||
import { TranslateLoaderMock } from '../../../shared/mocks/translate-loader.mock';
|
||||
|
||||
describe('HealthComponentComponent', () => {
|
||||
let component: HealthComponentComponent;
|
||||
let fixture: ComponentFixture<HealthComponentComponent>;
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [
|
||||
CommonModule,
|
||||
NgbCollapseModule,
|
||||
NoopAnimationsModule,
|
||||
TranslateModule.forRoot({
|
||||
loader: {
|
||||
provide: TranslateLoader,
|
||||
useClass: TranslateLoaderMock
|
||||
}
|
||||
})
|
||||
],
|
||||
declarations: [
|
||||
HealthComponentComponent,
|
||||
ObjNgFor
|
||||
],
|
||||
schemas: [NO_ERRORS_SCHEMA]
|
||||
})
|
||||
.compileComponents();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(HealthComponentComponent);
|
||||
component = fixture.componentInstance;
|
||||
});
|
||||
|
||||
describe('when has nested components', () => {
|
||||
beforeEach(() => {
|
||||
component.healthComponentName = 'db';
|
||||
component.healthComponent = HealthComponentOne;
|
||||
component.isCollapsed = false;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should create collapsible divs properly', () => {
|
||||
const collapseDivs = fixture.debugElement.queryAll(By.css('[data-test="collapse"]'));
|
||||
expect(collapseDivs.length).toBe(2);
|
||||
const detailsDivs = fixture.debugElement.queryAll(By.css('[data-test="details"]'));
|
||||
expect(detailsDivs.length).toBe(6);
|
||||
});
|
||||
});
|
||||
|
||||
describe('when has details', () => {
|
||||
beforeEach(() => {
|
||||
component.healthComponentName = 'geoIp';
|
||||
component.healthComponent = HealthComponentTwo;
|
||||
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should create detail divs properly', () => {
|
||||
const detailsDivs = fixture.debugElement.queryAll(By.css('[data-test="details"]'));
|
||||
expect(detailsDivs.length).toBe(1);
|
||||
const collapseDivs = fixture.debugElement.queryAll(By.css('[data-test="collapse"]'));
|
||||
expect(collapseDivs.length).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
@@ -0,0 +1,53 @@
|
||||
import { Component, Input } from '@angular/core';
|
||||
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
|
||||
import { HealthComponent } from '../../models/health-component.model';
|
||||
import { AlertType } from '../../../shared/alert/aletr-type';
|
||||
|
||||
/**
|
||||
* A component to render a "health component" object.
|
||||
*
|
||||
* Note that the word "component" in "health component" doesn't refer to Angular use of the term
|
||||
* but rather to the components used in the response of the health endpoint of Spring's Actuator
|
||||
* API.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'ds-health-component',
|
||||
templateUrl: './health-component.component.html',
|
||||
styleUrls: ['./health-component.component.scss']
|
||||
})
|
||||
export class HealthComponentComponent {
|
||||
|
||||
/**
|
||||
* The HealthComponent object to display
|
||||
*/
|
||||
@Input() healthComponent: HealthComponent;
|
||||
|
||||
/**
|
||||
* The HealthComponent object name
|
||||
*/
|
||||
@Input() healthComponentName: string;
|
||||
|
||||
public AlertTypeEnum = AlertType;
|
||||
|
||||
/**
|
||||
* A boolean representing if div should start collapsed
|
||||
*/
|
||||
public isCollapsed = false;
|
||||
|
||||
constructor(private translate: TranslateService) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return translated label if exist for the given property
|
||||
*
|
||||
* @param property
|
||||
*/
|
||||
public getPropertyLabel(property: string): string {
|
||||
const translationKey = `health-page.property.${property}`;
|
||||
const translation = this.translate.instant(translationKey);
|
||||
|
||||
return (translation === translationKey) ? property : translation;
|
||||
}
|
||||
}
|
25
src/app/health-page/health-panel/health-panel.component.html
Normal file
25
src/app/health-page/health-panel/health-panel.component.html
Normal file
@@ -0,0 +1,25 @@
|
||||
<p class="h4">{{'health-page.status' | translate}} : <ds-health-status [status]="healthResponse.status"></ds-health-status></p>
|
||||
<ngb-accordion #acc="ngbAccordion" [activeIds]="activeId">
|
||||
<ngb-panel [id]="entry.key" *ngFor="let entry of healthResponse.components | dsObjNgFor">
|
||||
<ng-template ngbPanelHeader>
|
||||
<div class="w-100 d-flex justify-content-between collapse-toggle" ngbPanelToggle (click)="acc.toggle(entry.key)" data-test="component">
|
||||
<button type="button" class="btn btn-link p-0" (click)="$event.preventDefault()" [attr.aria-expanded]="!acc.isExpanded(entry.key)"
|
||||
aria-controls="collapsePanels">
|
||||
{{ getPanelLabel(entry.key) | titlecase }}
|
||||
</button>
|
||||
<div class="text-right d-flex">
|
||||
<ds-health-status [status]="entry.value?.status"></ds-health-status>
|
||||
<div class="ml-3 d-inline-block">
|
||||
<span *ngIf="acc.isExpanded(entry.key)" class="fas fa-chevron-up fa-fw"></span>
|
||||
<span *ngIf="!acc.isExpanded(entry.key)" class="fas fa-chevron-down fa-fw"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ng-template>
|
||||
<ng-template ngbPanelContent>
|
||||
<ds-health-component [healthComponent]="entry.value" [healthComponentName]="entry.key"></ds-health-component>
|
||||
</ng-template>
|
||||
</ngb-panel>
|
||||
</ngb-accordion>
|
||||
|
||||
|
@@ -0,0 +1,3 @@
|
||||
.collapse-toggle {
|
||||
cursor: pointer;
|
||||
}
|
@@ -0,0 +1,57 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
|
||||
import { NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
|
||||
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
|
||||
import { NgbAccordionModule, NgbNavModule } from '@ng-bootstrap/ng-bootstrap';
|
||||
|
||||
import { TranslateLoaderMock } from '../../shared/mocks/translate-loader.mock';
|
||||
import { HealthPanelComponent } from './health-panel.component';
|
||||
import { HealthResponseObj } from '../../shared/mocks/health-endpoint.mocks';
|
||||
import { ObjNgFor } from '../../shared/utils/object-ngfor.pipe';
|
||||
|
||||
describe('HealthPanelComponent', () => {
|
||||
let component: HealthPanelComponent;
|
||||
let fixture: ComponentFixture<HealthPanelComponent>;
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [
|
||||
NgbNavModule,
|
||||
NgbAccordionModule,
|
||||
CommonModule,
|
||||
BrowserAnimationsModule,
|
||||
TranslateModule.forRoot({
|
||||
loader: {
|
||||
provide: TranslateLoader,
|
||||
useClass: TranslateLoaderMock
|
||||
}
|
||||
}),
|
||||
],
|
||||
declarations: [
|
||||
HealthPanelComponent,
|
||||
ObjNgFor
|
||||
],
|
||||
schemas: [NO_ERRORS_SCHEMA]
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(HealthPanelComponent);
|
||||
component = fixture.componentInstance;
|
||||
component.healthResponse = HealthResponseObj;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should render a panel for each component', () => {
|
||||
const components = fixture.debugElement.queryAll(By.css('[data-test="component"]'));
|
||||
expect(components.length).toBe(5);
|
||||
});
|
||||
|
||||
});
|
45
src/app/health-page/health-panel/health-panel.component.ts
Normal file
45
src/app/health-page/health-panel/health-panel.component.ts
Normal file
@@ -0,0 +1,45 @@
|
||||
import { Component, Input, OnInit } from '@angular/core';
|
||||
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
|
||||
import { HealthResponse } from '../models/health-component.model';
|
||||
|
||||
/**
|
||||
* Show the health panel
|
||||
*/
|
||||
@Component({
|
||||
selector: 'ds-health-panel',
|
||||
templateUrl: './health-panel.component.html',
|
||||
styleUrls: ['./health-panel.component.scss']
|
||||
})
|
||||
export class HealthPanelComponent implements OnInit {
|
||||
|
||||
/**
|
||||
* Health endpoint response
|
||||
*/
|
||||
@Input() healthResponse: HealthResponse;
|
||||
|
||||
/**
|
||||
* The first active panel id
|
||||
*/
|
||||
activeId: string;
|
||||
|
||||
constructor(private translate: TranslateService) {
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.activeId = Object.keys(this.healthResponse.components)[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Return translated label if exist for the given property
|
||||
*
|
||||
* @param panelKey
|
||||
*/
|
||||
public getPanelLabel(panelKey: string): string {
|
||||
const translationKey = `health-page.section.${panelKey}.title`;
|
||||
const translation = this.translate.instant(translationKey);
|
||||
|
||||
return (translation === translationKey) ? panelKey : translation;
|
||||
}
|
||||
}
|
@@ -0,0 +1,12 @@
|
||||
<ng-container [ngSwitch]="status">
|
||||
<i *ngSwitchCase="HealthStatus.UP"
|
||||
class="fa fa-check-circle text-success ml-2 mt-1"
|
||||
ngbTooltip="{{'health-page.status.ok.info' | translate}}" container="body" ></i>
|
||||
<i *ngSwitchCase="HealthStatus.UP_WITH_ISSUES"
|
||||
class="fa fa-exclamation-triangle text-warning ml-2 mt-1"
|
||||
ngbTooltip="{{'health-page.status.warning.info' | translate}}" container="body"></i>
|
||||
<i *ngSwitchCase="HealthStatus.DOWN"
|
||||
class="fa fa-times-circle text-danger ml-2 mt-1"
|
||||
ngbTooltip="{{'health-page.status.error.info' | translate}}" container="body"></i>
|
||||
|
||||
</ng-container>
|
@@ -0,0 +1,60 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
|
||||
import { HealthStatusComponent } from './health-status.component';
|
||||
import { HealthStatus } from '../../models/health-component.model';
|
||||
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
|
||||
import { TranslateLoaderMock } from '../../../shared/mocks/translate-loader.mock';
|
||||
import { NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
|
||||
|
||||
describe('HealthStatusComponent', () => {
|
||||
let component: HealthStatusComponent;
|
||||
let fixture: ComponentFixture<HealthStatusComponent>;
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [
|
||||
NgbTooltipModule,
|
||||
TranslateModule.forRoot({
|
||||
loader: {
|
||||
provide: TranslateLoader,
|
||||
useClass: TranslateLoaderMock
|
||||
}
|
||||
})
|
||||
],
|
||||
declarations: [ HealthStatusComponent ]
|
||||
})
|
||||
.compileComponents();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(HealthStatusComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should create success icon', () => {
|
||||
component.status = HealthStatus.UP;
|
||||
fixture.detectChanges();
|
||||
const icon = fixture.debugElement.query(By.css('i.text-success'));
|
||||
expect(icon).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should create warning icon', () => {
|
||||
component.status = HealthStatus.UP_WITH_ISSUES;
|
||||
fixture.detectChanges();
|
||||
const icon = fixture.debugElement.query(By.css('i.text-warning'));
|
||||
expect(icon).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should create success icon', () => {
|
||||
component.status = HealthStatus.DOWN;
|
||||
fixture.detectChanges();
|
||||
const icon = fixture.debugElement.query(By.css('i.text-danger'));
|
||||
expect(icon).toBeTruthy();
|
||||
});
|
||||
});
|
@@ -0,0 +1,23 @@
|
||||
import { Component, Input } from '@angular/core';
|
||||
import { HealthStatus } from '../../models/health-component.model';
|
||||
|
||||
/**
|
||||
* Show a health status object
|
||||
*/
|
||||
@Component({
|
||||
selector: 'ds-health-status',
|
||||
templateUrl: './health-status.component.html',
|
||||
styleUrls: ['./health-status.component.scss']
|
||||
})
|
||||
export class HealthStatusComponent {
|
||||
/**
|
||||
* The current status to show
|
||||
*/
|
||||
@Input() status: HealthStatus;
|
||||
|
||||
/**
|
||||
* He
|
||||
*/
|
||||
HealthStatus = HealthStatus;
|
||||
|
||||
}
|
32
src/app/health-page/health.service.ts
Normal file
32
src/app/health-page/health.service.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { DspaceRestService } from '../core/dspace-rest/dspace-rest.service';
|
||||
import { RawRestResponse } from '../core/dspace-rest/raw-rest-response.model';
|
||||
import { HALEndpointService } from '../core/shared/hal-endpoint.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class HealthService {
|
||||
constructor(protected halService: HALEndpointService,
|
||||
protected restService: DspaceRestService) {
|
||||
}
|
||||
/**
|
||||
* @returns health data
|
||||
*/
|
||||
getHealth(): Observable<RawRestResponse> {
|
||||
return this.halService.getEndpoint('/actuator').pipe(
|
||||
map((restURL: string) => restURL + '/health'),
|
||||
switchMap((endpoint: string) => this.restService.get(endpoint)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns information of server
|
||||
*/
|
||||
getInfo(): Observable<RawRestResponse> {
|
||||
return this.halService.getEndpoint('/actuator').pipe(
|
||||
map((restURL: string) => restURL + '/info'),
|
||||
switchMap((endpoint: string) => this.restService.get(endpoint)));
|
||||
}
|
||||
}
|
48
src/app/health-page/models/health-component.model.ts
Normal file
48
src/app/health-page/models/health-component.model.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* Interface for Health Status
|
||||
*/
|
||||
export enum HealthStatus {
|
||||
UP = 'UP',
|
||||
UP_WITH_ISSUES = 'UP_WITH_ISSUES',
|
||||
DOWN = 'DOWN'
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface describing the Health endpoint response
|
||||
*/
|
||||
export interface HealthResponse {
|
||||
status: HealthStatus;
|
||||
components: {
|
||||
[name: string]: HealthComponent;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface describing a single component retrieved from the Health endpoint response
|
||||
*/
|
||||
export interface HealthComponent {
|
||||
status: HealthStatus;
|
||||
details?: {
|
||||
[name: string]: number|string;
|
||||
};
|
||||
components?: {
|
||||
[name: string]: HealthComponent;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface describing the Health info endpoint response
|
||||
*/
|
||||
export interface HealthInfoResponse {
|
||||
[name: string]: HealthInfoComponent|string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface describing a single component retrieved from the Health info endpoint response
|
||||
*/
|
||||
export interface HealthInfoComponent {
|
||||
[property: string]: HealthInfoComponent|string;
|
||||
}
|
||||
|
||||
|
||||
|
@@ -1,7 +1,7 @@
|
||||
import { NgModule } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
|
||||
import { NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { NgbTooltipModule, NgbModule } from '@ng-bootstrap/ng-bootstrap';
|
||||
|
||||
import { SharedModule } from '../../shared/shared.module';
|
||||
import { EditItemPageRoutingModule } from './edit-item-page.routing.module';
|
||||
@@ -48,7 +48,8 @@ import { ResourcePoliciesModule } from '../../shared/resource-policies/resource-
|
||||
EditItemPageRoutingModule,
|
||||
SearchPageModule,
|
||||
DragDropModule,
|
||||
ResourcePoliciesModule
|
||||
ResourcePoliciesModule,
|
||||
NgbModule
|
||||
],
|
||||
declarations: [
|
||||
EditItemPageComponent,
|
||||
|
@@ -1,13 +1,33 @@
|
||||
<div class="container">
|
||||
<ds-alert [type]="'alert-info'" [content]="'item.edit.authorizations.heading'"></ds-alert>
|
||||
<ds-resource-policies [resourceType]="'item'" [resourceUUID]="(getItemUUID() | async)"></ds-resource-policies>
|
||||
<ng-container *ngFor="let bundle of (getItemBundles() | async); trackById">
|
||||
<ds-resource-policies [resourceType]="'bundle'"
|
||||
[resourceUUID]="bundle.id"></ds-resource-policies>
|
||||
<ng-container *ngFor="let bitstream of (bundleBitstreamsMap.get(bundle.id) | async)?.page; trackById">
|
||||
<ds-resource-policies [resourceType]="'bitstream'"
|
||||
[resourceUUID]="bitstream.id"></ds-resource-policies>
|
||||
<ds-resource-policies [resourceType]="'item'" [resourceName]="(getItemName() | async)"
|
||||
[resourceUUID]="(getItemUUID() | async)">
|
||||
</ds-resource-policies>
|
||||
<ng-container *ngFor="let bundle of (bundles$ | async); trackById">
|
||||
<ds-resource-policies [resourceType]="'bundle'" [resourceUUID]="bundle.id" [resourceName]="bundle.name">
|
||||
</ds-resource-policies>
|
||||
<ng-container *ngIf="(bundleBitstreamsMap.get(bundle.id)?.bitstreams | async)?.length > 0">
|
||||
<div class="card auth-bitstream-container">
|
||||
<div class="card-header">
|
||||
<button type="button" class="btn btn-outline-primary" (click)="collapseArea(bundle.id)"
|
||||
[attr.aria-expanded]="false" [attr.aria-controls]="bundle.id">
|
||||
{{ 'collection.edit.item.authorizations.show-bitstreams-button' | translate }} {{bundle.name}}
|
||||
</button>
|
||||
</div>
|
||||
<div class="card-body" [id]="bundle.id" [ngbCollapse]="bundleBitstreamsMap.get(bundle.id).isCollapsed">
|
||||
<ng-container
|
||||
*ngFor="let bitstream of (bundleBitstreamsMap.get(bundle.id).bitstreams | async); trackById">
|
||||
<ds-resource-policies [resourceType]="'bitstream'" [resourceUUID]="bitstream.id"
|
||||
[resourceName]="bitstream.name"></ds-resource-policies>
|
||||
</ng-container>
|
||||
<div class="row justify-content-center" *ngIf="!bundleBitstreamsMap.get(bundle.id).allBitstreamsLoaded">
|
||||
<button type="button" class="btn btn-link" (click)="onBitstreamsLoad(bundle)">{{ 'collection.edit.item.authorizations.load-more-button' | translate }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
</ng-container>
|
||||
<div class="row justify-content-center" *ngIf="!allBundlesLoaded">
|
||||
<button type="button" class="btn btn-link" (click)="onBundleLoad()">{{ 'collection.edit.item.authorizations.load-bundle-button' | translate }}</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
@@ -0,0 +1,4 @@
|
||||
.auth-bitstream-container {
|
||||
margin-top: -1em;
|
||||
margin-bottom: 1.5em;
|
||||
}
|
@@ -1,11 +1,12 @@
|
||||
import { Observable } from 'rxjs/internal/Observable';
|
||||
import { waitForAsync, ComponentFixture, inject, TestBed } from '@angular/core/testing';
|
||||
import { Component, NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
|
||||
import { of as observableOf } from 'rxjs';
|
||||
import { of as observableOf, of } from 'rxjs';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
import { cold } from 'jasmine-marbles';
|
||||
import { ItemAuthorizationsComponent } from './item-authorizations.component';
|
||||
import { ItemAuthorizationsComponent, BitstreamMapValue } from './item-authorizations.component';
|
||||
import { Bitstream } from '../../../core/shared/bitstream.model';
|
||||
import { Bundle } from '../../../core/shared/bundle.model';
|
||||
import { Item } from '../../../core/shared/item.model';
|
||||
@@ -57,8 +58,6 @@ describe('ItemAuthorizationsComponent test suite', () => {
|
||||
bitstreams: createSuccessfulRemoteDataObject$(createPaginatedList([bitstream3, bitstream4]))
|
||||
});
|
||||
const bundles = [bundle1, bundle2];
|
||||
const bitstreamList1: PaginatedList<Bitstream> = buildPaginatedList(new PageInfo(), [bitstream1, bitstream2]);
|
||||
const bitstreamList2: PaginatedList<Bitstream> = buildPaginatedList(new PageInfo(), [bitstream3, bitstream4]);
|
||||
|
||||
const item = Object.assign(new Item(), {
|
||||
uuid: 'item',
|
||||
@@ -142,13 +141,12 @@ describe('ItemAuthorizationsComponent test suite', () => {
|
||||
expect(compAsAny.bundleBitstreamsMap.has('bundle1')).toBeTruthy();
|
||||
expect(compAsAny.bundleBitstreamsMap.has('bundle2')).toBeTruthy();
|
||||
let bitstreamList = compAsAny.bundleBitstreamsMap.get('bundle1');
|
||||
expect(bitstreamList).toBeObservable(cold('(a|)', {
|
||||
a: bitstreamList1
|
||||
expect(bitstreamList.bitstreams).toBeObservable(cold('(a|)', {
|
||||
a : [bitstream1, bitstream2]
|
||||
}));
|
||||
|
||||
bitstreamList = compAsAny.bundleBitstreamsMap.get('bundle2');
|
||||
expect(bitstreamList).toBeObservable(cold('(a|)', {
|
||||
a: bitstreamList2
|
||||
expect(bitstreamList.bitstreams).toBeObservable(cold('(a|)', {
|
||||
a: [bitstream3, bitstream4]
|
||||
}));
|
||||
});
|
||||
|
||||
|
@@ -1,3 +1,5 @@
|
||||
import { isEqual } from 'lodash';
|
||||
import { DSONameService } from '../../../core/breadcrumbs/dso-name.service';
|
||||
import { Component, OnDestroy, OnInit } from '@angular/core';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
|
||||
@@ -6,7 +8,8 @@ import { catchError, filter, first, map, mergeMap, take } from 'rxjs/operators';
|
||||
|
||||
import { buildPaginatedList, PaginatedList } from '../../../core/data/paginated-list.model';
|
||||
import {
|
||||
getFirstSucceededRemoteDataPayload, getFirstSucceededRemoteDataWithNotEmptyPayload,
|
||||
getFirstSucceededRemoteDataPayload,
|
||||
getFirstSucceededRemoteDataWithNotEmptyPayload,
|
||||
} from '../../../core/shared/operators';
|
||||
import { Item } from '../../../core/shared/item.model';
|
||||
import { followLink } from '../../../shared/utils/follow-link-config.model';
|
||||
@@ -25,7 +28,8 @@ interface BundleBitstreamsMapEntry {
|
||||
|
||||
@Component({
|
||||
selector: 'ds-item-authorizations',
|
||||
templateUrl: './item-authorizations.component.html'
|
||||
templateUrl: './item-authorizations.component.html',
|
||||
styleUrls:['./item-authorizations.component.scss']
|
||||
})
|
||||
/**
|
||||
* Component that handles the item Authorizations
|
||||
@@ -36,13 +40,13 @@ export class ItemAuthorizationsComponent implements OnInit, OnDestroy {
|
||||
* A map that contains all bitstream of the item's bundles
|
||||
* @type {Observable<Map<string, Observable<PaginatedList<Bitstream>>>>}
|
||||
*/
|
||||
public bundleBitstreamsMap: Map<string, Observable<PaginatedList<Bitstream>>> = new Map<string, Observable<PaginatedList<Bitstream>>>();
|
||||
public bundleBitstreamsMap: Map<string, BitstreamMapValue> = new Map<string, BitstreamMapValue>();
|
||||
|
||||
/**
|
||||
* The list of bundle for the item
|
||||
* The list of all bundles for the item
|
||||
* @type {Observable<PaginatedList<Bundle>>}
|
||||
*/
|
||||
private bundles$: BehaviorSubject<Bundle[]> = new BehaviorSubject<Bundle[]>([]);
|
||||
bundles$: BehaviorSubject<Bundle[]> = new BehaviorSubject<Bundle[]>([]);
|
||||
|
||||
/**
|
||||
* The target editing item
|
||||
@@ -56,15 +60,48 @@ export class ItemAuthorizationsComponent implements OnInit, OnDestroy {
|
||||
*/
|
||||
private subs: Subscription[] = [];
|
||||
|
||||
/**
|
||||
* The size of the bundles to be loaded on demand
|
||||
* @type {number}
|
||||
*/
|
||||
bundlesPerPage = 6;
|
||||
|
||||
/**
|
||||
* The number of current page
|
||||
* @type {number}
|
||||
*/
|
||||
bundlesPageSize = 1;
|
||||
|
||||
/**
|
||||
* The flag to show or not the 'Load more' button
|
||||
* based on the condition if all the bundles are loaded or not
|
||||
* @type {boolean}
|
||||
*/
|
||||
allBundlesLoaded = false;
|
||||
|
||||
/**
|
||||
* Initial size of loaded bitstreams
|
||||
* The size of incrementation used in bitstream pagination
|
||||
*/
|
||||
bitstreamSize = 4;
|
||||
|
||||
/**
|
||||
* The size of the loaded bitstremas at a certain moment
|
||||
* @private
|
||||
*/
|
||||
private bitstreamPageSize = 4;
|
||||
|
||||
/**
|
||||
* Initialize instance variables
|
||||
*
|
||||
* @param {LinkService} linkService
|
||||
* @param {ActivatedRoute} route
|
||||
* @param nameService
|
||||
*/
|
||||
constructor(
|
||||
private linkService: LinkService,
|
||||
private route: ActivatedRoute
|
||||
private route: ActivatedRoute,
|
||||
private nameService: DSONameService
|
||||
) {
|
||||
}
|
||||
|
||||
@@ -72,12 +109,49 @@ export class ItemAuthorizationsComponent implements OnInit, OnDestroy {
|
||||
* Initialize the component, setting up the bundle and bitstream within the item
|
||||
*/
|
||||
ngOnInit(): void {
|
||||
this.getBundlesPerItem();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the item's UUID
|
||||
*/
|
||||
getItemUUID(): Observable<string> {
|
||||
return this.item$.pipe(
|
||||
map((item: Item) => item.id),
|
||||
first((UUID: string) => isNotEmpty(UUID))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the item's name
|
||||
*/
|
||||
getItemName(): Observable<string> {
|
||||
return this.item$.pipe(
|
||||
map((item: Item) => this.nameService.getName(item))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all item's bundles
|
||||
*
|
||||
* @return an observable that emits all item's bundles
|
||||
*/
|
||||
getItemBundles(): Observable<Bundle[]> {
|
||||
return this.bundles$.asObservable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all bundles per item
|
||||
* and all the bitstreams per bundle
|
||||
* @param page number of current page
|
||||
*/
|
||||
getBundlesPerItem(page: number = 1) {
|
||||
this.item$ = this.route.data.pipe(
|
||||
map((data) => data.dso),
|
||||
getFirstSucceededRemoteDataWithNotEmptyPayload(),
|
||||
map((item: Item) => this.linkService.resolveLink(
|
||||
item,
|
||||
followLink('bundles', {}, followLink('bitstreams'))
|
||||
followLink('bundles', {findListOptions: {currentPage : page, elementsPerPage: this.bundlesPerPage}}, followLink('bitstreams'))
|
||||
))
|
||||
) as Observable<Item>;
|
||||
|
||||
@@ -96,37 +170,36 @@ export class ItemAuthorizationsComponent implements OnInit, OnDestroy {
|
||||
take(1),
|
||||
map((list: PaginatedList<Bundle>) => list.page)
|
||||
).subscribe((bundles: Bundle[]) => {
|
||||
if (isEqual(bundles.length,0) || bundles.length < this.bundlesPerPage) {
|
||||
this.allBundlesLoaded = true;
|
||||
}
|
||||
if (isEqual(page, 1)) {
|
||||
this.bundles$.next(bundles);
|
||||
} else {
|
||||
this.bundles$.next(this.bundles$.getValue().concat(bundles));
|
||||
}
|
||||
}),
|
||||
bundles$.pipe(
|
||||
take(1),
|
||||
mergeMap((list: PaginatedList<Bundle>) => list.page),
|
||||
map((bundle: Bundle) => ({ id: bundle.id, bitstreams: this.getBundleBitstreams(bundle) }))
|
||||
).subscribe((entry: BundleBitstreamsMapEntry) => {
|
||||
this.bundleBitstreamsMap.set(entry.id, entry.bitstreams);
|
||||
let bitstreamMapValues: BitstreamMapValue = {
|
||||
isCollapsed: true,
|
||||
allBitstreamsLoaded: false,
|
||||
bitstreams: null
|
||||
};
|
||||
bitstreamMapValues.bitstreams = entry.bitstreams.pipe(
|
||||
map((b: PaginatedList<Bitstream>) => {
|
||||
bitstreamMapValues.allBitstreamsLoaded = b?.page.length < this.bitstreamSize;
|
||||
return [...b.page.slice(0, this.bitstreamSize)];
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the item's UUID
|
||||
*/
|
||||
getItemUUID(): Observable<string> {
|
||||
return this.item$.pipe(
|
||||
map((item: Item) => item.id),
|
||||
first((UUID: string) => isNotEmpty(UUID))
|
||||
this.bundleBitstreamsMap.set(entry.id, bitstreamMapValues);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all item's bundles
|
||||
*
|
||||
* @return an observable that emits all item's bundles
|
||||
*/
|
||||
getItemBundles(): Observable<Bundle[]> {
|
||||
return this.bundles$.asObservable();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return all bundle's bitstreams
|
||||
*
|
||||
@@ -142,6 +215,46 @@ export class ItemAuthorizationsComponent implements OnInit, OnDestroy {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Changes the collapsible state of the area that contains the bitstream list
|
||||
* @param bundleId Id of bundle responsible for the requested bitstreams
|
||||
*/
|
||||
collapseArea(bundleId: string) {
|
||||
this.bundleBitstreamsMap.get(bundleId).isCollapsed = !this.bundleBitstreamsMap.get(bundleId).isCollapsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads as much bundles as initial value of bundleSize to be displayed
|
||||
*/
|
||||
onBundleLoad(){
|
||||
this.bundlesPageSize ++;
|
||||
this.getBundlesPerItem(this.bundlesPageSize);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the bitstreams that are going to be loaded on demand,
|
||||
* based on the number configured on this.bitstreamSize.
|
||||
* @param bundle parent of bitstreams that are requested to be shown
|
||||
* @returns Subscription
|
||||
*/
|
||||
onBitstreamsLoad(bundle: Bundle) {
|
||||
return this.getBundleBitstreams(bundle).subscribe((res: PaginatedList<Bitstream>) => {
|
||||
let nextBitstreams = res?.page.slice(this.bitstreamPageSize, this.bitstreamPageSize + this.bitstreamSize);
|
||||
let bitstreamsToShow = this.bundleBitstreamsMap.get(bundle.id).bitstreams.pipe(
|
||||
map((existingBits: Bitstream[])=> {
|
||||
return [... existingBits, ...nextBitstreams];
|
||||
})
|
||||
);
|
||||
this.bitstreamPageSize = this.bitstreamPageSize + this.bitstreamSize;
|
||||
let bitstreamMapValues: BitstreamMapValue = {
|
||||
bitstreams: bitstreamsToShow ,
|
||||
isCollapsed: this.bundleBitstreamsMap.get(bundle.id).isCollapsed,
|
||||
allBitstreamsLoaded: res?.page.length <= this.bitstreamPageSize
|
||||
};
|
||||
this.bundleBitstreamsMap.set(bundle.id, bitstreamMapValues);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsubscribe from all subscriptions
|
||||
*/
|
||||
@@ -151,3 +264,9 @@ export class ItemAuthorizationsComponent implements OnInit, OnDestroy {
|
||||
.forEach((subscription) => subscription.unsubscribe());
|
||||
}
|
||||
}
|
||||
|
||||
export interface BitstreamMapValue {
|
||||
bitstreams: Observable<Bitstream[]>;
|
||||
isCollapsed: boolean;
|
||||
allBitstreamsLoaded: boolean;
|
||||
}
|
||||
|
@@ -147,7 +147,6 @@ export class ItemBitstreamsComponent extends AbstractItemUpdateComponent impleme
|
||||
// Perform the setup actions from above in order and display notifications
|
||||
removedResponses$.pipe(take(1)).subscribe((responses: RemoteData<NoContent>[]) => {
|
||||
this.displayNotifications('item.edit.bitstreams.notifications.remove', responses);
|
||||
this.reset();
|
||||
this.submitting = false;
|
||||
});
|
||||
}
|
||||
@@ -242,27 +241,6 @@ export class ItemBitstreamsComponent extends AbstractItemUpdateComponent impleme
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* De-cache the current item (it should automatically reload due to itemUpdateSubscription)
|
||||
*/
|
||||
reset() {
|
||||
this.refreshItemCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove the current item's cache from object- and request-cache
|
||||
*/
|
||||
refreshItemCache() {
|
||||
this.bundles$.pipe(take(1)).subscribe((bundles: Bundle[]) => {
|
||||
bundles.forEach((bundle: Bundle) => {
|
||||
this.objectCache.remove(bundle.self);
|
||||
this.requestService.removeByHrefSubstring(bundle.self);
|
||||
});
|
||||
this.objectCache.remove(this.item.self);
|
||||
this.requestService.removeByHrefSubstring(this.item.self);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Unsubscribe from open subscriptions whenever the component gets destroyed
|
||||
*/
|
||||
|
@@ -1,15 +1,14 @@
|
||||
import { map } from 'rxjs/operators';
|
||||
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
|
||||
import { Observable } from 'rxjs';
|
||||
import { map } from 'rxjs/operators';
|
||||
|
||||
import { ItemDataService } from '../../core/data/item-data.service';
|
||||
import { RemoteData } from '../../core/data/remote-data';
|
||||
|
||||
import { Item } from '../../core/shared/item.model';
|
||||
|
||||
import { fadeInOut } from '../../shared/animations/fade';
|
||||
import { getAllSucceededRemoteDataPayload} from '../../core/shared/operators';
|
||||
import { getAllSucceededRemoteDataPayload } from '../../core/shared/operators';
|
||||
import { ViewMode } from '../../core/shared/view-mode.model';
|
||||
import { AuthService } from '../../core/auth/auth.service';
|
||||
import { getItemPageRoute } from '../item-page-routing-paths';
|
||||
@@ -56,13 +55,16 @@ export class ItemPageComponent implements OnInit {
|
||||
*/
|
||||
isAdmin$: Observable<boolean>;
|
||||
|
||||
itemUrl: string;
|
||||
|
||||
constructor(
|
||||
protected route: ActivatedRoute,
|
||||
private router: Router,
|
||||
private items: ItemDataService,
|
||||
private authService: AuthService,
|
||||
private authorizationService: AuthorizationDataService
|
||||
) { }
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize instance variables
|
||||
@@ -78,5 +80,6 @@ export class ItemPageComponent implements OnInit {
|
||||
);
|
||||
|
||||
this.isAdmin$ = this.authorizationService.isAuthorized(FeatureID.AdministratorOf);
|
||||
|
||||
}
|
||||
}
|
||||
|
@@ -4,7 +4,7 @@ import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
|
||||
import { By } from '@angular/platform-browser';
|
||||
import { Store } from '@ngrx/store';
|
||||
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
|
||||
import { Observable } from 'rxjs';
|
||||
import {Observable, of as observableOf} from 'rxjs';
|
||||
import { RemoteDataBuildService } from '../../../../core/cache/builders/remote-data-build.service';
|
||||
import { ObjectCacheService } from '../../../../core/cache/object-cache.service';
|
||||
import { BitstreamDataService } from '../../../../core/data/bitstream-data.service';
|
||||
@@ -32,6 +32,8 @@ import { ItemComponent } from './item.component';
|
||||
import { createPaginatedList } from '../../../../shared/testing/utils.test';
|
||||
import { RouteService } from '../../../../core/services/route.service';
|
||||
import { MetadataValue } from '../../../../core/shared/metadata.models';
|
||||
import {AuthorizationDataService} from '../../../../core/data/feature-authorization/authorization-data.service';
|
||||
import {ResearcherProfileService} from '../../../../core/profile/researcher-profile.service';
|
||||
|
||||
export const iiifEnabled = Object.assign(new MetadataValue(),{
|
||||
'value': 'true',
|
||||
@@ -69,6 +71,11 @@ export function getItemPageFieldsTest(mockItem: Item, component) {
|
||||
return createSuccessfulRemoteDataObject$(new Bitstream());
|
||||
}
|
||||
};
|
||||
|
||||
const authorizationService = jasmine.createSpyObj('authorizationService', {
|
||||
isAuthorized: observableOf(true)
|
||||
});
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
imports: [TranslateModule.forRoot({
|
||||
loader: {
|
||||
@@ -92,7 +99,9 @@ export function getItemPageFieldsTest(mockItem: Item, component) {
|
||||
{ provide: NotificationsService, useValue: {} },
|
||||
{ provide: DefaultChangeAnalyzer, useValue: {} },
|
||||
{ provide: BitstreamDataService, useValue: mockBitstreamDataService },
|
||||
{ provide: RouteService, useValue: {} }
|
||||
{ provide: RouteService, useValue: {} },
|
||||
{ provide: AuthorizationDataService, useValue: authorizationService },
|
||||
{ provide: ResearcherProfileService, useValue: {} }
|
||||
],
|
||||
|
||||
schemas: [NO_ERRORS_SCHEMA]
|
||||
|
@@ -2,7 +2,7 @@ import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { VersionedItemComponent } from './versioned-item.component';
|
||||
import { VersionHistoryDataService } from '../../../../core/data/version-history-data.service';
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
|
||||
import { VersionDataService } from '../../../../core/data/version-data.service';
|
||||
import { NotificationsService } from '../../../../shared/notifications/notifications.service';
|
||||
import { ItemVersionsSharedService } from '../../../../shared/item/item-versions/item-versions-shared.service';
|
||||
@@ -19,6 +19,7 @@ import { SearchService } from '../../../../core/shared/search/search.service';
|
||||
import { ItemDataService } from '../../../../core/data/item-data.service';
|
||||
import { Version } from '../../../../core/shared/version.model';
|
||||
import { RouteService } from '../../../../core/services/route.service';
|
||||
import { TranslateLoaderMock } from '../../../../shared/testing/translate-loader.mock';
|
||||
|
||||
const mockItem: Item = Object.assign(new Item(), {
|
||||
bundles: createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), [])),
|
||||
@@ -57,10 +58,17 @@ describe('VersionedItemComponent', () => {
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
declarations: [VersionedItemComponent, DummyComponent],
|
||||
imports: [RouterTestingModule],
|
||||
imports: [
|
||||
RouterTestingModule,
|
||||
TranslateModule.forRoot({
|
||||
loader: {
|
||||
provide: TranslateLoader,
|
||||
useClass: TranslateLoaderMock,
|
||||
}
|
||||
}),
|
||||
],
|
||||
providers: [
|
||||
{ provide: VersionHistoryDataService, useValue: versionHistoryServiceSpy },
|
||||
{ provide: TranslateService, useValue: {} },
|
||||
{ provide: VersionDataService, useValue: versionServiceSpy },
|
||||
{ provide: NotificationsService, useValue: {} },
|
||||
{ provide: ItemVersionsSharedService, useValue: {} },
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user