Merge remote-tracking branch 'origin/main' into CST-5668

# Conflicts:
#	src/app/core/core.module.ts
#	src/app/core/profile/researcher-profile.service.ts
#	src/app/item-page/simple/item-page.component.ts
#	src/app/profile-page/profile-page.component.spec.ts
#	src/app/profile-page/profile-page.component.ts
#	src/app/shared/shared.module.ts
This commit is contained in:
Giuseppe Digilio
2022-06-09 17:39:43 +02:00
108 changed files with 4417 additions and 714 deletions

View File

@@ -47,7 +47,6 @@
],
"styles": [
"src/styles/startup.scss",
"./node_modules/ngx-ui-switch/ui-switch.component.css",
{
"input": "src/styles/base-theme.scss",
"inject": false,

View File

@@ -80,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",

View File

@@ -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';
/*
@@ -174,6 +175,11 @@ export function app() {
*/
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
router.get('*', ngApp);
@@ -319,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.

View File

@@ -124,3 +124,5 @@ export const REQUEST_COPY_MODULE_PATH = 'request-a-copy';
export function getRequestCopyModulePath() {
return `/${REQUEST_COPY_MODULE_PATH}`;
}
export const HEALTH_PAGE_PATH = 'health';

View File

@@ -3,7 +3,9 @@ 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,
@@ -11,6 +13,7 @@ import {
ERROR_PAGE,
FORBIDDEN_PATH,
FORGOT_PASSWORD_PATH,
HEALTH_PAGE_PATH,
INFO_MODULE_PATH,
INTERNAL_SERVER_ERROR,
LEGACY_BITSTREAM_MODULE_PATH,
@@ -28,8 +31,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';
import { ThemedPageErrorComponent } from './page-error/themed-page-error.component';
@@ -213,6 +220,11 @@ import { ThemedPageErrorComponent } from './page-error/themed-page-error.compone
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),

View File

@@ -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'])

View File

@@ -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');
});
});
});

View File

@@ -132,11 +132,15 @@ import { Feature } from './shared/feature.model';
import { Authorization } from './shared/authorization.model';
import { FeatureDataService } from './data/feature-authorization/feature-data.service';
import { AuthorizationDataService } from './data/feature-authorization/authorization-data.service';
import { SiteAdministratorGuard } from './data/feature-authorization/feature-authorization-guard/site-administrator.guard';
import {
SiteAdministratorGuard
} from './data/feature-authorization/feature-authorization-guard/site-administrator.guard';
import { Registration } from './shared/registration.model';
import { MetadataSchemaDataService } from './data/metadata-schema-data.service';
import { MetadataFieldDataService } from './data/metadata-field-data.service';
import { DsDynamicTypeBindRelationService } from '../shared/form/builder/ds-dynamic-form-ui/ds-dynamic-type-bind-relation.service';
import {
DsDynamicTypeBindRelationService
} from '../shared/form/builder/ds-dynamic-form-ui/ds-dynamic-type-bind-relation.service';
import { TokenResponseParsingService } from './auth/token-response-parsing.service';
import { SubmissionCcLicenseDataService } from './submission/submission-cc-license-data.service';
import { SubmissionCcLicence } from './submission/models/submission-cc-license.model';
@@ -163,12 +167,12 @@ import { SequenceService } from './shared/sequence.service';
import { CoreState } from './core-state.model';
import { GroupDataService } from './eperson/group-data.service';
import { SubmissionAccessesModel } from './config/models/config-submission-accesses.model';
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';
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
@@ -357,8 +361,8 @@ export const models =
Root,
SearchConfig,
SubmissionAccessesModel,
ResearcherProfile,
AccessStatusObject
AccessStatusObject,
ResearcherProfile
];
@NgModule({

View File

@@ -8,11 +8,12 @@ import {
find,
map,
mergeMap,
skipWhile,
switchMap,
take,
takeWhile,
switchMap,
tap,
skipWhile, toArray
toArray
} from 'rxjs/operators';
import { hasValue, isNotEmpty, isNotEmptyOperator } from '../../shared/empty.util';
import { NotificationOptions } from '../../shared/notifications/models/notification-options.model';
@@ -26,18 +27,12 @@ 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, getFirstCompletedRemoteData } 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';
@@ -169,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)) {

View File

@@ -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)) {

View File

@@ -1,10 +1,15 @@
import { Observable } from 'rxjs';
import { autoserialize, deserialize, deserializeAs } from 'cerialize';
import { typedObject } from '../../cache/builders/build-decorators';
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.
@@ -46,4 +51,11 @@ export class ResearcherProfile extends CacheableObject {
eperson: HALLink
};
/**
* The related person Item
* Will be undefined unless the item {@link HALLink} has been resolved.
*/
@link(ITEM)
item?: Observable<RemoteData<Item>>;
}

View 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'));
});
});
});

View File

@@ -2,10 +2,12 @@
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { Operation, RemoveOperation, ReplaceOperation } from 'fast-json-patch';
import { combineLatest, Observable, of as observableOf } from 'rxjs';
import { catchError, find, map, switchMap, tap } from 'rxjs/operators';
import { RemoveOperation, ReplaceOperation } from 'fast-json-patch';
import { combineLatest, Observable } from 'rxjs';
import { find, map, switchMap } from 'rxjs/operators';
import { environment } from '../../../environments/environment';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { dataService } from '../cache/builders/build-decorators';
@@ -19,9 +21,9 @@ import { RemoteData } from '../data/remote-data';
import { RequestService } from '../data/request.service';
import { ConfigurationProperty } from '../shared/configuration-property.model';
import { HALEndpointService } from '../shared/hal-endpoint.service';
import { Item } from '../shared/item.model';
import { NoContent } from '../shared/NoContent.model';
import {
getAllCompletedRemoteData,
getFinishedRemoteData,
getFirstCompletedRemoteData,
getFirstSucceededRemoteDataPayload
@@ -32,6 +34,8 @@ 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.
@@ -67,7 +71,6 @@ export class ResearcherProfileService {
constructor(
protected requestService: RequestService,
protected rdbService: RemoteDataBuildService,
protected store: Store<CoreState>,
protected objectCache: ObjectCacheService,
protected halService: HALEndpointService,
protected notificationsService: NotificationsService,
@@ -77,7 +80,7 @@ export class ResearcherProfileService {
protected itemService: ItemDataService,
protected configurationService: ConfigurationDataService) {
this.dataService = new ResearcherProfileServiceImpl(requestService, rdbService, store, objectCache, halService,
this.dataService = new ResearcherProfileServiceImpl(requestService, rdbService, null, objectCache, halService,
notificationsService, http, comparator);
}
@@ -86,17 +89,23 @@ export class ResearcherProfileService {
* 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
*/
findById(uuid: string): Observable<ResearcherProfile> {
return this.dataService.findById(uuid, false)
.pipe ( getFinishedRemoteData(),
map((remoteData) => remoteData.payload));
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.
*/
create(): Observable<RemoteData<ResearcherProfile>> {
public create(): Observable<RemoteData<ResearcherProfile>> {
return this.dataService.create(new ResearcherProfile());
}
@@ -105,14 +114,9 @@ export class ResearcherProfileService {
*
* @param researcherProfile the profile to delete
*/
delete(researcherProfile: ResearcherProfile): Observable<boolean> {
public delete(researcherProfile: ResearcherProfile): Observable<boolean> {
return this.dataService.delete(researcherProfile.id).pipe(
getFirstCompletedRemoteData(),
tap((response: RemoteData<NoContent>) => {
if (response.isSuccess) {
this.requestService.setStaleByHrefSubstring(researcherProfile._links.self.href);
}
}),
map((response: RemoteData<NoContent>) => response.isSuccess)
);
}
@@ -122,14 +126,12 @@ export class ResearcherProfileService {
*
* @param researcherProfile the profile to find for
*/
findRelatedItemId( researcherProfile: ResearcherProfile ): Observable<string> {
return this.itemService.findByHref(researcherProfile._links.item.href, false)
.pipe (getFirstSucceededRemoteDataPayload(),
catchError((error) => {
console.debug(error);
return observableOf(null);
}),
map((item) => item != null ? item.id : null ));
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)
);
}
/**
@@ -138,21 +140,14 @@ export class ResearcherProfileService {
* @param researcherProfile the profile to update
* @param visible the visibility value to set
*/
setVisibility(researcherProfile: ResearcherProfile, visible: boolean): Observable<ResearcherProfile> {
public setVisibility(researcherProfile: ResearcherProfile, visible: boolean): Observable<RemoteData<ResearcherProfile>> {
const replaceOperation: ReplaceOperation<boolean> = {
path: '/visible',
op: 'replace',
value: visible
};
return this.patch(researcherProfile, [replaceOperation]).pipe (
switchMap( ( ) => this.findById(researcherProfile.id))
);
}
patch(researcherProfile: ResearcherProfile, operations: Operation[]): Observable<RemoteData<ResearcherProfile>> {
return this.dataService.patch(researcherProfile, operations);
return this.dataService.patch(researcherProfile, [replaceOperation]);
}
/**
@@ -215,7 +210,8 @@ export class ResearcherProfileService {
}];
return this.findById(item.firstMetadata('dspace.object.owner').authority).pipe(
switchMap((profile) => this.patch(profile, operations)),
getFirstCompletedRemoteData(),
switchMap((profileRD) => this.dataService.patch(profileRD.payload, operations)),
getFinishedRemoteData()
);
}
@@ -248,13 +244,13 @@ export class ResearcherProfileService {
href$.pipe(
find((href: string) => hasValue(href)),
map((href: string) => {
const request = new PostRequest(requestId, href, sourceUri, options);
map((href: string) => this.dataService.buildHrefWithParams(href, [], followLink('item')))
).subscribe((endpoint: string) => {
const request = new PostRequest(requestId, endpoint, sourceUri, options);
this.requestService.send(request);
})
).subscribe();
});
return this.rdbService.buildFromRequestUUID(requestId);
return this.rdbService.buildFromRequestUUID(requestId, followLink('item'));
}
private getOrcidDisconnectionAllowedUsersConfiguration(): Observable<ConfigurationProperty> {

View File

@@ -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;
}

View File

@@ -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;
}

View File

@@ -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;

View File

@@ -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"

View File

@@ -1,10 +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';
import {isNotEmpty} from '../../../../../shared/empty.util';
@listableObjectComponent('PersonSearchResult', ViewMode.ListElement)
@Component({
@@ -21,11 +24,10 @@ export class PersonSearchResultListElementComponent extends ItemSearchResultList
super(truncatableService, dsoNameService);
}
/**
* Return the person name
*/
get name() {
let personName = this.dsoNameService.getName(this.dso);
if (isNotEmpty(this.firstMetadataValue('person.familyName')) && isNotEmpty(this.firstMetadataValue('person.givenName'))) {
personName = this.firstMetadataValue('person.familyName') + ', ' + this.firstMetadataValue('person.givenName');
}
return personName;
return this.dsoNameService.getName(this.dso);
}
}

View File

@@ -5,7 +5,7 @@
<div class="pl-2">
<ds-dso-page-orcid-button [pageRoute]="itemPageRoute" [dso]="object" class="mr-2"></ds-dso-page-orcid-button>
<ds-dso-page-edit-button [pageRoute]="itemPageRoute" [dso]="object" [tooltipMsg]="'person.page.edit'"></ds-dso-page-edit-button>
<button class="edit-button btn btn-dark btn-sm" *ngIf="(isClaimable() | async)" (click)="claim()"> {{"item.page.claim.button" | translate }} </button>
<ds-person-page-claim-button [object]="object"></ds-person-page-claim-button>
</div>
</div>
<div class="row">
@@ -21,18 +21,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
@@ -57,6 +49,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}}

View File

@@ -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',
@@ -62,4 +50,42 @@ const mockItem: Item = Object.assign(new Item(), {
}
});
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));

View File

@@ -1,20 +1,10 @@
import {Component, OnInit} from '@angular/core';
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';
import {FeatureID} from '../../../../core/data/feature-authorization/feature-id';
import {mergeMap, take} from 'rxjs/operators';
import {getFirstSucceededRemoteData} from '../../../../core/shared/operators';
import {RemoteData} from '../../../../core/data/remote-data';
import {ResearcherProfile} from '../../../../core/profile/model/researcher-profile.model';
import {isNotUndefined} from '../../../../shared/empty.util';
import {BehaviorSubject, Observable} from 'rxjs';
import {RouteService} from '../../../../core/services/route.service';
import {AuthorizationDataService} from '../../../../core/data/feature-authorization/authorization-data.service';
import {ResearcherProfileService} from '../../../../core/profile/researcher-profile.service';
import {NotificationsService} from '../../../../shared/notifications/notifications.service';
import {TranslateService} from '@ngx-translate/core';
@listableObjectComponent('Person', ViewMode.StandalonePage)
@Component({
@@ -25,57 +15,7 @@ import {TranslateService} from '@ngx-translate/core';
/**
* The component for displaying metadata and relations of an item of the type Person
*/
export class PersonComponent extends ItemComponent implements OnInit {
claimable$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
constructor(protected routeService: RouteService,
protected authorizationService: AuthorizationDataService,
protected notificationsService: NotificationsService,
protected translate: TranslateService,
protected researcherProfileService: ResearcherProfileService) {
super(routeService);
}
ngOnInit(): void {
super.ngOnInit();
this.authorizationService.isAuthorized(FeatureID.CanClaimItem, this.object._links.self.href).pipe(
take(1)
).subscribe((isAuthorized: boolean) => {
this.claimable$.next(isAuthorized);
});
}
/**
* Create a new researcher profile claiming the current item.
*/
claim() {
this.researcherProfileService.createFromExternalSource(this.object._links.self.href).pipe(
getFirstSucceededRemoteData(),
mergeMap((rd: RemoteData<ResearcherProfile>) => {
return this.researcherProfileService.findRelatedItemId(rd.payload);
}))
.subscribe((id: string) => {
if (isNotUndefined(id)) {
this.notificationsService.success(this.translate.get('researcherprofile.success.claim.title'),
this.translate.get('researcherprofile.success.claim.body'));
this.claimable$.next(false);
} else {
this.notificationsService.error(
this.translate.get('researcherprofile.error.claim.title'),
this.translate.get('researcherprofile.error.claim.body'));
}
});
}
/**
* Returns true if the item is claimable, false otherwise.
*/
isClaimable(): Observable<boolean> {
return this.claimable$;
}
export class PersonComponent extends ItemComponent {
/**
* Returns the metadata values to be used for the page title.
@@ -96,5 +36,4 @@ export class PersonComponent extends ItemComponent implements OnInit {
}
return metadataValues;
}
}

View File

@@ -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>

View File

@@ -0,0 +1,3 @@
.collapse-toggle {
cursor: pointer;
}

View File

@@ -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);
});
});
});

View File

@@ -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';
}
}

View 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>

View File

@@ -0,0 +1,3 @@
.collapse-toggle {
cursor: pointer;
}

View File

@@ -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);
});
});

View 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;
}
}

View 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>

View 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);
});
});

View 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);
}
});
}
}

View 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 {
}

View 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 {
}

View File

@@ -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>

View File

@@ -0,0 +1,3 @@
.collapse-toggle {
cursor: pointer;
}

View File

@@ -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);
});
});
});

View File

@@ -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;
}
}

View 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>

View File

@@ -0,0 +1,3 @@
.collapse-toggle {
cursor: pointer;
}

View File

@@ -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);
});
});

View 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;
}
}

View File

@@ -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>

View File

@@ -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();
});
});

View File

@@ -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;
}

View 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)));
}
}

View 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;
}

View File

@@ -1,13 +1,12 @@
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 { ViewMode } from '../../core/shared/view-mode.model';
@@ -17,7 +16,6 @@ import { redirectOn4xx } from '../../core/shared/authorized.operators';
import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service';
import { FeatureID } from '../../core/data/feature-authorization/feature-id';
/**
* This component renders a simple item page.
* The route parameter 'id' is used to request the item it represents.

View File

@@ -15,18 +15,34 @@ import { MenuService } from './shared/menu/menu.service';
import { filter, find, map, take } from 'rxjs/operators';
import { hasValue } from './shared/empty.util';
import { FeatureID } from './core/data/feature-authorization/feature-id';
import { CreateCommunityParentSelectorComponent } from './shared/dso-selector/modal-wrappers/create-community-parent-selector/create-community-parent-selector.component';
import {
CreateCommunityParentSelectorComponent
} from './shared/dso-selector/modal-wrappers/create-community-parent-selector/create-community-parent-selector.component';
import { OnClickMenuItemModel } from './shared/menu/menu-item/models/onclick.model';
import { CreateCollectionParentSelectorComponent } from './shared/dso-selector/modal-wrappers/create-collection-parent-selector/create-collection-parent-selector.component';
import { CreateItemParentSelectorComponent } from './shared/dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component';
import { EditCommunitySelectorComponent } from './shared/dso-selector/modal-wrappers/edit-community-selector/edit-community-selector.component';
import { EditCollectionSelectorComponent } from './shared/dso-selector/modal-wrappers/edit-collection-selector/edit-collection-selector.component';
import { EditItemSelectorComponent } from './shared/dso-selector/modal-wrappers/edit-item-selector/edit-item-selector.component';
import { ExportMetadataSelectorComponent } from './shared/dso-selector/modal-wrappers/export-metadata-selector/export-metadata-selector.component';
import {
CreateCollectionParentSelectorComponent
} from './shared/dso-selector/modal-wrappers/create-collection-parent-selector/create-collection-parent-selector.component';
import {
CreateItemParentSelectorComponent
} from './shared/dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component';
import {
EditCommunitySelectorComponent
} from './shared/dso-selector/modal-wrappers/edit-community-selector/edit-community-selector.component';
import {
EditCollectionSelectorComponent
} from './shared/dso-selector/modal-wrappers/edit-collection-selector/edit-collection-selector.component';
import {
EditItemSelectorComponent
} from './shared/dso-selector/modal-wrappers/edit-item-selector/edit-item-selector.component';
import {
ExportMetadataSelectorComponent
} from './shared/dso-selector/modal-wrappers/export-metadata-selector/export-metadata-selector.component';
import { AuthorizationDataService } from './core/data/feature-authorization/authorization-data.service';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import {
METADATA_EXPORT_SCRIPT_NAME, METADATA_IMPORT_SCRIPT_NAME, ScriptDataService
METADATA_EXPORT_SCRIPT_NAME,
METADATA_IMPORT_SCRIPT_NAME,
ScriptDataService
} from './core/data/processes/script-data.service';
/**
@@ -321,6 +337,18 @@ export class MenuResolver implements Resolve<boolean> {
icon: 'terminal',
index: 10
},
{
id: 'health',
active: false,
visible: isSiteAdmin,
model: {
type: MenuItemType.LINK,
text: 'menu.section.health',
link: '/health'
} as LinkMenuItemModel,
icon: 'heartbeat',
index: 11
},
];
menuList.forEach((menuSection) => this.menuService.addSection(MenuID.ADMIN, Object.assign(menuSection, {
shouldPersistOnRouteChange: true

View File

@@ -26,7 +26,7 @@
</div>
<div class="modal-footer">
<div class="mr-5">
<input type="checkbox" [checked]="false" (change)="toggleCheckbox()"/>
<input type="checkbox" [checked]="checked" (change)="toggleCheckbox()"/>
{{ 'dso-selector.claim.item.not-mine-label' | translate }}
</div>
<button type="submit" class="btn btn-primary ml-5 mr-2" (click)="createFromScratch()" [disabled]="!checked">

View File

@@ -0,0 +1,223 @@
import { ActivatedRoute, Router } from '@angular/router';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { By } from '@angular/platform-browser';
import { of } from 'rxjs';
import { TranslateModule } from '@ngx-translate/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { ProfileClaimItemModalComponent } from './profile-claim-item-modal.component';
import { ProfileClaimService } from '../profile-claim/profile-claim.service';
import { Item } from '../../core/shared/item.model';
import { ItemSearchResult } from '../../shared/object-collection/shared/item-search-result.model';
import { SearchObjects } from '../../shared/search/models/search-objects.model';
import { createSuccessfulRemoteDataObject } from '../../shared/remote-data.utils';
import { getItemPageRoute } from '../../item-page/item-page-routing-paths';
import { RouterStub } from '../../shared/testing/router.stub';
describe('ProfileClaimItemModalComponent', () => {
let component: ProfileClaimItemModalComponent;
let fixture: ComponentFixture<ProfileClaimItemModalComponent>;
const item1: Item = Object.assign(new Item(), {
uuid: 'e1c51c69-896d-42dc-8221-1d5f2ad5516e',
metadata: {
'person.email': [
{
value: 'fake@email.com'
}
],
'person.familyName': [
{
value: 'Doe'
}
],
'person.givenName': [
{
value: 'John'
}
]
},
_links: {
self: {
href: 'item-href'
}
}
});
const item2: Item = Object.assign(new Item(), {
uuid: 'c8279647-1acc-41ae-b036-951d5f65649b',
metadata: {
'person.email': [
{
value: 'fake2@email.com'
}
],
'dc.title': [
{
value: 'John, Doe'
}
]
},
_links: {
self: {
href: 'item-href'
}
}
});
const item3: Item = Object.assign(new Item(), {
uuid: 'c8279647-1acc-41ae-b036-951d5f65649b',
metadata: {
'person.email': [
{
value: 'fake3@email.com'
}
],
'dc.title': [
{
value: 'John, Doe'
}
]
},
_links: {
self: {
href: 'item-href'
}
}
});
const searchResult1 = Object.assign(new ItemSearchResult(), { indexableObject: item1 });
const searchResult2 = Object.assign(new ItemSearchResult(), { indexableObject: item2 });
const searchResult3 = Object.assign(new ItemSearchResult(), { indexableObject: item3 });
const searchResult = Object.assign(new SearchObjects(), {
page: [searchResult1, searchResult2, searchResult3]
});
const emptySearchResult = Object.assign(new SearchObjects(), {
page: []
});
const searchResultRD = createSuccessfulRemoteDataObject(searchResult);
const emptySearchResultRD = createSuccessfulRemoteDataObject(emptySearchResult);
const profileClaimService = jasmine.createSpyObj('profileClaimService', {
searchForSuggestions: jasmine.createSpy('searchForSuggestions')
});
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot()],
declarations: [ProfileClaimItemModalComponent],
providers: [
{ provide: NgbActiveModal, useValue: {} },
{ provide: ActivatedRoute, useValue: {} },
{ provide: Router, useValue: new RouterStub() },
{ provide: ProfileClaimService, useValue: profileClaimService }
],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ProfileClaimItemModalComponent);
component = fixture.componentInstance;
});
describe('when there are suggestions', () => {
beforeEach(() => {
profileClaimService.searchForSuggestions.and.returnValue(of(searchResultRD));
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should init the list of suggestions', () => {
const entries = fixture.debugElement.queryAll(By.css('.list-group-item'));
expect(component.listEntries$.value).toEqual(searchResultRD);
expect(entries.length).toBe(3);
});
it('should close modal and call navigate method', () => {
spyOn(component, 'close');
spyOn(component, 'navigate');
component.selectItem(item1);
expect(component.close).toHaveBeenCalled();
expect(component.navigate).toHaveBeenCalledWith(item1);
});
it('should call router navigate method', () => {
const route = [getItemPageRoute(item1)];
component.navigate(item1);
expect((component as any).router.navigate).toHaveBeenCalledWith(route);
});
it('should toggle checkbox', () => {
component.toggleCheckbox();
expect((component as any).checked).toBe(true);
});
it('should emit create event', () => {
spyOn(component, 'close');
spyOn(component.create, 'emit');
component.createFromScratch();
expect(component.create.emit).toHaveBeenCalled();
expect(component.close).toHaveBeenCalled();
});
});
describe('when there are not suggestions', () => {
beforeEach(() => {
profileClaimService.searchForSuggestions.and.returnValue(of(emptySearchResultRD));
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should init the list of suggestions', () => {
const entries = fixture.debugElement.queryAll(By.css('.list-group-item'));
expect(component.listEntries$.value).toEqual(emptySearchResultRD);
expect(entries.length).toBe(0);
});
it('should close modal and call navigate method', () => {
spyOn(component, 'close');
spyOn(component, 'navigate');
component.selectItem(item1);
expect(component.close).toHaveBeenCalled();
expect(component.navigate).toHaveBeenCalledWith(item1);
});
it('should call router navigate method', () => {
const route = [getItemPageRoute(item1)];
component.navigate(item1);
expect((component as any).router.navigate).toHaveBeenCalledWith(route);
});
it('should toggle checkbox', () => {
component.toggleCheckbox();
expect((component as any).checked).toBe(true);
});
it('should emit create event', () => {
spyOn(component, 'close');
spyOn(component.create, 'emit');
component.createFromScratch();
expect(component.create.emit).toHaveBeenCalled();
expect(component.close).toHaveBeenCalled();
});
});
});

View File

@@ -0,0 +1,108 @@
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { BehaviorSubject } from 'rxjs';
import { RemoteData } from '../../core/data/remote-data';
import { Item } from '../../core/shared/item.model';
import {
DSOSelectorModalWrapperComponent
} from '../../shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component';
import { getItemPageRoute } from '../../item-page/item-page-routing-paths';
import { EPerson } from '../../core/eperson/models/eperson.model';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { ViewMode } from '../../core/shared/view-mode.model';
import { ProfileClaimService } from '../profile-claim/profile-claim.service';
import { CollectionElementLinkType } from '../../shared/object-collection/collection-element-link.type';
import { SearchObjects } from '../../shared/search/models/search-objects.model';
import { getFirstCompletedRemoteData } from '../../core/shared/operators';
/**
* Component representing a modal that show a list of suggested profile item to claim
*/
@Component({
selector: 'ds-profile-claim-item-modal',
templateUrl: './profile-claim-item-modal.component.html'
})
export class ProfileClaimItemModalComponent extends DSOSelectorModalWrapperComponent implements OnInit {
/**
* The current page's DSO
*/
@Input() dso: DSpaceObject;
/**
* List of suggested profiles, if any
*/
listEntries$: BehaviorSubject<RemoteData<SearchObjects<DSpaceObject>>> = new BehaviorSubject(null);
/**
* The view mode of the listed objects
*/
viewMode = ViewMode.ListElement;
/**
* The available link types
*/
linkTypes = CollectionElementLinkType;
/**
* A boolean representing form checkbox status
*/
checked = false;
/**
* An event fired when user click on submit button
*/
@Output() create: EventEmitter<any> = new EventEmitter<any>();
constructor(protected activeModal: NgbActiveModal, protected route: ActivatedRoute, private router: Router,
private profileClaimService: ProfileClaimService) {
super(activeModal, route);
}
/**
* Retrieve suggested profiles, if any
*/
ngOnInit(): void {
this.profileClaimService.searchForSuggestions(this.dso as EPerson).pipe(
getFirstCompletedRemoteData(),
).subscribe(
(result: RemoteData<SearchObjects<DSpaceObject>>) => this.listEntries$.next(result)
);
}
/**
* Close modal and Navigate to given DSO
*
* @param dso
*/
selectItem(dso: DSpaceObject): void {
this.close();
this.navigate(dso);
}
/**
* Navigate to given DSO
*
* @param dso
*/
navigate(dso: DSpaceObject) {
this.router.navigate([getItemPageRoute(dso as Item)]);
}
/**
* Change the status of form's checkbox
*/
toggleCheckbox() {
this.checked = !this.checked;
}
/**
* Emit an event when profile should be created from scratch
*/
createFromScratch() {
this.create.emit();
this.close();
}
}

View File

@@ -0,0 +1,215 @@
import { cold, getTestScheduler } from 'jasmine-marbles';
import { of as observableOf } from 'rxjs';
import { TestScheduler } from 'rxjs/testing';
import { ProfileClaimService } from './profile-claim.service';
import { SearchService } from '../../core/shared/search/search.service';
import { ItemSearchResult } from '../../shared/object-collection/shared/item-search-result.model';
import { SearchObjects } from '../../shared/search/models/search-objects.model';
import { Item } from '../../core/shared/item.model';
import { createNoContentRemoteDataObject, createSuccessfulRemoteDataObject } from '../../shared/remote-data.utils';
import { EPerson } from '../../core/eperson/models/eperson.model';
describe('ProfileClaimService', () => {
let scheduler: TestScheduler;
let service: ProfileClaimService;
let serviceAsAny: any;
let searchService: jasmine.SpyObj<SearchService>;
const eperson: EPerson = Object.assign(new EPerson(), {
id: 'id',
metadata: {
'eperson.firstname': [
{
value: 'John'
}
],
'eperson.lastname': [
{
value: 'Doe'
},
],
},
email: 'fake@email.com'
});
const item1: Item = Object.assign(new Item(), {
uuid: 'e1c51c69-896d-42dc-8221-1d5f2ad5516e',
metadata: {
'person.email': [
{
value: 'fake@email.com'
}
],
'person.familyName': [
{
value: 'Doe'
}
],
'person.givenName': [
{
value: 'John'
}
]
},
_links: {
self: {
href: 'item-href'
}
}
});
const item2: Item = Object.assign(new Item(), {
uuid: 'c8279647-1acc-41ae-b036-951d5f65649b',
metadata: {
'person.email': [
{
value: 'fake2@email.com'
}
],
'dc.title': [
{
value: 'John, Doe'
}
]
},
_links: {
self: {
href: 'item-href'
}
}
});
const item3: Item = Object.assign(new Item(), {
uuid: 'c8279647-1acc-41ae-b036-951d5f65649b',
metadata: {
'person.email': [
{
value: 'fake3@email.com'
}
],
'dc.title': [
{
value: 'John, Doe'
}
]
},
_links: {
self: {
href: 'item-href'
}
}
});
const searchResult1 = Object.assign(new ItemSearchResult(), { indexableObject: item1 });
const searchResult2 = Object.assign(new ItemSearchResult(), { indexableObject: item2 });
const searchResult3 = Object.assign(new ItemSearchResult(), { indexableObject: item3 });
const searchResult = Object.assign(new SearchObjects(), {
page: [searchResult1, searchResult2, searchResult3]
});
const emptySearchResult = Object.assign(new SearchObjects(), {
page: []
});
const searchResultRD = createSuccessfulRemoteDataObject(searchResult);
const emptySearchResultRD = createSuccessfulRemoteDataObject(emptySearchResult);
beforeEach(() => {
scheduler = getTestScheduler();
searchService = jasmine.createSpyObj('SearchService', {
search: jasmine.createSpy('search')
});
service = new ProfileClaimService(searchService);
serviceAsAny = service;
});
describe('hasProfilesToSuggest', () => {
describe('when has suggestions', () => {
beforeEach(() => {
spyOn(service, 'searchForSuggestions').and.returnValue(observableOf(searchResultRD));
});
it('should return true', () => {
const result = service.hasProfilesToSuggest(eperson);
const expected = cold('(a|)', {
a: true
});
expect(result).toBeObservable(expected);
});
});
describe('when has not suggestions', () => {
beforeEach(() => {
spyOn(service, 'searchForSuggestions').and.returnValue(observableOf(emptySearchResultRD));
});
it('should return false', () => {
const result = service.hasProfilesToSuggest(eperson);
const expected = cold('(a|)', {
a: false
});
expect(result).toBeObservable(expected);
});
});
describe('when has not valid eperson', () => {
it('should return false', () => {
const result = service.hasProfilesToSuggest(null);
const expected = cold('(a|)', {
a: false
});
expect(result).toBeObservable(expected);
});
});
});
describe('search', () => {
describe('when has search results', () => {
beforeEach(() => {
searchService.search.and.returnValue(observableOf(searchResultRD));
});
it('should return the proper search object', () => {
const result = service.searchForSuggestions(eperson);
const expected = cold('(a|)', {
a: searchResultRD
});
expect(result).toBeObservable(expected);
});
});
describe('when has not suggestions', () => {
beforeEach(() => {
searchService.search.and.returnValue(observableOf(emptySearchResultRD));
});
it('should return null', () => {
const result = service.searchForSuggestions(eperson);
const expected = cold('(a|)', {
a: emptySearchResultRD
});
expect(result).toBeObservable(expected);
});
});
describe('when has not valid eperson', () => {
it('should return null', () => {
const result = service.searchForSuggestions(null);
const expected = cold('(a|)', {
a: createNoContentRemoteDataObject()
});
expect(result).toBeObservable(expected);
});
});
});
});

View File

@@ -1,16 +1,17 @@
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { mergeMap, take } from 'rxjs/operators';
import { ConfigurationDataService } from '../../core/data/configuration-data.service';
import { PaginatedList } from '../../core/data/paginated-list.model';
import { map } from 'rxjs/operators';
import { RemoteData } from '../../core/data/remote-data';
import { EPerson } from '../../core/eperson/models/eperson.model';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { SearchService } from '../../core/shared/search/search.service';
import { hasValue } from '../../shared/empty.util';
import { isEmpty, isNotEmpty } from '../../shared/empty.util';
import { PaginatedSearchOptions } from '../../shared/search/models/paginated-search-options.model';
import { SearchResult } from '../../shared/search/models/search-result.model';
import { getFirstSucceededRemoteData } from './../../core/shared/operators';
import { getFirstCompletedRemoteData } from '../../core/shared/operators';
import { SearchObjects } from '../../shared/search/models/search-objects.model';
import { createNoContentRemoteDataObject } from '../../shared/remote-data.utils';
/**
* Service that handle profiles claim.
@@ -18,8 +19,7 @@ import { getFirstSucceededRemoteData } from './../../core/shared/operators';
@Injectable()
export class ProfileClaimService {
constructor(private searchService: SearchService,
private configurationService: ConfigurationDataService) {
constructor(private searchService: SearchService) {
}
/**
@@ -27,51 +27,54 @@ export class ProfileClaimService {
*
* @param eperson the eperson
*/
canClaimProfiles(eperson: EPerson): Observable<boolean> {
const query = this.personQueryData(eperson);
if (!hasValue(query) || query.length === 0) {
return of(false);
}
return this.lookup(query).pipe(
mergeMap((rd: RemoteData<PaginatedList<SearchResult<DSpaceObject>>>) => of(rd.payload.totalElements > 0))
hasProfilesToSuggest(eperson: EPerson): Observable<boolean> {
return this.searchForSuggestions(eperson).pipe(
getFirstCompletedRemoteData(),
map((rd: RemoteData<SearchObjects<DSpaceObject>>) => {
return isNotEmpty(rd) && rd.hasSucceeded && rd.payload?.page?.length > 0;
})
);
}
/**
* Returns profiles that could be associated with the given user.
*
* @param eperson the user
*/
search(eperson: EPerson): Observable<RemoteData<PaginatedList<SearchResult<DSpaceObject>>>> {
searchForSuggestions(eperson: EPerson): Observable<RemoteData<SearchObjects<DSpaceObject>>> {
const query = this.personQueryData(eperson);
if (!hasValue(query) || query.length === 0) {
return of(null);
if (isEmpty(query)) {
return of(createNoContentRemoteDataObject() as RemoteData<SearchObjects<DSpaceObject>>);
}
return this.lookup(query);
}
/**
* Search object by the given query.
*
* @param query the query for the search
*/
private lookup(query: string): Observable<RemoteData<PaginatedList<SearchResult<DSpaceObject>>>> {
if (!hasValue(query)) {
return of(null);
private lookup(query: string): Observable<RemoteData<SearchObjects<DSpaceObject>>> {
if (isEmpty(query)) {
return of(createNoContentRemoteDataObject() as RemoteData<SearchObjects<DSpaceObject>>);
}
return this.searchService.search(new PaginatedSearchOptions({
configuration: 'eperson_claims',
query: query
}))
.pipe(
getFirstSucceededRemoteData(),
take(1));
}), null, false, true);
}
/**
* Return the search query for person lookup, from the given eperson
*
* @param eperson The eperson to use for the lookup
*/
private personQueryData(eperson: EPerson): string {
return 'dc.title:' + eperson.name;
if (eperson && eperson.email) {
return 'person.email:' + eperson.email;
} else {
return null;
}
}
}

View File

@@ -3,14 +3,17 @@
<p>{{'researcher.profile.associated' | translate}}</p>
<p class="align-items-center researcher-profile-switch" >
<span class="mr-3">{{'researcher.profile.status' | translate}}</span>
<ui-switch [checkedLabel]="'researcher.profile.public.visibility' | translate" [uncheckedLabel]="'researcher.profile.private.visibility' | translate" (change)="toggleProfileVisibility(researcherProfile)" [checked]="researcherProfile.visible"></ui-switch>
<ui-switch [checkedLabel]="'researcher.profile.public.visibility' | translate"
[uncheckedLabel]="'researcher.profile.private.visibility' | translate"
[checked]="researcherProfile.visible"
(change)="toggleProfileVisibility(researcherProfile)" ></ui-switch>
</p>
</div>
<div *ngIf="!researcherProfile">
<p>{{'researcher.profile.not.associated' | translate}}</p>
</div>
<button class="btn btn-primary mr-2"
[disabled]="researcherProfile || (isProcessingCreate() | async)"
<button *ngIf="!researcherProfile" class="btn btn-primary mr-2"
[disabled]="(isProcessingCreate() | async)"
(click)="createProfile()">
<span *ngIf="(isProcessingCreate() | async)">
<i class='fas fa-circle-notch fa-spin'></i> {{'researcher.profile.action.processing' | translate}}

View File

@@ -2,20 +2,22 @@ import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { TranslateModule } from '@ngx-translate/core';
import { of as observableOf } from 'rxjs';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { NotificationsServiceStub } from '../../shared/testing/notifications-service.stub';
import { EPerson } from '../../core/eperson/models/eperson.model';
import { ResearcherProfile } from '../../core/profile/model/researcher-profile.model';
import { ResearcherProfileService } from '../../core/profile/researcher-profile.service';
import { VarDirective } from '../../shared/utils/var.directive';
import { ProfilePageResearcherFormComponent } from './profile-page-researcher-form.component';
import { ProfileClaimService } from '../profile-claim/profile-claim.service';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { AuthService } from 'src/app/core/auth/auth.service';
import { AuthService } from '../../core/auth/auth.service';
import { createFailedRemoteDataObject$, createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
import { followLink } from '../../shared/utils/follow-link-config.model';
describe('ProfilePageResearcherFormComponent', () => {
@@ -26,13 +28,13 @@ describe('ProfilePageResearcherFormComponent', () => {
let user: EPerson;
let profile: ResearcherProfile;
let researcherProfileService: ResearcherProfileService;
let researcherProfileService: jasmine.SpyObj<ResearcherProfileService>;
let notificationsServiceStub: NotificationsServiceStub;
let profileClaimService: ProfileClaimService;
let profileClaimService: jasmine.SpyObj<ProfileClaimService>;
let authService: AuthService;
let authService: jasmine.SpyObj<AuthService>;
function init() {
@@ -51,9 +53,9 @@ describe('ProfilePageResearcherFormComponent', () => {
});
researcherProfileService = jasmine.createSpyObj('researcherProfileService', {
findById: observableOf(profile),
findById: createSuccessfulRemoteDataObject$(profile),
create: observableOf(profile),
setVisibility: observableOf(profile),
setVisibility: jasmine.createSpy('setVisibility'),
delete: observableOf(true),
findRelatedItemId: observableOf('a42557ca-cbb8-4442-af9c-3bb5cad2d075')
});
@@ -61,7 +63,7 @@ describe('ProfilePageResearcherFormComponent', () => {
notificationsServiceStub = new NotificationsServiceStub();
profileClaimService = jasmine.createSpyObj('profileClaimService', {
canClaimProfiles: observableOf(false),
hasProfilesToSuggest: observableOf(false),
});
}
@@ -91,7 +93,7 @@ describe('ProfilePageResearcherFormComponent', () => {
});
it('should search the researcher profile for the current user', () => {
expect(researcherProfileService.findById).toHaveBeenCalledWith(user.id);
expect(researcherProfileService.findById).toHaveBeenCalledWith(user.id, false, true, followLink('item'));
});
describe('createProfile', () => {
@@ -105,6 +107,12 @@ describe('ProfilePageResearcherFormComponent', () => {
describe('toggleProfileVisibility', () => {
describe('', () => {
beforeEach(() => {
researcherProfileService.setVisibility.and.returnValue(createSuccessfulRemoteDataObject$(profile));
});
it('should set the profile visibility to true', () => {
profile.visible = false;
component.toggleProfileVisibility(profile);
@@ -116,13 +124,47 @@ describe('ProfilePageResearcherFormComponent', () => {
component.toggleProfileVisibility(profile);
expect(researcherProfileService.setVisibility).toHaveBeenCalledWith(profile, false);
});
});
describe('on successful', () => {
beforeEach(() => {
researcherProfileService.setVisibility.and.returnValue(createSuccessfulRemoteDataObject$(profile));
});
it('should update the profile properly', () => {
profile.visible = true;
component.toggleProfileVisibility(profile);
expect(component.researcherProfile$.value).toEqual(profile);
});
});
describe('on error', () => {
beforeEach(() => {
researcherProfileService.setVisibility.and.returnValue(createFailedRemoteDataObject$());
});
it('should update the profile properly', () => {
const unchangedProfile = profile;
profile.visible = true;
component.toggleProfileVisibility(profile);
expect(component.researcherProfile$.value).toEqual(unchangedProfile);
expect((component as any).notificationService.error).toHaveBeenCalled();
});
});
});
describe('deleteProfile', () => {
beforeEach(() => {
const modalService = (component as any).modalService;
spyOn(modalService, 'open').and.returnValue(Object.assign({ componentInstance: Object.assign({ response: observableOf(true) }) }));
component.deleteProfile(profile);
fixture.detectChanges();
});
it('should delete the profile', () => {
component.deleteProfile(profile);
expect(researcherProfileService.delete).toHaveBeenCalledWith(profile);
});

View File

@@ -4,17 +4,20 @@ import { Router } from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { TranslateService } from '@ngx-translate/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { filter, mergeMap, switchMap, take, tap } from 'rxjs/operators';
import { mergeMap, switchMap, take, tap } from 'rxjs/operators';
import { getFirstCompletedRemoteData } from '../../core/shared/operators';
import { ClaimItemSelectorComponent } from '../../shared/dso-selector/modal-wrappers/claim-item-selector/claim-item-selector.component';
import { getFirstCompletedRemoteData, getFirstSucceededRemoteDataPayload } from '../../core/shared/operators';
import { ProfileClaimItemModalComponent } from '../profile-claim-item-modal/profile-claim-item-modal.component';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { AuthService } from '../../core/auth/auth.service';
import { EPerson } from '../../core/eperson/models/eperson.model';
import { ResearcherProfile } from '../../core/profile/model/researcher-profile.model';
import { ResearcherProfileService } from '../../core/profile/researcher-profile.service';
import { ProfileClaimService } from '../profile-claim/profile-claim.service';
import { RemoteData } from '../../core/data/remote-data';
import { isNotEmpty } from '../../shared/empty.util';
import { followLink } from '../../shared/utils/follow-link-config.model';
import { ConfirmationModalComponent } from '../../shared/confirmation-modal/confirmation-modal.component';
@Component({
selector: 'ds-profile-page-researcher-form',
@@ -77,12 +80,13 @@ export class ProfilePageResearcherFormComponent implements OnInit {
this.processingCreate$.next(true);
this.authService.getAuthenticatedUserFromStore().pipe(
switchMap((currentUser) => this.profileClaimService.canClaimProfiles(currentUser)))
.subscribe((canClaimProfiles) => {
take(1),
switchMap((currentUser) => this.profileClaimService.hasProfilesToSuggest(currentUser)))
.subscribe((hasProfilesToSuggest) => {
if (canClaimProfiles) {
if (hasProfilesToSuggest) {
this.processingCreate$.next(false);
const modal = this.modalService.open(ClaimItemSelectorComponent);
const modal = this.modalService.open(ProfileClaimItemModalComponent);
modal.componentInstance.dso = this.user;
modal.componentInstance.create.pipe(take(1)).subscribe(() => {
this.createProfileFromScratch();
@@ -111,6 +115,15 @@ export class ProfilePageResearcherFormComponent implements OnInit {
* @param researcherProfile the profile to delete
*/
deleteProfile(researcherProfile: ResearcherProfile): void {
const modalRef = this.modalService.open(ConfirmationModalComponent);
modalRef.componentInstance.headerLabel = 'confirmation-modal.delete-profile.header';
modalRef.componentInstance.infoLabel = 'confirmation-modal.delete-profile.info';
modalRef.componentInstance.cancelLabel = 'confirmation-modal.delete-profile.cancel';
modalRef.componentInstance.confirmLabel = 'confirmation-modal.delete-profile.confirm';
modalRef.componentInstance.brandColor = 'danger';
modalRef.componentInstance.confirmIcon = 'fas fa-trash';
modalRef.componentInstance.response.pipe(take(1)).subscribe((confirm: boolean) => {
if (confirm) {
this.processingDelete$.next(true);
this.researcherProfileService.delete(researcherProfile)
.subscribe((deleted) => {
@@ -121,6 +134,8 @@ export class ProfilePageResearcherFormComponent implements OnInit {
this.processingDelete$.next(false);
});
}
});
}
/**
* Toggle the visibility of the given researcher profile.
@@ -128,9 +143,14 @@ export class ProfilePageResearcherFormComponent implements OnInit {
* @param researcherProfile the profile to update
*/
toggleProfileVisibility(researcherProfile: ResearcherProfile): void {
this.researcherProfileService.setVisibility(researcherProfile, !researcherProfile.visible)
.subscribe((updatedProfile) => {
this.researcherProfile$.next(updatedProfile);
this.researcherProfileService.setVisibility(researcherProfile, !researcherProfile.visible).pipe(
getFirstCompletedRemoteData()
).subscribe((rd: RemoteData<ResearcherProfile>) => {
if (rd.hasSucceeded) {
this.researcherProfile$.next(rd.payload);
} else {
this.notificationService.error(null, this.translationService.get('researcher.profile.change-visibility.fail'));
}
});
}
@@ -163,9 +183,9 @@ export class ProfilePageResearcherFormComponent implements OnInit {
this.processingCreate$.next(false);
if (remoteData.isSuccess) {
this.initResearchProfile();
this.notificationService.success(this.translationService.get('researcher.profile.create.success'));
this.notificationService.success(null, this.translationService.get('researcher.profile.create.success'));
} else {
this.notificationService.error(this.translationService.get('researcher.profile.create.fail'));
this.notificationService.error(null, this.translationService.get('researcher.profile.create.fail'));
}
});
}
@@ -174,13 +194,14 @@ export class ProfilePageResearcherFormComponent implements OnInit {
* Initializes the researcherProfile and researcherProfileItemId attributes using the profile of the current user.
*/
private initResearchProfile(): void {
this.researcherProfileService.findById(this.user.id).pipe(
take(1),
filter((researcherProfile) => isNotEmpty(researcherProfile)),
this.researcherProfileService.findById(this.user.id, false, true, followLink('item')).pipe(
getFirstSucceededRemoteDataPayload(),
tap((researcherProfile) => this.researcherProfile$.next(researcherProfile)),
mergeMap((researcherProfile) => this.researcherProfileService.findRelatedItemId(researcherProfile)),
).subscribe((itemId: string) => {
if (isNotEmpty(itemId)) {
this.researcherProfileItemId = itemId;
}
});
}

View File

@@ -11,18 +11,18 @@ import { AuthTokenInfo } from '../core/auth/models/auth-token-info.model';
import { EPersonDataService } from '../core/eperson/eperson-data.service';
import { NotificationsService } from '../shared/notifications/notifications.service';
import { authReducer } from '../core/auth/auth.reducer';
import { createSuccessfulRemoteDataObject$ } from '../shared/remote-data.utils';
import { createFailedRemoteDataObject$, createSuccessfulRemoteDataObject$ } from '../shared/remote-data.utils';
import { createPaginatedList } from '../shared/testing/utils.test';
import { BehaviorSubject, of as observableOf } from 'rxjs';
import { AuthService } from '../core/auth/auth.service';
import { RestResponse } from '../core/cache/response.models';
import { provideMockStore } from '@ngrx/store/testing';
import { AuthorizationDataService } from '../core/data/feature-authorization/authorization-data.service';
import { getTestScheduler } from 'jasmine-marbles';
import { cold, getTestScheduler } from 'jasmine-marbles';
import { By } from '@angular/platform-browser';
import { EmptySpecialGroupDataMock$, SpecialGroupDataMock$ } from '../shared/testing/special-group.mock';
import { ConfigurationDataService } from '../core/data/configuration-data.service';
import { ConfigurationProperty } from '../core/shared/configuration-property.model';
import { EmptySpecialGroupDataMock$, SpecialGroupDataMock$ } from '../shared/testing/special-group.mock';
describe('ProfilePageComponent', () => {
let component: ProfilePageComponent;
@@ -31,10 +31,22 @@ describe('ProfilePageComponent', () => {
let initialState: any;
let authService;
let authorizationService;
let epersonService;
let notificationsService;
let configurationService;
const canChangePassword = new BehaviorSubject(true);
const validConfiguration = Object.assign(new ConfigurationProperty(), {
name: 'researcher-profile.entity-type',
values: [
'Person'
]
});
const emptyConfiguration = Object.assign(new ConfigurationProperty(), {
name: 'researcher-profile.entity-type',
values: []
});
function init() {
user = Object.assign(new EPerson(), {
@@ -55,7 +67,7 @@ describe('ProfilePageComponent', () => {
}
}
};
authorizationService = jasmine.createSpyObj('authorizationService', { isAuthorized: canChangePassword });
authService = jasmine.createSpyObj('authService', {
getAuthenticatedUserFromStore: observableOf(user),
getSpecialGroupsFromAuthStatus: SpecialGroupDataMock$
@@ -69,6 +81,9 @@ describe('ProfilePageComponent', () => {
error: {},
warning: {}
});
configurationService = jasmine.createSpyObj('configurationDataService', {
findByPropertyName: jasmine.createSpy('findByPropertyName')
});
}
beforeEach(waitForAsync(() => {
@@ -84,15 +99,8 @@ describe('ProfilePageComponent', () => {
{ provide: EPersonDataService, useValue: epersonService },
{ provide: NotificationsService, useValue: notificationsService },
{ provide: AuthService, useValue: authService },
{ provide: ConfigurationDataService, useValue: jasmine.createSpyObj('configurationDataService', {
findByPropertyName: createSuccessfulRemoteDataObject$(Object.assign(new ConfigurationProperty(), {
name: 'researcher-profile.entity-type',
values: [
'Person'
]
}))
})},
{ provide: AuthorizationDataService, useValue: jasmine.createSpyObj('authorizationService', { isAuthorized: canChangePassword }) },
{ provide: ConfigurationDataService, useValue: configurationService },
{ provide: AuthorizationDataService, useValue: authorizationService },
provideMockStore({ initialState }),
],
schemas: [NO_ERRORS_SCHEMA]
@@ -102,6 +110,12 @@ describe('ProfilePageComponent', () => {
beforeEach(() => {
fixture = TestBed.createComponent(ProfilePageComponent);
component = fixture.componentInstance;
});
describe('', () => {
beforeEach(() => {
configurationService.findByPropertyName.and.returnValue(createSuccessfulRemoteDataObject$(validConfiguration));
fixture.detectChanges();
});
@@ -269,3 +283,55 @@ describe('ProfilePageComponent', () => {
});
});
});
describe('isResearcherProfileEnabled', () => {
describe('when configuration service return values', () => {
beforeEach(() => {
configurationService.findByPropertyName.and.returnValue(createSuccessfulRemoteDataObject$(validConfiguration));
fixture.detectChanges();
});
it('should return true', () => {
const result = component.isResearcherProfileEnabled();
const expected = cold('a', {
a: true
});
expect(result).toBeObservable(expected);
});
});
describe('when configuration service return no values', () => {
beforeEach(() => {
configurationService.findByPropertyName.and.returnValue(createSuccessfulRemoteDataObject$(emptyConfiguration));
fixture.detectChanges();
});
it('should return false', () => {
const result = component.isResearcherProfileEnabled();
const expected = cold('a', {
a: false
});
expect(result).toBeObservable(expected);
});
});
describe('when configuration service return an error', () => {
beforeEach(() => {
configurationService.findByPropertyName.and.returnValue(createFailedRemoteDataObject$());
fixture.detectChanges();
});
it('should return false', () => {
const result = component.isResearcherProfileEnabled();
const expected = cold('a', {
a: false
});
expect(result).toBeObservable(expected);
});
});
});
});

View File

@@ -9,11 +9,7 @@ import { RemoteData } from '../core/data/remote-data';
import { PaginatedList } from '../core/data/paginated-list.model';
import { filter, switchMap, tap } from 'rxjs/operators';
import { EPersonDataService } from '../core/eperson/eperson-data.service';
import {
getAllSucceededRemoteData,
getRemoteDataPayload,
getFirstCompletedRemoteData, getFirstSucceededRemoteDataPayload
} from '../core/shared/operators';
import { getAllSucceededRemoteData, getFirstCompletedRemoteData, getRemoteDataPayload } from '../core/shared/operators';
import { hasValue, isNotEmpty } from '../shared/empty.util';
import { followLink } from '../shared/utils/follow-link-config.model';
import { AuthService } from '../core/auth/auth.service';
@@ -21,6 +17,7 @@ import { Operation } from 'fast-json-patch';
import { AuthorizationDataService } from '../core/data/feature-authorization/authorization-data.service';
import { FeatureID } from '../core/data/feature-authorization/feature-id';
import { ConfigurationDataService } from '../core/data/configuration-data.service';
import { ConfigurationProperty } from '../core/shared/configuration-property.model';
@Component({
selector: 'ds-profile-page',
@@ -97,10 +94,13 @@ export class ProfilePageComponent implements OnInit {
);
this.groupsRD$ = this.user$.pipe(switchMap((user: EPerson) => user.groups));
this.canChangePassword$ = this.user$.pipe(switchMap((user: EPerson) => this.authorizationService.isAuthorized(FeatureID.CanChangePassword, user._links.self.href)));
this.configurationService.findByPropertyName('researcher-profile.entity-type').pipe(
getFirstSucceededRemoteDataPayload()
).subscribe(() => this.isResearcherProfileEnabled$.next(true));
this.specialGroupsRD$ = this.authService.getSpecialGroupsFromAuthStatus();
this.configurationService.findByPropertyName('researcher-profile.entity-type').pipe(
getFirstCompletedRemoteData()
).subscribe((configRD: RemoteData<ConfigurationProperty>) => {
this.isResearcherProfileEnabled$.next(configRD.hasSucceeded && configRD.payload.values.length > 0);
});
}
/**
@@ -180,8 +180,8 @@ export class ProfilePageComponent implements OnInit {
/**
* Returns true if the researcher profile feature is enabled, false otherwise.
*/
isResearcherProfileEnabled(){
return this.isResearcherProfileEnabled$;
isResearcherProfileEnabled(): Observable<boolean> {
return this.isResearcherProfileEnabled$.asObservable();
}
}

View File

@@ -5,10 +5,13 @@ import { ProfilePageRoutingModule } from './profile-page-routing.module';
import { ProfilePageComponent } from './profile-page.component';
import { ProfilePageMetadataFormComponent } from './profile-page-metadata-form/profile-page-metadata-form.component';
import { ProfilePageSecurityFormComponent } from './profile-page-security-form/profile-page-security-form.component';
import { ProfilePageResearcherFormComponent } from './profile-page-researcher-form/profile-page-researcher-form.component';
import {
ProfilePageResearcherFormComponent
} from './profile-page-researcher-form/profile-page-researcher-form.component';
import { ThemedProfilePageComponent } from './themed-profile-page.component';
import { FormModule } from '../shared/form/form.module';
import { UiSwitchModule } from 'ngx-ui-switch';
import { ProfileClaimItemModalComponent } from './profile-claim-item-modal/profile-claim-item-modal.component';
@NgModule({
@@ -29,6 +32,7 @@ import { UiSwitchModule } from 'ngx-ui-switch';
declarations: [
ProfilePageComponent,
ThemedProfilePageComponent,
ProfileClaimItemModalComponent,
ProfilePageMetadataFormComponent,
ProfilePageSecurityFormComponent,
ProfilePageResearcherFormComponent

View File

@@ -0,0 +1 @@
<button class="edit-button btn btn-dark btn-sm" data-test="item-claim" *ngIf="(isClaimable() | async)" (click)="claim()"> {{"item.page.claim.button" | translate }} </button>

View File

@@ -0,0 +1,186 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { of as observableOf } from 'rxjs';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { PersonPageClaimButtonComponent } from './person-page-claim-button.component';
import { AuthorizationDataService } from '../../../core/data/feature-authorization/authorization-data.service';
import { NotificationsService } from '../../notifications/notifications.service';
import { NotificationsServiceStub } from '../../testing/notifications-service.stub';
import { TranslateLoaderMock } from '../../mocks/translate-loader.mock';
import { ResearcherProfileService } from '../../../core/profile/researcher-profile.service';
import { RouteService } from '../../../core/services/route.service';
import { routeServiceStub } from '../../testing/route-service.stub';
import { Item } from '../../../core/shared/item.model';
import { ResearcherProfile } from '../../../core/profile/model/researcher-profile.model';
import { createFailedRemoteDataObject$, createSuccessfulRemoteDataObject$ } from '../../remote-data.utils';
import { getTestScheduler } from 'jasmine-marbles';
import { TestScheduler } from 'rxjs/testing';
describe('PersonPageClaimButtonComponent', () => {
let scheduler: TestScheduler;
let component: PersonPageClaimButtonComponent;
let fixture: ComponentFixture<PersonPageClaimButtonComponent>;
const mockItem: Item = Object.assign(new Item(), {
metadata: {
'person.email': [
{
language: 'en_US',
value: 'fake@email.com'
}
],
'person.birthDate': [
{
language: 'en_US',
value: '1993'
}
],
'person.jobTitle': [
{
language: 'en_US',
value: 'Developer'
}
],
'person.familyName': [
{
language: 'en_US',
value: 'Doe'
}
],
'person.givenName': [
{
language: 'en_US',
value: 'John'
}
]
},
_links: {
self: {
href: 'item-href'
}
}
});
const mockResearcherProfile: ResearcherProfile = Object.assign(new ResearcherProfile(), {
id: 'test-id',
visible: true,
type: 'profile',
_links: {
item: {
href: 'https://rest.api/rest/api/profiles/test-id/item'
},
self: {
href: 'https://rest.api/rest/api/profiles/test-id'
},
}
});
const notificationsService = new NotificationsServiceStub();
const authorizationDataService = jasmine.createSpyObj('authorizationDataService', {
isAuthorized: jasmine.createSpy('isAuthorized')
});
const researcherProfileService = jasmine.createSpyObj('researcherProfileService', {
createFromExternalSource: jasmine.createSpy('createFromExternalSource'),
findRelatedItemId: jasmine.createSpy('findRelatedItemId'),
});
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
})
],
declarations: [PersonPageClaimButtonComponent],
providers: [
{ provide: AuthorizationDataService, useValue: authorizationDataService },
{ provide: NotificationsService, useValue: notificationsService },
{ provide: ResearcherProfileService, useValue: researcherProfileService },
{ provide: RouteService, useValue: routeServiceStub },
]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(PersonPageClaimButtonComponent);
component = fixture.componentInstance;
component.object = mockItem;
});
describe('when item can be claimed', () => {
beforeEach(() => {
authorizationDataService.isAuthorized.and.returnValue(observableOf(true));
researcherProfileService.createFromExternalSource.calls.reset();
researcherProfileService.findRelatedItemId.calls.reset();
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should create claim button', () => {
const btn = fixture.debugElement.query(By.css('[data-test="item-claim"]'));
expect(btn).toBeTruthy();
});
describe('claim', () => {
describe('when successfully', () => {
beforeEach(() => {
scheduler = getTestScheduler();
researcherProfileService.createFromExternalSource.and.returnValue(createSuccessfulRemoteDataObject$(mockResearcherProfile));
researcherProfileService.findRelatedItemId.and.returnValue(observableOf('test-id'));
});
it('should display success notification', () => {
scheduler.schedule(() => component.claim());
scheduler.flush();
expect(researcherProfileService.findRelatedItemId).toHaveBeenCalled();
expect(notificationsService.success).toHaveBeenCalled();
});
});
describe('when not successfully', () => {
beforeEach(() => {
scheduler = getTestScheduler();
researcherProfileService.createFromExternalSource.and.returnValue(createFailedRemoteDataObject$());
});
it('should display success notification', () => {
scheduler.schedule(() => component.claim());
scheduler.flush();
expect(researcherProfileService.findRelatedItemId).not.toHaveBeenCalled();
expect(notificationsService.error).toHaveBeenCalled();
});
});
});
});
describe('when item cannot be claimed', () => {
beforeEach(() => {
authorizationDataService.isAuthorized.and.returnValue(observableOf(false));
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should create claim button', () => {
const btn = fixture.debugElement.query(By.css('[data-test="item-claim"]'));
expect(btn).toBeFalsy();
});
});
});

View File

@@ -0,0 +1,84 @@
import { Component, Input, OnInit } from '@angular/core';
import { BehaviorSubject, Observable, of as observableOf } from 'rxjs';
import { mergeMap, take } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';
import { RouteService } from '../../../core/services/route.service';
import { AuthorizationDataService } from '../../../core/data/feature-authorization/authorization-data.service';
import { NotificationsService } from '../../notifications/notifications.service';
import { ResearcherProfileService } from '../../../core/profile/researcher-profile.service';
import { FeatureID } from '../../../core/data/feature-authorization/feature-id';
import { getFirstCompletedRemoteData } from '../../../core/shared/operators';
import { RemoteData } from '../../../core/data/remote-data';
import { ResearcherProfile } from '../../../core/profile/model/researcher-profile.model';
import { isNotEmpty } from '../../empty.util';
import { DSpaceObject } from '../../../core/shared/dspace-object.model';
@Component({
selector: 'ds-person-page-claim-button',
templateUrl: './person-page-claim-button.component.html',
styleUrls: ['./person-page-claim-button.component.scss']
})
export class PersonPageClaimButtonComponent implements OnInit {
/**
* The target person item to claim
*/
@Input() object: DSpaceObject;
/**
* A boolean representing if item can be claimed or not
*/
claimable$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
constructor(protected routeService: RouteService,
protected authorizationService: AuthorizationDataService,
protected notificationsService: NotificationsService,
protected translate: TranslateService,
protected researcherProfileService: ResearcherProfileService) {
}
ngOnInit(): void {
this.authorizationService.isAuthorized(FeatureID.CanClaimItem, this.object._links.self.href, null, false).pipe(
take(1)
).subscribe((isAuthorized: boolean) => {
this.claimable$.next(isAuthorized);
});
}
/**
* Create a new researcher profile claiming the current item.
*/
claim() {
this.researcherProfileService.createFromExternalSource(this.object._links.self.href).pipe(
getFirstCompletedRemoteData(),
mergeMap((rd: RemoteData<ResearcherProfile>) => {
if (rd.hasSucceeded) {
return this.researcherProfileService.findRelatedItemId(rd.payload);
} else {
return observableOf(null);
}
}))
.subscribe((id: string) => {
if (isNotEmpty(id)) {
this.notificationsService.success(this.translate.get('researcherprofile.success.claim.title'),
this.translate.get('researcherprofile.success.claim.body'));
this.claimable$.next(false);
} else {
this.notificationsService.error(
this.translate.get('researcherprofile.error.claim.title'),
this.translate.get('researcherprofile.error.claim.body'));
}
});
}
/**
* Returns true if the item is claimable, false otherwise.
*/
isClaimable(): Observable<boolean> {
return this.claimable$;
}
}

View File

@@ -1,45 +0,0 @@
import { ActivatedRoute, Router } from '@angular/router';
/* tslint:disable:no-unused-variable */
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ClaimItemSelectorComponent } from './claim-item-selector.component';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { ProfileClaimService } from '../../../../profile-page/profile-claim/profile-claim.service';
import { of } from 'rxjs';
describe('ClaimItemSelectorComponent', () => {
let component: ClaimItemSelectorComponent;
let fixture: ComponentFixture<ClaimItemSelectorComponent>;
const profileClaimService = jasmine.createSpyObj('profileClaimService', {
search: of({ payload: {page: []}})
});
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot()],
declarations: [ ClaimItemSelectorComponent ],
providers: [
{ provide: NgbActiveModal, useValue: {} },
{ provide: ActivatedRoute, useValue: {} },
{ provide: Router, useValue: {} },
{ provide: ProfileClaimService, useValue: profileClaimService }
],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ClaimItemSelectorComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -1,69 +0,0 @@
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { BehaviorSubject } from 'rxjs';
import { PaginatedList } from '../../../../core/data/paginated-list.model';
import { RemoteData } from '../../../../core/data/remote-data';
import { Item } from '../../../../core/shared/item.model';
import { SearchResult } from '../../../search/models/search-result.model';
import { DSOSelectorModalWrapperComponent } from '../dso-selector-modal-wrapper.component';
import { getItemPageRoute } from '../../../../item-page/item-page-routing-paths';
import { EPerson } from '../../../../core/eperson/models/eperson.model';
import { DSpaceObject } from '../../../../core/shared/dspace-object.model';
import { ViewMode } from '../../../../core/shared/view-mode.model';
import { ProfileClaimService } from '../../../../profile-page/profile-claim/profile-claim.service';
import { CollectionElementLinkType } from '../../../object-collection/collection-element-link.type';
/**
* Component
*/
@Component({
selector: 'ds-claim-item-selector',
templateUrl: './claim-item-selector.component.html'
})
export class ClaimItemSelectorComponent extends DSOSelectorModalWrapperComponent implements OnInit {
@Input() dso: DSpaceObject;
listEntries$: BehaviorSubject<RemoteData<PaginatedList<SearchResult<DSpaceObject>>>> = new BehaviorSubject(null);
viewMode = ViewMode.ListElement;
// enum to be exposed
linkTypes = CollectionElementLinkType;
checked = false;
@Output() create: EventEmitter<any> = new EventEmitter<any>();
constructor(protected activeModal: NgbActiveModal, protected route: ActivatedRoute, private router: Router,
private profileClaimService: ProfileClaimService) {
super(activeModal, route);
}
ngOnInit(): void {
this.profileClaimService.search(this.dso as EPerson).subscribe(
(result) => this.listEntries$.next(result)
);
}
// triggered when an item is selected
selectItem(dso: DSpaceObject): void {
this.close();
this.navigate(dso);
}
navigate(dso: DSpaceObject) {
this.router.navigate([getItemPageRoute(dso as Item)]);
}
toggleCheckbox() {
this.checked = !this.checked;
}
createFromScratch() {
this.create.emit();
this.close();
}
}

View File

@@ -0,0 +1,160 @@
import {
HealthComponent,
HealthInfoComponent,
HealthInfoResponse,
HealthResponse,
HealthStatus
} from '../../health-page/models/health-component.model';
export const HealthResponseObj: HealthResponse = {
'status': HealthStatus.UP_WITH_ISSUES,
'components': {
'db': {
'status': HealthStatus.UP,
'components': {
'dataSource': {
'status': HealthStatus.UP,
'details': {
'database': 'PostgreSQL',
'result': 1,
'validationQuery': 'SELECT 1'
}
},
'dspaceDataSource': {
'status': HealthStatus.UP,
'details': {
'database': 'PostgreSQL',
'result': 1,
'validationQuery': 'SELECT 1'
}
}
}
},
'geoIp': {
'status': HealthStatus.UP_WITH_ISSUES,
'details': {
'reason': 'The GeoLite Database file is missing (/var/lib/GeoIP/GeoLite2-City.mmdb)! Solr Statistics cannot generate location based reports! Please see the DSpace installation instructions for instructions to install this file.'
}
},
'solrOaiCore': {
'status': HealthStatus.UP,
'details': {
'status': 0,
'detectedPathType': 'particular core'
}
},
'solrSearchCore': {
'status': HealthStatus.UP,
'details': {
'status': 0,
'detectedPathType': 'particular core'
}
},
'solrStatisticsCore': {
'status': HealthStatus.UP,
'details': {
'status': 0,
'detectedPathType': 'particular core'
}
}
}
};
export const HealthComponentOne: HealthComponent = {
'status': HealthStatus.UP,
'components': {
'dataSource': {
'status': HealthStatus.UP,
'details': {
'database': 'PostgreSQL',
'result': 1,
'validationQuery': 'SELECT 1'
}
},
'dspaceDataSource': {
'status': HealthStatus.UP,
'details': {
'database': 'PostgreSQL',
'result': 1,
'validationQuery': 'SELECT 1'
}
}
}
};
export const HealthComponentTwo: HealthComponent = {
'status': HealthStatus.UP_WITH_ISSUES,
'details': {
'reason': 'The GeoLite Database file is missing (/var/lib/GeoIP/GeoLite2-City.mmdb)! Solr Statistics cannot generate location based reports! Please see the DSpace installation instructions for instructions to install this file.'
}
};
export const HealthInfoResponseObj: HealthInfoResponse = {
'app': {
'name': 'DSpace at My University',
'dir': '/home/giuseppe/development/java/install/dspace7-review',
'url': 'http://localhost:8080/server',
'db': 'jdbc:postgresql://localhost:5432/dspace7',
'solr': {
'server': 'http://localhost:8983/solr',
'prefix': ''
},
'mail': {
'server': 'smtp.example.com',
'from-address': 'dspace-noreply@myu.edu',
'feedback-recipient': 'dspace-help@myu.edu',
'mail-admin': 'dspace-help@myu.edu',
'mail-helpdesk': 'dspace-help@myu.edu',
'alert-recipient': 'dspace-help@myu.edu'
},
'cors': {
'allowed-origins': 'http://localhost:4000'
},
'ui': {
'url': 'http://localhost:4000'
}
},
'java': {
'vendor': 'Private Build',
'version': '11.0.15',
'runtime': {
'name': 'OpenJDK Runtime Environment',
'version': '11.0.15+10-Ubuntu-0ubuntu0.20.04.1'
},
'jvm': {
'name': 'OpenJDK 64-Bit Server VM',
'vendor': 'Private Build',
'version': '11.0.15+10-Ubuntu-0ubuntu0.20.04.1'
}
},
'version': '7.3-SNAPSHOT'
};
export const HealthInfoComponentOne: HealthInfoComponent = {
'name': 'DSpace at My University',
'dir': '/home/giuseppe/development/java/install/dspace7-review',
'url': 'http://localhost:8080/server',
'db': 'jdbc:postgresql://localhost:5432/dspace7',
'solr': {
'server': 'http://localhost:8983/solr',
'prefix': ''
},
'mail': {
'server': 'smtp.example.com',
'from-address': 'dspace-noreply@myu.edu',
'feedback-recipient': 'dspace-help@myu.edu',
'mail-admin': 'dspace-help@myu.edu',
'mail-helpdesk': 'dspace-help@myu.edu',
'alert-recipient': 'dspace-help@myu.edu'
},
'cors': {
'allowed-origins': 'http://localhost:4000'
},
'ui': {
'url': 'http://localhost:4000'
}
};
export const HealthInfoComponentTwo = {
'version': '7.3-SNAPSHOT'
};

View File

@@ -0,0 +1,101 @@
import {
WorkspaceitemSectionSherpaPoliciesObject
} from '../../core/submission/models/workspaceitem-section-sherpa-policies.model';
export const SherpaDataResponse = {
'id': 'sherpaPolicies',
'retrievalTime': '2022-04-20T09:44:39.870+00:00',
'sherpaResponse':
{
'error': false,
'message': null,
'metadata': {
'id': 23803,
'uri': 'http://v2.sherpa.ac.uk/id/publication/23803',
'dateCreated': '2012-11-20 14:51:52',
'dateModified': '2020-03-06 11:25:54',
'inDOAJ': false,
'publiclyVisible': true
},
'journals': [{
'titles': ['The Lancet', 'Lancet'],
'url': 'http://www.thelancet.com/journals/lancet/issue/current',
'issns': ['0140-6736', '1474-547X'],
'romeoPub': 'Elsevier: The Lancet',
'zetoPub': 'Elsevier: The Lancet',
'publisher': {
'name': 'Elsevier',
'relationshipType': null,
'country': null,
'uri': 'http://www.elsevier.com/',
'identifier': null,
'publicationCount': 0,
'paidAccessDescription': 'Open access',
'paidAccessUrl': 'https://www.elsevier.com/about/open-science/open-access'
},
'publishers': [{
'name': 'Elsevier',
'relationshipType': null,
'country': null,
'uri': 'http://www.elsevier.com/',
'identifier': null,
'publicationCount': 0,
'paidAccessDescription': 'Open access',
'paidAccessUrl': 'https://www.elsevier.com/about/open-science/open-access'
}],
'policies': [{
'id': 0,
'openAccessPermitted': false,
'uri': null,
'internalMoniker': 'Lancet',
'permittedVersions': [{
'articleVersion': 'submitted',
'option': 1,
'conditions': ['Upon publication publisher copyright and source must be acknowledged', 'Upon publication must link to publisher version'],
'prerequisites': [],
'locations': ['Author\'s Homepage', 'Preprint Repository'],
'licenses': [],
'embargo': null
}, {
'articleVersion': 'accepted',
'option': 1,
'conditions': ['Publisher copyright and source must be acknowledged', 'Must link to publisher version'],
'prerequisites': [],
'locations': ['Author\'s Homepage', 'Institutional Website'],
'licenses': ['CC BY-NC-ND'],
'embargo': null
}, {
'articleVersion': 'accepted',
'option': 2,
'conditions': ['Publisher copyright and source must be acknowledged', 'Must link to publisher version'],
'prerequisites': ['If Required by Funder'],
'locations': ['Non-Commercial Repository'],
'licenses': ['CC BY-NC-ND'],
'embargo': { amount: 6, units: 'Months' }
}, {
'articleVersion': 'accepted',
'option': 3,
'conditions': ['Publisher copyright and source must be acknowledged', 'Must link to publisher version'],
'prerequisites': [],
'locations': ['Non-Commercial Repository'],
'licenses': [],
'embargo': null
}],
'urls': {
'http://download.thelancet.com/flatcontentassets/authors/lancet-information-for-authors.pdf': 'Guidelines for Authors',
'http://www.thelancet.com/journals/lancet/article/PIIS0140-6736%2813%2960720-5/fulltext': 'The Lancet journals welcome a new open access policy',
'http://www.thelancet.com/lancet-information-for-authors/after-publication': 'What happens after publication?',
'http://www.thelancet.com/lancet/information-for-authors/disclosure-of-results': 'Disclosure of results before publication',
'https://www.elsevier.com/__data/assets/pdf_file/0005/78476/external-embargo-list.pdf': 'Journal Embargo Period List',
'https://www.elsevier.com/__data/assets/pdf_file/0011/78473/UK-Embargo-Periods.pdf': 'Journal Embargo List for UK Authors'
},
'openAccessProhibited': false,
'publicationCount': 0,
'preArchiving': 'can',
'postArchiving': 'can',
'pubArchiving': 'cannot'
}],
'inDOAJ': false
}]
}
} as WorkspaceitemSectionSherpaPoliciesObject;

View File

@@ -7,7 +7,12 @@ import { DragDropModule } from '@angular/cdk/drag-drop';
import { NouisliderModule } from 'ng2-nouislider';
import {
NgbDatepickerModule, NgbDropdownModule, NgbNavModule, NgbPaginationModule, NgbTimepickerModule, NgbTooltipModule,
NgbDatepickerModule,
NgbDropdownModule,
NgbNavModule,
NgbPaginationModule,
NgbTimepickerModule,
NgbTooltipModule,
NgbTypeaheadModule,
} from '@ng-bootstrap/ng-bootstrap';
import { MissingTranslationHandler, TranslateModule } from '@ngx-translate/core';
@@ -16,7 +21,9 @@ import { FileUploadModule } from 'ng2-file-upload';
import { InfiniteScrollModule } from 'ngx-infinite-scroll';
import { MomentModule } from 'ngx-moment';
import { ConfirmationModalComponent } from './confirmation-modal/confirmation-modal.component';
import { ExportMetadataSelectorComponent } from './dso-selector/modal-wrappers/export-metadata-selector/export-metadata-selector.component';
import {
ExportMetadataSelectorComponent
} from './dso-selector/modal-wrappers/export-metadata-selector/export-metadata-selector.component';
import { FileDropzoneNoUploaderComponent } from './file-dropzone-no-uploader/file-dropzone-no-uploader.component';
import { ItemListElementComponent } from './object-list/item-list-element/item-types/item/item-list-element.component';
import { EnumKeysPipe } from './utils/enum-keys-pipe';
@@ -24,13 +31,21 @@ import { FileSizePipe } from './utils/file-size-pipe';
import { MetadataFieldValidator } from './utils/metadatafield-validator.directive';
import { SafeUrlPipe } from './utils/safe-url-pipe';
import { ConsolePipe } from './utils/console.pipe';
import { CollectionListElementComponent } from './object-list/collection-list-element/collection-list-element.component';
import {
CollectionListElementComponent
} from './object-list/collection-list-element/collection-list-element.component';
import { CommunityListElementComponent } from './object-list/community-list-element/community-list-element.component';
import { SearchResultListElementComponent } from './object-list/search-result-list-element/search-result-list-element.component';
import {
SearchResultListElementComponent
} from './object-list/search-result-list-element/search-result-list-element.component';
import { ObjectListComponent } from './object-list/object-list.component';
import { CollectionGridElementComponent } from './object-grid/collection-grid-element/collection-grid-element.component';
import {
CollectionGridElementComponent
} from './object-grid/collection-grid-element/collection-grid-element.component';
import { CommunityGridElementComponent } from './object-grid/community-grid-element/community-grid-element.component';
import { AbstractListableElementComponent } from './object-collection/shared/object-collection-element/abstract-listable-element.component';
import {
AbstractListableElementComponent
} from './object-collection/shared/object-collection-element/abstract-listable-element.component';
import { ObjectGridComponent } from './object-grid/object-grid.component';
import { ObjectCollectionComponent } from './object-collection/object-collection.component';
import { ErrorComponent } from './error/error.component';
@@ -38,7 +53,9 @@ import { LoadingComponent } from './loading/loading.component';
import { PaginationComponent } from './pagination/pagination.component';
import { ThumbnailComponent } from '../thumbnail/thumbnail.component';
import { SearchFormComponent } from './search-form/search-form.component';
import { SearchResultGridElementComponent } from './object-grid/search-result-grid-element/search-result-grid-element.component';
import {
SearchResultGridElementComponent
} from './object-grid/search-result-grid-element/search-result-grid-element.component';
import { ViewModeSwitchComponent } from './view-mode-switch/view-mode-switch.component';
import { VarDirective } from './utils/var.directive';
import { AuthNavMenuComponent } from './auth-nav-menu/auth-nav-menu.component';
@@ -53,21 +70,33 @@ import { ChipsComponent } from './chips/chips.component';
import { NumberPickerComponent } from './number-picker/number-picker.component';
import { MockAdminGuard } from './mocks/admin-guard.service.mock';
import { AlertComponent } from './alert/alert.component';
import { SearchResultDetailElementComponent } from './object-detail/my-dspace-result-detail-element/search-result-detail-element.component';
import {
SearchResultDetailElementComponent
} from './object-detail/my-dspace-result-detail-element/search-result-detail-element.component';
import { ClaimedTaskActionsComponent } from './mydspace-actions/claimed-task/claimed-task-actions.component';
import { PoolTaskActionsComponent } from './mydspace-actions/pool-task/pool-task-actions.component';
import { ObjectDetailComponent } from './object-detail/object-detail.component';
import { ItemDetailPreviewComponent } from './object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component';
import { MyDSpaceItemStatusComponent } from './object-collection/shared/mydspace-item-status/my-dspace-item-status.component';
import {
ItemDetailPreviewComponent
} from './object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component';
import {
MyDSpaceItemStatusComponent
} from './object-collection/shared/mydspace-item-status/my-dspace-item-status.component';
import { WorkspaceitemActionsComponent } from './mydspace-actions/workspaceitem/workspaceitem-actions.component';
import { WorkflowitemActionsComponent } from './mydspace-actions/workflowitem/workflowitem-actions.component';
import { ItemSubmitterComponent } from './object-collection/shared/mydspace-item-submitter/item-submitter.component';
import { ItemActionsComponent } from './mydspace-actions/item/item-actions.component';
import { ClaimedTaskActionsApproveComponent } from './mydspace-actions/claimed-task/approve/claimed-task-actions-approve.component';
import { ClaimedTaskActionsRejectComponent } from './mydspace-actions/claimed-task/reject/claimed-task-actions-reject.component';
import {
ClaimedTaskActionsApproveComponent
} from './mydspace-actions/claimed-task/approve/claimed-task-actions-approve.component';
import {
ClaimedTaskActionsRejectComponent
} from './mydspace-actions/claimed-task/reject/claimed-task-actions-reject.component';
import { ObjNgFor } from './utils/object-ngfor.pipe';
import { BrowseByComponent } from './browse-by/browse-by.component';
import { BrowseEntryListElementComponent } from './object-list/browse-entry-list-element/browse-entry-list-element.component';
import {
BrowseEntryListElementComponent
} from './object-list/browse-entry-list-element/browse-entry-list-element.component';
import { DebounceDirective } from './utils/debounce.directive';
import { ClickOutsideDirective } from './utils/click-outside.directive';
import { EmphasizePipe } from './utils/emphasize.pipe';
@@ -76,54 +105,106 @@ import { CapitalizePipe } from './utils/capitalize.pipe';
import { ObjectKeysPipe } from './utils/object-keys-pipe';
import { AuthorityConfidenceStateDirective } from './authority-confidence/authority-confidence-state.directive';
import { LangSwitchComponent } from './lang-switch/lang-switch.component';
import { PlainTextMetadataListElementComponent } from './object-list/metadata-representation-list-element/plain-text/plain-text-metadata-list-element.component';
import { ItemMetadataListElementComponent } from './object-list/metadata-representation-list-element/item/item-metadata-list-element.component';
import { MetadataRepresentationListElementComponent } from './object-list/metadata-representation-list-element/metadata-representation-list-element.component';
import {
PlainTextMetadataListElementComponent
} from './object-list/metadata-representation-list-element/plain-text/plain-text-metadata-list-element.component';
import {
ItemMetadataListElementComponent
} from './object-list/metadata-representation-list-element/item/item-metadata-list-element.component';
import {
MetadataRepresentationListElementComponent
} from './object-list/metadata-representation-list-element/metadata-representation-list-element.component';
import { ObjectValuesPipe } from './utils/object-values-pipe';
import { InListValidator } from './utils/in-list-validator.directive';
import { AutoFocusDirective } from './utils/auto-focus.directive';
import { StartsWithDateComponent } from './starts-with/date/starts-with-date.component';
import { StartsWithTextComponent } from './starts-with/text/starts-with-text.component';
import { DSOSelectorComponent } from './dso-selector/dso-selector/dso-selector.component';
import { CreateCommunityParentSelectorComponent } from './dso-selector/modal-wrappers/create-community-parent-selector/create-community-parent-selector.component';
import { CreateItemParentSelectorComponent } from './dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component';
import { CreateCollectionParentSelectorComponent } from './dso-selector/modal-wrappers/create-collection-parent-selector/create-collection-parent-selector.component';
import { CommunitySearchResultListElementComponent } from './object-list/search-result-list-element/community-search-result/community-search-result-list-element.component';
import { CollectionSearchResultListElementComponent } from './object-list/search-result-list-element/collection-search-result/collection-search-result-list-element.component';
import { EditItemSelectorComponent } from './dso-selector/modal-wrappers/edit-item-selector/edit-item-selector.component';
import { EditCommunitySelectorComponent } from './dso-selector/modal-wrappers/edit-community-selector/edit-community-selector.component';
import { EditCollectionSelectorComponent } from './dso-selector/modal-wrappers/edit-collection-selector/edit-collection-selector.component';
import { ItemListPreviewComponent } from './object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component';
import { MetadataFieldWrapperComponent } from '../item-page/field-components/metadata-field-wrapper/metadata-field-wrapper.component';
import {
CreateCommunityParentSelectorComponent
} from './dso-selector/modal-wrappers/create-community-parent-selector/create-community-parent-selector.component';
import {
CreateItemParentSelectorComponent
} from './dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component';
import {
CreateCollectionParentSelectorComponent
} from './dso-selector/modal-wrappers/create-collection-parent-selector/create-collection-parent-selector.component';
import {
CommunitySearchResultListElementComponent
} from './object-list/search-result-list-element/community-search-result/community-search-result-list-element.component';
import {
CollectionSearchResultListElementComponent
} from './object-list/search-result-list-element/collection-search-result/collection-search-result-list-element.component';
import {
EditItemSelectorComponent
} from './dso-selector/modal-wrappers/edit-item-selector/edit-item-selector.component';
import {
EditCommunitySelectorComponent
} from './dso-selector/modal-wrappers/edit-community-selector/edit-community-selector.component';
import {
EditCollectionSelectorComponent
} from './dso-selector/modal-wrappers/edit-collection-selector/edit-collection-selector.component';
import {
ItemListPreviewComponent
} from './object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component';
import {
MetadataFieldWrapperComponent
} from '../item-page/field-components/metadata-field-wrapper/metadata-field-wrapper.component';
import { MetadataValuesComponent } from '../item-page/field-components/metadata-values/metadata-values.component';
import { RoleDirective } from './roles/role.directive';
import { UserMenuComponent } from './auth-nav-menu/user-menu/user-menu.component';
import { ClaimedTaskActionsReturnToPoolComponent } from './mydspace-actions/claimed-task/return-to-pool/claimed-task-actions-return-to-pool.component';
import { ItemDetailPreviewFieldComponent } from './object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component';
import { CollectionSearchResultGridElementComponent } from './object-grid/search-result-grid-element/collection-search-result/collection-search-result-grid-element.component';
import { CommunitySearchResultGridElementComponent } from './object-grid/search-result-grid-element/community-search-result/community-search-result-grid-element.component';
import {
ClaimedTaskActionsReturnToPoolComponent
} from './mydspace-actions/claimed-task/return-to-pool/claimed-task-actions-return-to-pool.component';
import {
ItemDetailPreviewFieldComponent
} from './object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component';
import {
CollectionSearchResultGridElementComponent
} from './object-grid/search-result-grid-element/collection-search-result/collection-search-result-grid-element.component';
import {
CommunitySearchResultGridElementComponent
} from './object-grid/search-result-grid-element/community-search-result/community-search-result-grid-element.component';
import { PageSizeSelectorComponent } from './page-size-selector/page-size-selector.component';
import { AbstractTrackableComponent } from './trackable/abstract-trackable.component';
import { ComcolMetadataComponent } from './comcol/comcol-forms/edit-comcol-page/comcol-metadata/comcol-metadata.component';
import {
ComcolMetadataComponent
} from './comcol/comcol-forms/edit-comcol-page/comcol-metadata/comcol-metadata.component';
import { ItemSelectComponent } from './object-select/item-select/item-select.component';
import { CollectionSelectComponent } from './object-select/collection-select/collection-select.component';
import { FilterInputSuggestionsComponent } from './input-suggestions/filter-suggestions/filter-input-suggestions.component';
import { DsoInputSuggestionsComponent } from './input-suggestions/dso-input-suggestions/dso-input-suggestions.component';
import {
FilterInputSuggestionsComponent
} from './input-suggestions/filter-suggestions/filter-input-suggestions.component';
import {
DsoInputSuggestionsComponent
} from './input-suggestions/dso-input-suggestions/dso-input-suggestions.component';
import { ItemGridElementComponent } from './object-grid/item-grid-element/item-types/item/item-grid-element.component';
import { TypeBadgeComponent } from './object-list/type-badge/type-badge.component';
import { AccessStatusBadgeComponent } from './object-list/access-status-badge/access-status-badge.component';
import { MetadataRepresentationLoaderComponent } from './metadata-representation/metadata-representation-loader.component';
import {
MetadataRepresentationLoaderComponent
} from './metadata-representation/metadata-representation-loader.component';
import { MetadataRepresentationDirective } from './metadata-representation/metadata-representation.directive';
import { ListableObjectComponentLoaderComponent } from './object-collection/shared/listable-object/listable-object-component-loader.component';
import { ItemSearchResultListElementComponent } from './object-list/search-result-list-element/item-search-result/item-types/item/item-search-result-list-element.component';
import {
ListableObjectComponentLoaderComponent
} from './object-collection/shared/listable-object/listable-object-component-loader.component';
import {
ItemSearchResultListElementComponent
} from './object-list/search-result-list-element/item-search-result/item-types/item/item-search-result-list-element.component';
import { ListableObjectDirective } from './object-collection/shared/listable-object/listable-object.directive';
import { ItemMetadataRepresentationListElementComponent } from './object-list/metadata-representation-list-element/item/item-metadata-representation-list-element.component';
import {
ItemMetadataRepresentationListElementComponent
} from './object-list/metadata-representation-list-element/item/item-metadata-representation-list-element.component';
import { PageWithSidebarComponent } from './sidebar/page-with-sidebar.component';
import { SidebarDropdownComponent } from './sidebar/sidebar-dropdown.component';
import { SidebarFilterComponent } from './sidebar/filter/sidebar-filter.component';
import { SidebarFilterSelectedOptionComponent } from './sidebar/filter/sidebar-filter-selected-option.component';
import { SelectableListItemControlComponent } from './object-collection/shared/selectable-list-item-control/selectable-list-item-control.component';
import { ImportableListItemControlComponent } from './object-collection/shared/importable-list-item-control/importable-list-item-control.component';
import {
SelectableListItemControlComponent
} from './object-collection/shared/selectable-list-item-control/selectable-list-item-control.component';
import {
ImportableListItemControlComponent
} from './object-collection/shared/importable-list-item-control/importable-list-item-control.component';
import { ItemVersionsComponent } from './item/item-versions/item-versions.component';
import { SortablejsModule } from 'ngx-sortablejs';
import { LogInContainerComponent } from './log-in/container/log-in-container.component';
@@ -136,10 +217,16 @@ import { ItemVersionsNoticeComponent } from './item/item-versions/notice/item-ve
import { FileValidator } from './utils/require-file.validator';
import { FileValueAccessorDirective } from './utils/file-value-accessor.directive';
import { FileSectionComponent } from '../item-page/simple/field-components/file-section/file-section.component';
import { ModifyItemOverviewComponent } from '../item-page/edit-item-page/modify-item-overview/modify-item-overview.component';
import { ClaimedTaskActionsLoaderComponent } from './mydspace-actions/claimed-task/switcher/claimed-task-actions-loader.component';
import {
ModifyItemOverviewComponent
} from '../item-page/edit-item-page/modify-item-overview/modify-item-overview.component';
import {
ClaimedTaskActionsLoaderComponent
} from './mydspace-actions/claimed-task/switcher/claimed-task-actions-loader.component';
import { ClaimedTaskActionsDirective } from './mydspace-actions/claimed-task/switcher/claimed-task-actions.directive';
import { ClaimedTaskActionsEditMetadataComponent } from './mydspace-actions/claimed-task/edit-metadata/claimed-task-actions-edit-metadata.component';
import {
ClaimedTaskActionsEditMetadataComponent
} from './mydspace-actions/claimed-task/edit-metadata/claimed-task-actions-edit-metadata.component';
import { ImpersonateNavbarComponent } from './impersonate-navbar/impersonate-navbar.component';
import { NgForTrackByIdDirective } from './ng-for-track-by-id.directive';
import { FileDownloadLinkComponent } from './file-download-link/file-download-link.component';
@@ -147,38 +234,62 @@ import { CollectionDropdownComponent } from './collection-dropdown/collection-dr
import { EntityDropdownComponent } from './entity-dropdown/entity-dropdown.component';
import { VocabularyTreeviewComponent } from './vocabulary-treeview/vocabulary-treeview.component';
import { CurationFormComponent } from '../curation-form/curation-form.component';
import { PublicationSidebarSearchListElementComponent } from './object-list/sidebar-search-list-element/item-types/publication/publication-sidebar-search-list-element.component';
import { SidebarSearchListElementComponent } from './object-list/sidebar-search-list-element/sidebar-search-list-element.component';
import { CollectionSidebarSearchListElementComponent } from './object-list/sidebar-search-list-element/collection/collection-sidebar-search-list-element.component';
import { CommunitySidebarSearchListElementComponent } from './object-list/sidebar-search-list-element/community/community-sidebar-search-list-element.component';
import { AuthorizedCollectionSelectorComponent } from './dso-selector/dso-selector/authorized-collection-selector/authorized-collection-selector.component';
import {
PublicationSidebarSearchListElementComponent
} from './object-list/sidebar-search-list-element/item-types/publication/publication-sidebar-search-list-element.component';
import {
SidebarSearchListElementComponent
} from './object-list/sidebar-search-list-element/sidebar-search-list-element.component';
import {
CollectionSidebarSearchListElementComponent
} from './object-list/sidebar-search-list-element/collection/collection-sidebar-search-list-element.component';
import {
CommunitySidebarSearchListElementComponent
} from './object-list/sidebar-search-list-element/community/community-sidebar-search-list-element.component';
import {
AuthorizedCollectionSelectorComponent
} from './dso-selector/dso-selector/authorized-collection-selector/authorized-collection-selector.component';
import { DsoPageEditButtonComponent } from './dso-page/dso-page-edit-button/dso-page-edit-button.component';
import { DsoPageVersionButtonComponent } from './dso-page/dso-page-version-button/dso-page-version-button.component';
import { HoverClassDirective } from './hover-class.directive';
import { ValidationSuggestionsComponent } from './input-suggestions/validation-suggestions/validation-suggestions.component';
import {
ValidationSuggestionsComponent
} from './input-suggestions/validation-suggestions/validation-suggestions.component';
import { ItemAlertsComponent } from './item/item-alerts/item-alerts.component';
import { ItemSearchResultGridElementComponent } from './object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component';
import {
ItemSearchResultGridElementComponent
} from './object-grid/search-result-grid-element/item-search-result/item/item-search-result-grid-element.component';
import { BitstreamDownloadPageComponent } from './bitstream-download-page/bitstream-download-page.component';
import { GenericItemPageFieldComponent } from '../item-page/simple/field-components/specific-field/generic/generic-item-page-field.component';
import { MetadataRepresentationListComponent } from '../item-page/simple/metadata-representation-list/metadata-representation-list.component';
import {
GenericItemPageFieldComponent
} from '../item-page/simple/field-components/specific-field/generic/generic-item-page-field.component';
import {
MetadataRepresentationListComponent
} from '../item-page/simple/metadata-representation-list/metadata-representation-list.component';
import { RelatedItemsComponent } from '../item-page/simple/related-items/related-items-component';
import { LinkMenuItemComponent } from './menu/menu-item/link-menu-item.component';
import { OnClickMenuItemComponent } from './menu/menu-item/onclick-menu-item.component';
import { TextMenuItemComponent } from './menu/menu-item/text-menu-item.component';
import { SearchNavbarComponent } from '../search-navbar/search-navbar.component';
import { ItemVersionsSummaryModalComponent } from './item/item-versions/item-versions-summary-modal/item-versions-summary-modal.component';
import { ItemVersionsDeleteModalComponent } from './item/item-versions/item-versions-delete-modal/item-versions-delete-modal.component';
import {
ItemVersionsSummaryModalComponent
} from './item/item-versions/item-versions-summary-modal/item-versions-summary-modal.component';
import {
ItemVersionsDeleteModalComponent
} from './item/item-versions/item-versions-delete-modal/item-versions-delete-modal.component';
import { ScopeSelectorModalComponent } from './search-form/scope-selector-modal/scope-selector-modal.component';
import { BitstreamRequestACopyPageComponent } from './bitstream-request-a-copy-page/bitstream-request-a-copy-page.component';
import {
BitstreamRequestACopyPageComponent
} from './bitstream-request-a-copy-page/bitstream-request-a-copy-page.component';
import { DsSelectComponent } from './ds-select/ds-select.component';
import { LogInOidcComponent } from './log-in/methods/oidc/log-in-oidc.component';
import { ThemedItemListPreviewComponent } from './object-list/my-dspace-result-list-element/item-list-preview/themed-item-list-preview.component';
import { ClaimItemSelectorComponent } from './dso-selector/modal-wrappers/claim-item-selector/claim-item-selector.component';
import { RSSComponent } from './rss-feed/rss.component';
import { ExternalLinkMenuItemComponent } from './menu/menu-item/external-link-menu-item.component';
import { DsoPageOrcidButtonComponent } from './dso-page/dso-page-orcid-button/dso-page-orcid-button.component';
import { LogInOrcidComponent } from './log-in/methods/orcid/log-in-orcid.component';
import { BrowserOnlyPipe } from './utils/browser-only.pipe';
import { PersonPageClaimButtonComponent } from './dso-page/person-page-claim-button/person-page-claim-button.component';
const MODULES = [
CommonModule,
@@ -350,9 +461,7 @@ const COMPONENTS = [
CollectionSidebarSearchListElementComponent,
CommunitySidebarSearchListElementComponent,
SearchNavbarComponent,
ScopeSelectorModalComponent,
ClaimItemSelectorComponent
ScopeSelectorModalComponent
];
const ENTRY_COMPONENTS = [
@@ -410,7 +519,6 @@ const ENTRY_COMPONENTS = [
OnClickMenuItemComponent,
TextMenuItemComponent,
ScopeSelectorModalComponent,
ClaimItemSelectorComponent,
ExternalLinkMenuItemComponent
];
@@ -419,6 +527,7 @@ const SHARED_ITEM_PAGE_COMPONENTS = [
MetadataValuesComponent,
DsoPageEditButtonComponent,
DsoPageVersionButtonComponent,
PersonPageClaimButtonComponent,
ItemAlertsComponent,
GenericItemPageFieldComponent,
MetadataRepresentationListComponent,

View File

@@ -20,4 +20,5 @@ export class SectionsServiceStub {
computeSectionConfiguredMetadata = jasmine.createSpy('computeSectionConfiguredMetadata');
getShownSectionErrors = jasmine.createSpy('getShownSectionErrors');
getSectionServerErrors = jasmine.createSpy('getSectionServerErrors');
getIsInformational = jasmine.createSpy('getIsInformational');
}

View File

@@ -2,7 +2,7 @@ import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { Store } from '@ngrx/store';
import { TranslateService } from '@ngx-translate/core';
import { isEqual, union } from 'lodash';
import { findKey, isEqual, union } from 'lodash';
import { from as observableFrom, Observable, of as observableOf } from 'rxjs';
import { catchError, filter, map, mergeMap, switchMap, take, tap, withLatestFrom } from 'rxjs/operators';
@@ -425,7 +425,15 @@ export class SubmissionObjectEffects {
const filteredErrors = filterErrors(sectionForm, sectionErrors, currentState.sections[sectionId].sectionType, showErrors);
mappedActions.push(new UpdateSectionDataAction(submissionId, sectionId, sectionData, filteredErrors, sectionErrors));
}
// Sherpa Policies section needs to be updated when the rest response section is empty
const sherpaPoliciesSectionId = findKey(currentState.sections, (section) => section.sectionType === SectionsType.SherpaPolicies);
if (isNotUndefined(sherpaPoliciesSectionId) && isNotEmpty(currentState.sections[sherpaPoliciesSectionId]?.data)
&& isEmpty(sections[sherpaPoliciesSectionId])) {
mappedActions.push(new UpdateSectionDataAction(submissionId, sherpaPoliciesSectionId, null, [], []));
}
});
}
return mappedActions;
}

View File

@@ -1,31 +1,34 @@
<div dsSection #sectionRef="sectionRef"
[attr.id]="'section_' + sectionData.id"
[ngClass]="{ 'section-focus' : sectionRef.isSectionActive() }"
[mandatory]="sectionData.mandatory"
[submissionId]="submissionId"
[sectionType]="sectionData.sectionType"
[sectionId]="sectionData.id">
<ngb-accordion #acc="ngbAccordion"
*ngIf="(sectionRef.isEnabled() | async)"
(panelChange)="sectionRef.sectionChange($event)"
activeIds="{{ sectionData.id }}"
[destroyOnHide]="false">
<ngb-panel id="{{ sectionData.id }}">
<div dsSection #sectionRef="sectionRef" [attr.id]="'section_' + sectionData.id"
[ngClass]="{ 'section-focus' : sectionRef.isSectionActive() }" [mandatory]="sectionData.mandatory"
[submissionId]="submissionId" [sectionType]="sectionData.sectionType" [sectionId]="sectionData.id">
<ngb-accordion #acc="ngbAccordion" *ngIf="(sectionRef.isEnabled() | async)"
(panelChange)="sectionRef.sectionChange($event)" activeIds="{{ sectionData.id }}" [destroyOnHide]="false">
<ngb-panel id="{{ sectionData.id }}" [type]="sectionRef.isInfo() ? 'info' : ''">
<ng-template ngbPanelTitle>
<span class="float-left section-title" tabindex="0">{{ 'submission.sections.'+sectionData.header | translate }}</span>
<span [ngClass]="{ 'text-white' : sectionRef.isInfo()}" class="float-left section-title" tabindex="0">{{
'submission.sections.'+sectionData.header | translate
}}</span>
<div class="d-inline-block float-right">
<i *ngIf="!(sectionRef.isValid() | async) && !(sectionRef.hasErrors())" class="fas fa-exclamation-circle text-warning mr-3"
title="{{'submission.sections.status.warnings.title' | translate}}" role="img" [attr.aria-label]="'submission.sections.status.warnings.aria' | translate"></i>
<i *ngIf="(sectionRef.hasErrors())" class="fas fa-exclamation-circle text-danger mr-3"
title="{{'submission.sections.status.errors.title' | translate}}" role="img" [attr.aria-label]="'submission.sections.status.errors.aria' | translate"></i>
<i *ngIf="(sectionRef.isValid() | async) && !(sectionRef.hasErrors())" class="fas fa-check-circle text-success mr-3"
title="{{'submission.sections.status.valid.title' | translate}}" role="img" [attr.aria-label]="'submission.sections.status.valid.aria' | translate"></i>
<a class="close"
tabindex="0"
role="button"
<i *ngIf="!(sectionRef.isValid() | async) && !(sectionRef.hasErrors()) && !(sectionRef.isInfo())"
class="fas fa-exclamation-circle text-warning mr-3"
title="{{'submission.sections.status.warnings.title' | translate}}" role="img"
[attr.aria-label]="'submission.sections.status.warnings.aria' | translate"></i>
<i *ngIf="(sectionRef.hasErrors()) && !(sectionRef.isInfo())"
class="fas fa-exclamation-circle text-danger mr-3"
title="{{'submission.sections.status.errors.title' | translate}}" role="img"
[attr.aria-label]="'submission.sections.status.errors.aria' | translate"></i>
<i *ngIf="(sectionRef.isValid() | async) && !(sectionRef.hasErrors()) && !(sectionRef.isInfo())"
class="fas fa-check-circle text-success mr-3"
title="{{'submission.sections.status.valid.title' | translate}}" role="img"
[attr.aria-label]="'submission.sections.status.valid.aria' | translate"></i>
<i *ngIf="sectionRef.isInfo()" class="fas fa-info-circle mr-3 text-white"
title="{{'submission.sections.status.info.title' | translate}}" role="img"
[attr.aria-label]="'submission.sections.status.info.aria' | translate"></i>
<a class="close" tabindex="0" role="button"
[attr.aria-label]="(sectionRef.isOpen() ? 'submission.sections.toggle.aria.close' : 'submission.sections.toggle.aria.open') | translate: {sectionHeader: ('submission.sections.'+sectionData.header | translate)}"
[title]="(sectionRef.isOpen() ? 'submission.sections.toggle.close' : 'submission.sections.toggle.open') | translate">
<span *ngIf="sectionRef.isOpen()" class="fas fa-chevron-up fa-fw"></span>
<span *ngIf="sectionRef.isOpen()" [ngClass]="{ 'text-white' : sectionRef.isInfo()}"
class="fas fa-chevron-up fa-fw"></span>
<span *ngIf="!sectionRef.isOpen()" class="fas fa-chevron-down fa-fw"></span>
</a>
<a href="javascript:void(0);" class="close mr-3" *ngIf="!sectionRef.isMandatory()"
@@ -36,14 +39,10 @@
</ng-template>
<ng-template ngbPanelContent>
<div id="sectionGenericError_{{sectionData.id}}" *ngIf="sectionRef.hasGenericErrors()">
<ds-alert *ngFor="let error of sectionRef.getErrors(); let i = index"
[content]="error"
[dismissible]="true"
[type]="AlertTypeEnum.Error"
(close)="sectionRef.removeError(i)"></ds-alert>
<ds-alert *ngFor="let error of sectionRef.getErrors(); let i = index" [content]="error" [dismissible]="true"
[type]="AlertTypeEnum.Error" (close)="sectionRef.removeError(i)"></ds-alert>
</div>
<div id="sectionContent_{{sectionData.id}}"
(click)="sectionRef.setFocus($event)">
<div id="sectionContent_{{sectionData.id}}" (click)="sectionRef.setFocus($event)">
<ng-container *ngComponentOutlet="getSectionContent(); injector: objectInjector;"></ng-container>
</div>
</ng-template>

View File

@@ -6,4 +6,5 @@ export enum SectionsType {
CcLicense = 'cclicense',
collection = 'collection',
AccessesCondition = 'accessCondition',
SherpaPolicies = 'sherpaPolicy',
}

View File

@@ -272,6 +272,19 @@ export class SectionsDirective implements OnDestroy, OnInit {
}
}
/**
* Check if section is information
*
* @returns {Observable<boolean>}
* Emits true whenever section is information
*/
public isInfo(): boolean {
return this.sectionService.getIsInformational(this.sectionType);
}
/**
* Remove error from list
*

View File

@@ -514,4 +514,16 @@ export class SectionsService {
return metadata;
}
/**
* Return if the section is an informational type section.
* @param sectionType
*/
public getIsInformational(sectionType: SectionsType): boolean {
if (sectionType === SectionsType.SherpaPolicies) {
return true;
} else {
return false;
}
}
}

View File

@@ -0,0 +1,90 @@
<div class="mb-3 border-bottom" data-test="collapse">
<div class="w-100 d-flex justify-content-between collapse-toggle" (click)="collapse.toggle()">
<div class="d-flex">
<button type="button" class="btn btn-link p-0 mr-4" (click)="$event.preventDefault()"
[attr.aria-expanded]="!collapse.collapsed" aria-controls="collapseExample">
{{version.articleVersion | titlecase}} {{ 'submission.sections.sherpa.publisher.policy.version' |
translate
}}
</button>
<div>
<span *ngIf="!!version?.embargo && !!version?.embargo.amount;else noEmbargoTitle"> <i
class="fas fa-hourglass-half"></i> {{version.embargo.amount}}
{{version.embargo?.units[0]}}</span>
<ng-template #noEmbargoTitle>
<span><i class="fas fa-hourglass-half"></i> {{
'submission.sections.sherpa.publisher.policy.noembargo' | translate }}</span>
</ng-template>
<span class="m-1 ml-4">
<i class="far fa-folder-open"></i>
<span *ngIf="!!version?.locations && version.locations.length > 0; else noLocations">
{{version.locations[0]}} <span
*ngIf="version.locations.length > 1">+{{version.locations.length-1}}</span>
</span>
<ng-template #noLocations>
<span>{{
'submission.sections.sherpa.publisher.policy.nolocation' | translate }}</span>
</ng-template>
</span>
</div>
</div>
<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 *ngIf="!!version" class="ml-4">
<div class="row" *ngIf="!!version?.embargo && !!version?.embargo.amount">
<div class="col-4">
<p class="m-1"><i class="fas fa-hourglass-half"></i> {{
'submission.sections.sherpa.publisher.policy.embargo' | translate }}</p>
</div>
<div class="col-6">
<p class="m-1" *ngIf="!!version.embargo;else noEmbargo">{{version.embargo.amount}}
{{version.embargo.units}}</p>
<ng-template #noEmbargo>
<p class="m-1">{{ 'submission.sections.sherpa.publisher.policy.noembargo' | translate }}</p>
</ng-template>
</div>
</div>
<div class="row" *ngIf="!!version?.licenses && version.licenses.length > 0">
<div class="col-4">
<p class="m-1"><i class="fas fa-certificate"></i> {{
'submission.sections.sherpa.publisher.policy.license' | translate }}</p>
</div>
<div class="col-6">
<p class="m-1" *ngFor="let license of version.licenses">{{license}}</p>
</div>
</div>
<div class="row" *ngIf="!!version?.prerequisites && version.prerequisites.length > 0">
<div class="col-4">
<p class="m-1"><i class="fas fa-exclamation-circle"></i> {{
'submission.sections.sherpa.publisher.policy.prerequisites' | translate }}</p>
</div>
<div class="col-6">
<p class="m-1" *ngFor="let prerequisite of version.prerequisites">{{prerequisite}}</p>
</div>
</div>
<div class="row" *ngIf="!!version?.locations && version.locations.length > 0">
<div class="col-4">
<p class="m-1"><i class="far fa-folder-open"></i> {{
'submission.sections.sherpa.publisher.policy.location' | translate }}</p>
</div>
<div class="col-6">
<p class="m-1" *ngFor="let location of version.locations">{{location}}</p>
</div>
</div>
<div class="row" *ngIf="!!version?.conditions && version.conditions.length > 0">
<div class="col-4">
<p class="m-1"><i class="fas fa-tasks"></i> {{
'submission.sections.sherpa.publisher.policy.conditions' | translate }}</p>
</div>
<div class="col-6">
<p class="m-1" *ngFor="let condition of version.conditions">{{condition}}</p>
</div>
</div>
</div>
</div>
</div>

View File

@@ -0,0 +1,57 @@
import { NgbCollapseModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslateLoaderMock } from '../../../../shared/mocks/translate-loader.mock';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ContentAccordionComponent } from './content-accordion.component';
import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { SherpaDataResponse } from '../../../../shared/mocks/section-sherpa-policies.service.mock';
describe('ContentAccordionComponent', () => {
let component: ContentAccordionComponent;
let fixture: ComponentFixture<ContentAccordionComponent>;
let de: DebugElement;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}),
NgbCollapseModule
],
declarations: [ContentAccordionComponent]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(ContentAccordionComponent);
component = fixture.componentInstance;
de = fixture.debugElement;
component.isCollapsed = false;
component.version = SherpaDataResponse.sherpaResponse.journals[0].policies[0].permittedVersions[0];
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should show 2 rows', () => {
component.version = SherpaDataResponse.sherpaResponse.journals[0].policies[0].permittedVersions[0];
fixture.detectChanges();
expect(de.queryAll(By.css('.row')).length).toEqual(2);
});
it('should show 5 rows', () => {
component.version = SherpaDataResponse.sherpaResponse.journals[0].policies[0].permittedVersions[2];
fixture.detectChanges();
expect(de.queryAll(By.css('.row')).length).toEqual(5);
});
});

View File

@@ -0,0 +1,23 @@
import { Component, Input } from '@angular/core';
import { PermittedVersions } from '../../../../core/submission/models/sherpa-policies-details.model';
/**
* This component represents a section that contains the inner accordions for the publisher policy versions.
*/
@Component({
selector: 'ds-content-accordion',
templateUrl: './content-accordion.component.html',
styleUrls: ['./content-accordion.component.scss']
})
export class ContentAccordionComponent {
/**
* PermittedVersions to show information from
*/
@Input() version: PermittedVersions;
/**
* A boolean representing if div should start collapsed
*/
public isCollapsed = true;
}

View File

@@ -0,0 +1,39 @@
<div class="ml-4">
<div class="row" *ngIf="!!metadata?.id">
<div class="col-4">
<p class="m-1">{{ 'submission.sections.sherpa.record.information.id' | translate }}</p>
</div>
<div class="col-8">
<p class="m-1">{{metadata.id}}
</p>
</div>
</div>
<div class="row" *ngIf="!!metadata?.dateCreated">
<div class="col-4">
<p class="m-1">{{ 'submission.sections.sherpa.record.information.date.created' | translate }}</p>
</div>
<div class="col-8">
<p class="m-1">{{metadata.dateCreated | date: 'd MMMM Y H:mm:ss zzzz' }}
</p>
</div>
</div>
<div class="row" *ngIf="!!metadata?.dateModified">
<div class="col-4">
<p class="m-1">{{ 'submission.sections.sherpa.record.information.date.modified' | translate }}</p>
</div>
<div class="col-8">
<p class="m-1">{{metadata.dateModified| date: 'd MMMM Y H:mm:ss zzzz' }}
</p>
</div>
</div>
<div class="row" *ngIf="!!metadata?.uri">
<div class="col-4">
<p class="m-1">{{ 'submission.sections.sherpa.record.information.uri' | translate }}</p>
</div>
<div class="col-8">
<p class="m-1">
<a [href]="metadata.uri" target="_blank">{{metadata.uri}}</a>
</p>
</div>
</div>
</div>

View File

@@ -0,0 +1,47 @@
import { TranslateLoaderMock } from '../../../../shared/testing/translate-loader.mock';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MetadataInformationComponent } from './metadata-information.component';
import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { SherpaDataResponse } from '../../../../shared/mocks/section-sherpa-policies.service.mock';
describe('MetadataInformationComponent', () => {
let component: MetadataInformationComponent;
let fixture: ComponentFixture<MetadataInformationComponent>;
let de: DebugElement;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}),
],
declarations: [MetadataInformationComponent]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MetadataInformationComponent);
component = fixture.componentInstance;
de = fixture.debugElement;
component.metadata = SherpaDataResponse.sherpaResponse.metadata;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should show 4 rows', () => {
expect(de.queryAll(By.css('.row')).length).toEqual(4);
});
});

View File

@@ -0,0 +1,19 @@
import { Component, Input } from '@angular/core';
import { Metadata } from '../../../../core/submission/models/sherpa-policies-details.model';
/**
* This component represents a section that contains the matadata informations.
*/
@Component({
selector: 'ds-metadata-information',
templateUrl: './metadata-information.component.html',
styleUrls: ['./metadata-information.component.scss']
})
export class MetadataInformationComponent {
/**
* Metadata to show information from
*/
@Input() metadata: Metadata;
}

View File

@@ -0,0 +1,64 @@
<div class="ml-4">
<div class="row" *ngIf="!!journal?.titles && journal.titles.length > 0">
<div class="col-4">
<p class="m-1">{{'submission.sections.sherpa.publication.information.title' | translate}}</p>
</div>
<div class="col-4">
<p class="m-1" *ngFor="let title of journal.titles">{{title}}
</p>
</div>
</div>
<div class="row" *ngIf="!!journal?.issns && journal.issns.length > 0">
<div class="col-4">
<p class="m-1">{{'submission.sections.sherpa.publication.information.issns' | translate}}</p>
</div>
<div class="col-4">
<p class="m-1" *ngFor="let issn of journal.issns">{{issn}}
</p>
</div>
</div>
<div class="row" *ngIf="!!journal?.url">
<div class="col-4">
<p class="m-1">{{'submission.sections.sherpa.publication.information.url' | translate}}</p>
</div>
<div class="col-4">
<p class="m-1">
<a href="{{journal.url}}" target="_blank">
{{journal.url}}
</a>
</p>
</div>
</div>
<div class="row" *ngIf="!!journal?.publishers && journal.publishers.length > 0">
<div class="col-4">
<p class="m-1">{{'submission.sections.sherpa.publication.information.publishers' | translate}}</p>
</div>
<div class="col-4" *ngFor="let publisher of journal.publishers">
<p class="m-1">
<a href="{{publisher.uri}}" target="_blank">
{{publisher.name}}
</a>
</p>
</div>
</div>
<div class="row" *ngIf="!!journal?.romeoPub">
<div class="col-4">
<p class="m-1">{{'submission.sections.sherpa.publication.information.romeoPub' | translate}}</p>
</div>
<div class="col-4">
<p class="m-1">
{{journal.romeoPub}}
</p>
</div>
</div>
<div class="row" *ngIf="!!journal?.zetoPub">
<div class="col-4">
<p class="m-1">{{'submission.sections.sherpa.publication.information.zetoPub' | translate}}</p>
</div>
<div class="col-4">
<p class="m-1">
{{journal.zetoPub}}
</p>
</div>
</div>
</div>

View File

@@ -0,0 +1,47 @@
import { TranslateLoaderMock } from '../../../../shared/testing/translate-loader.mock';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { PublicationInformationComponent } from './publication-information.component';
import { DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { SherpaDataResponse } from '../../../../shared/mocks/section-sherpa-policies.service.mock';
describe('PublicationInformationComponent', () => {
let component: PublicationInformationComponent;
let fixture: ComponentFixture<PublicationInformationComponent>;
let de: DebugElement;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}),
],
declarations: [PublicationInformationComponent]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(PublicationInformationComponent);
component = fixture.componentInstance;
de = fixture.debugElement;
component.journal = SherpaDataResponse.sherpaResponse.journals[0];
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should show 6 rows', () => {
expect(de.queryAll(By.css('.row')).length).toEqual(6);
});
});

View File

@@ -0,0 +1,19 @@
import { Component, Input } from '@angular/core';
import { Journal } from '../../../../core/submission/models/sherpa-policies-details.model';
/**
* This component represents a section that contains the journal publication information.
*/
@Component({
selector: 'ds-publication-information',
templateUrl: './publication-information.component.html',
styleUrls: ['./publication-information.component.scss']
})
export class PublicationInformationComponent {
/**
* Journal to show information from
*/
@Input() journal: Journal;
}

View File

@@ -0,0 +1,16 @@
<div class="ml-4">
<ds-content-accordion *ngFor="let permittedVersions of policy.permittedVersions" [version]="permittedVersions">
</ds-content-accordion>
<div class="row" *ngIf="!!policy?.urls">
<div class="col-12">
<p class="m-1">
{{'submission.sections.sherpa.publisher.policy.more.information' | translate}}
</p>
<ul>
<li *ngFor="let url of policy.urls | keyvalue">
<a href="{{url.key}}" target="_blank">{{url.value}}</a>
</li>
</ul>
</div>
</div>
</div>

View File

@@ -0,0 +1,49 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { PublisherPolicyComponent } from './publisher-policy.component';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { SherpaDataResponse } from '../../../../shared/mocks/section-sherpa-policies.service.mock';
import { TranslateLoaderMock } from '../../../../shared/mocks/translate-loader.mock';
describe('PublisherPolicyComponent', () => {
let component: PublisherPolicyComponent;
let fixture: ComponentFixture<PublisherPolicyComponent>;
let de: DebugElement;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}),
],
declarations: [PublisherPolicyComponent],
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(PublisherPolicyComponent);
component = fixture.componentInstance;
de = fixture.debugElement;
component.policy = SherpaDataResponse.sherpaResponse.journals[0].policies[0];
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should show content accordion', () => {
expect(de.query(By.css('ds-content-accordion'))).toBeTruthy();
});
it('should show 1 row', () => {
expect(de.queryAll(By.css('.row')).length).toEqual(1);
});
});

View File

@@ -0,0 +1,28 @@
import { Component, Input } from '@angular/core';
import { Policy } from '../../../../core/submission/models/sherpa-policies-details.model';
import { AlertType } from '../../../../shared/alert/aletr-type';
/**
* This component represents a section that contains the publisher policy informations.
*/
@Component({
selector: 'ds-publisher-policy',
templateUrl: './publisher-policy.component.html',
styleUrls: ['./publisher-policy.component.scss']
})
export class PublisherPolicyComponent {
/**
* Policy to show information from
*/
@Input() policy: Policy;
/**
* The AlertType enumeration
* @type {AlertType}
*/
public AlertTypeEnum = AlertType;
}

View File

@@ -0,0 +1,72 @@
<ds-alert [type]="'alert-info'" *ngIf="hasNoData()" [content]="'submission.sections.sherpa-policy.title-empty'">
</ds-alert>
<div *ngIf="!hasNoData()" class="d-flex flex-column flex-nowrap mt-2 mb-4">
<ds-alert [type]="'alert-info'" >
{{'submission.sections.sherpa.publisher.policy.description' | translate}}
</ds-alert>
<div>
<button type="button" class="btn btn-secondary float-right" (click)="refresh()" data-test="refresh-btn">
<span><i class="fas fa-sync"></i> {{'submission.sections.sherpa.publisher.policy.refresh' | translate}} </span>
</button>
</div>
</div>
<ng-container *ngVar="(sherpaPoliciesData$ | async)?.sherpaResponse as sherpaData">
<ng-container *ngIf="!hasNoData() && (!!sherpaData && !sherpaData.error)">
<ng-container *ngFor="let journal of sherpaData.journals;let j=index;">
<div class="mb-3 border-bottom" data-test="collapse">
<div class="w-100 d-flex justify-content-between collapse-toggle mb-3" (click)="collapse.toggle()">
<button type="button" class="btn btn-link p-0" (click)="$event.preventDefault()"
[attr.aria-expanded]="!collapse.collapsed" aria-controls="collapseExample">
{{'submission.sections.sherpa.publication.information' | translate}}
</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">
<ds-publication-information [journal]="journal"></ds-publication-information>
</div>
</div>
<div *ngFor="let policy of journal.policies; let p=index;" class="mb-3 border-bottom" data-test="collapse">
<div class="w-100 d-flex justify-content-between collapse-toggle mb-3" (click)="collapse.toggle()">
<button type="button" class="btn btn-link p-0" (click)="$event.preventDefault()"
[attr.aria-expanded]="!collapse.collapsed" aria-controls="collapseExample">
{{'submission.sections.sherpa.publisher.policy' | translate}}
</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">
<ds-publisher-policy [policy]="policy"></ds-publisher-policy>
</div>
</div>
</ng-container>
<div class="mb-3 border-bottom" data-test="collapse">
<div class="w-100 d-flex justify-content-between collapse-toggle mb-3" (click)="collapse.toggle()">
<button type="button" class="btn btn-link p-0" (click)="$event.preventDefault()"
[attr.aria-expanded]="!collapse.collapsed" aria-controls="collapseExample">
{{'submission.sections.sherpa.record.information' | translate}}
</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">
<ds-metadata-information [metadata]="sherpaData.metadata"></ds-metadata-information>
</div>
</div>
</ng-container>
<ng-container *ngIf="!!sherpaData && sherpaData.error">
<ds-alert [type]="AlertTypeEnum.Error"
[content]="!!sherpaData.message ? sherpaData.message : 'submission.sections.sherpa.error.message'| translate">
</ds-alert>
</ng-container>
</ng-container>

View File

@@ -0,0 +1,117 @@
import { SharedModule } from '../../../shared/shared.module';
import { NgbCollapseModule } from '@ng-bootstrap/ng-bootstrap';
import { SubmissionServiceStub } from '../../../shared/testing/submission-service.stub';
import { SherpaDataResponse } from '../../../shared/mocks/section-sherpa-policies.service.mock';
import { ComponentFixture, inject, TestBed } from '@angular/core/testing';
import { SectionsService } from '../sections.service';
import { SectionsServiceStub } from '../../../shared/testing/sections-service.stub';
import { JsonPatchOperationsBuilder } from '../../../core/json-patch/builder/json-patch-operations-builder';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { BrowserModule, By } from '@angular/platform-browser';
import { Store } from '@ngrx/store';
import { AppState } from '../../../app.reducer';
import { SubmissionSectionSherpaPoliciesComponent } from './section-sherpa-policies.component';
import { SubmissionService } from '../../submission.service';
import { DebugElement } from '@angular/core';
import { TranslateLoaderMock } from '../../../shared/mocks/translate-loader.mock';
import { of as observableOf } from 'rxjs';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
describe('SubmissionSectionSherpaPoliciesComponent', () => {
let component: SubmissionSectionSherpaPoliciesComponent;
let fixture: ComponentFixture<SubmissionSectionSherpaPoliciesComponent>;
let de: DebugElement;
const sectionsServiceStub = new SectionsServiceStub();
const operationsBuilder = jasmine.createSpyObj('operationsBuilder', {
add: undefined,
remove: undefined,
replace: undefined,
});
const storeStub = jasmine.createSpyObj('store', ['dispatch']);
const sectionData = {
header: 'submit.progressbar.sherpaPolicies',
config: 'http://localhost:8080/server/api/config/submissionaccessoptions/SherpaPoliciesDefaultConfiguration',
mandatory: true,
sectionType: 'sherpaPolicies',
collapsed: false,
enabled: true,
data: SherpaDataResponse,
errorsToShow: [],
serverValidationErrors: [],
isLoading: false,
isValid: true
};
describe('SubmissionSectionSherpaPoliciesComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
BrowserModule,
NoopAnimationsModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}),
NgbCollapseModule,
SharedModule
],
declarations: [SubmissionSectionSherpaPoliciesComponent],
providers: [
{ provide: SectionsService, useValue: sectionsServiceStub },
{ provide: JsonPatchOperationsBuilder, useValue: operationsBuilder },
{ provide: SubmissionService, useValue: SubmissionServiceStub },
{ provide: Store, useValue: storeStub },
{ provide: 'sectionDataProvider', useValue: sectionData },
{ provide: 'submissionIdProvider', useValue: '1508' },
]
})
.compileComponents();
});
beforeEach(inject([Store], (store: Store<AppState>) => {
fixture = TestBed.createComponent(SubmissionSectionSherpaPoliciesComponent);
component = fixture.componentInstance;
de = fixture.debugElement;
sectionsServiceStub.getSectionData.and.returnValue(observableOf(SherpaDataResponse));
fixture.detectChanges();
}));
it('should create', () => {
expect(component).toBeTruthy();
});
it('should show refresh button', () => {
expect(de.query(By.css('[data-test="refresh-btn"]'))).toBeTruthy();
});
it('should show publisher information', () => {
expect(de.query(By.css('ds-publication-information'))).toBeTruthy();
});
it('should show publisher policy', () => {
expect(de.query(By.css('ds-publisher-policy'))).toBeTruthy();
});
it('should show metadata information', () => {
expect(de.query(By.css('ds-metadata-information'))).toBeTruthy();
});
it('when refresh button click operationsBuilder.remove should have been called', () => {
de.query(By.css('[data-test="refresh-btn"]')).nativeElement.click();
expect(operationsBuilder.remove).toHaveBeenCalled();
});
});
});

View File

@@ -0,0 +1,127 @@
import { AlertType } from '../../../shared/alert/aletr-type';
import { Component, Inject } from '@angular/core';
import { BehaviorSubject, Observable, of, Subscription } from 'rxjs';
import { JsonPatchOperationPathCombiner } from '../../../core/json-patch/builder/json-patch-operation-path-combiner';
import { JsonPatchOperationsBuilder } from '../../../core/json-patch/builder/json-patch-operations-builder';
import {
WorkspaceitemSectionSherpaPoliciesObject
} from '../../../core/submission/models/workspaceitem-section-sherpa-policies.model';
import { renderSectionFor } from '../sections-decorator';
import { SectionsType } from '../sections-type';
import { SectionDataObject } from '../models/section-data.model';
import { SectionsService } from '../sections.service';
import { SectionModelComponent } from '../models/section.model';
import { SubmissionService } from '../../submission.service';
import { hasValue, isEmpty } from '../../../shared/empty.util';
/**
* This component represents a section for the sherpa policy informations structure.
*/
@Component({
selector: 'ds-section-sherpa-policies',
templateUrl: './section-sherpa-policies.component.html',
styleUrls: ['./section-sherpa-policies.component.scss']
})
@renderSectionFor(SectionsType.SherpaPolicies)
export class SubmissionSectionSherpaPoliciesComponent extends SectionModelComponent {
/**
* The accesses section data
* @type {WorkspaceitemSectionAccessesObject}
*/
public sherpaPoliciesData$: BehaviorSubject<WorkspaceitemSectionSherpaPoliciesObject> = new BehaviorSubject<WorkspaceitemSectionSherpaPoliciesObject>(null);
/**
* The [[JsonPatchOperationPathCombiner]] object
* @type {JsonPatchOperationPathCombiner}
*/
protected pathCombiner: JsonPatchOperationPathCombiner;
/**
* Array to track all subscriptions and unsubscribe them onDestroy
* @type {Array}
*/
protected subs: Subscription[] = [];
/**
* A boolean representing if div should start collapsed
*/
public isCollapsed = false;
/**
* The AlertType enumeration
* @type {AlertType}
*/
public AlertTypeEnum = AlertType;
/**
* Initialize instance variables
*
* @param {SectionsService} sectionService
* @param {SectionDataObject} injectedSectionData
* @param {JsonPatchOperationsBuilder} operationsBuilder
* @param {SubmissionService} submissionService
* @param {string} injectedSubmissionId
*/
constructor(
protected sectionService: SectionsService,
protected operationsBuilder: JsonPatchOperationsBuilder,
private submissionService: SubmissionService,
@Inject('sectionDataProvider') public injectedSectionData: SectionDataObject,
@Inject('submissionIdProvider') public injectedSubmissionId: string) {
super(undefined, injectedSectionData, injectedSubmissionId);
}
/**
* Unsubscribe from all subscriptions
*/
onSectionDestroy() {
this.subs
.filter((subscription) => hasValue(subscription))
.forEach((subscription) => subscription.unsubscribe());
}
/**
* Initialize all instance variables and retrieve collection default access conditions
*/
protected onSectionInit(): void {
this.pathCombiner = new JsonPatchOperationPathCombiner('sections', this.sectionData.id);
this.subs.push(
this.sectionService.getSectionData(this.submissionId, this.sectionData.id, this.sectionData.sectionType)
.subscribe((sherpaPolicies: WorkspaceitemSectionSherpaPoliciesObject) => {
this.sherpaPoliciesData$.next(sherpaPolicies);
})
);
}
/**
* Get section status
*
* @return Observable<boolean>
* the section status
*/
protected getSectionStatus(): Observable<boolean> {
return of(true);
}
/**
* Check if section has no data
*/
hasNoData(): boolean {
return isEmpty(this.sherpaPoliciesData$.value);
}
/**
* Refresh sherpa information
*/
refresh() {
this.operationsBuilder.remove(this.pathCombiner.getPath('retrievalTime'));
this.submissionService.dispatchSaveSection(this.submissionId, this.sectionData.id);
}
}

View File

@@ -22,15 +22,27 @@ import { SubmissionSectionLicenseComponent } from './sections/license/section-li
import { SubmissionUploadsConfigService } from '../core/config/submission-uploads-config.service';
import { SubmissionEditComponent } from './edit/submission-edit.component';
import { SubmissionSectionUploadFileComponent } from './sections/upload/file/section-upload-file.component';
import { SubmissionSectionUploadFileEditComponent } from './sections/upload/file/edit/section-upload-file-edit.component';
import { SubmissionSectionUploadFileViewComponent } from './sections/upload/file/view/section-upload-file-view.component';
import { SubmissionSectionUploadAccessConditionsComponent } from './sections/upload/accessConditions/submission-section-upload-access-conditions.component';
import {
SubmissionSectionUploadFileEditComponent
} from './sections/upload/file/edit/section-upload-file-edit.component';
import {
SubmissionSectionUploadFileViewComponent
} from './sections/upload/file/view/section-upload-file-view.component';
import {
SubmissionSectionUploadAccessConditionsComponent
} from './sections/upload/accessConditions/submission-section-upload-access-conditions.component';
import { SubmissionSubmitComponent } from './submit/submission-submit.component';
import { storeModuleConfig } from '../app.reducer';
import { SubmissionImportExternalComponent } from './import-external/submission-import-external.component';
import { SubmissionImportExternalSearchbarComponent } from './import-external/import-external-searchbar/submission-import-external-searchbar.component';
import { SubmissionImportExternalPreviewComponent } from './import-external/import-external-preview/submission-import-external-preview.component';
import { SubmissionImportExternalCollectionComponent } from './import-external/import-external-collection/submission-import-external-collection.component';
import {
SubmissionImportExternalSearchbarComponent
} from './import-external/import-external-searchbar/submission-import-external-searchbar.component';
import {
SubmissionImportExternalPreviewComponent
} from './import-external/import-external-preview/submission-import-external-preview.component';
import {
SubmissionImportExternalCollectionComponent
} from './import-external/import-external-collection/submission-import-external-collection.component';
import { SubmissionSectionCcLicensesComponent } from './sections/cc-license/submission-section-cc-licenses.component';
import { JournalEntitiesModule } from '../entity-groups/journal-entities/journal-entities.module';
import { ResearchEntitiesModule } from '../entity-groups/research-entities/research-entities.module';
@@ -38,10 +50,19 @@ import { ThemedSubmissionEditComponent } from './edit/themed-submission-edit.com
import { ThemedSubmissionSubmitComponent } from './submit/themed-submission-submit.component';
import { ThemedSubmissionImportExternalComponent } from './import-external/themed-submission-import-external.component';
import { FormModule } from '../shared/form/form.module';
import { NgbAccordionModule, NgbModalModule } from '@ng-bootstrap/ng-bootstrap';
import { NgbCollapseModule, NgbModalModule, NgbAccordionModule } from '@ng-bootstrap/ng-bootstrap';
import { SubmissionSectionAccessesComponent } from './sections/accesses/section-accesses.component';
import { SubmissionAccessesConfigService } from '../core/config/submission-accesses-config.service';
import { SectionAccessesService } from './sections/accesses/section-accesses.service';
import { SubmissionSectionSherpaPoliciesComponent } from './sections/sherpa-policies/section-sherpa-policies.component';
import { ContentAccordionComponent } from './sections/sherpa-policies/content-accordion/content-accordion.component';
import { PublisherPolicyComponent } from './sections/sherpa-policies/publisher-policy/publisher-policy.component';
import {
PublicationInformationComponent
} from './sections/sherpa-policies/publication-information/publication-information.component';
import {
MetadataInformationComponent
} from './sections/sherpa-policies/metadata-information/metadata-information.component';
const ENTRY_COMPONENTS = [
// put only entry components that use custom decorator
@@ -50,7 +71,8 @@ const ENTRY_COMPONENTS = [
SubmissionSectionLicenseComponent,
SubmissionSectionCcLicensesComponent,
SubmissionSectionAccessesComponent,
SubmissionSectionUploadFileEditComponent
SubmissionSectionUploadFileEditComponent,
SubmissionSectionSherpaPoliciesComponent,
];
const DECLARATIONS = [
@@ -75,6 +97,10 @@ const DECLARATIONS = [
SubmissionImportExternalSearchbarComponent,
SubmissionImportExternalPreviewComponent,
SubmissionImportExternalCollectionComponent,
ContentAccordionComponent,
PublisherPolicyComponent,
PublicationInformationComponent,
MetadataInformationComponent,
];
@NgModule({
@@ -87,8 +113,9 @@ const DECLARATIONS = [
JournalEntitiesModule.withEntryComponents(),
ResearchEntitiesModule.withEntryComponents(),
FormModule,
NgbAccordionModule,
NgbModalModule
NgbModalModule,
NgbCollapseModule,
NgbAccordionModule
],
declarations: DECLARATIONS,
exports: DECLARATIONS,

View File

@@ -1371,6 +1371,14 @@
"confirmation-modal.delete-eperson.confirm": "Delete",
"confirmation-modal.delete-profile.header": "Delete Profile",
"confirmation-modal.delete-profile.info": "Are you sure you want to delete your profile",
"confirmation-modal.delete-profile.cancel": "Cancel",
"confirmation-modal.delete-profile.confirm": "Delete",
"error.bitstream": "Error fetching bitstream",
@@ -1603,6 +1611,46 @@
"grant-request-copy.success": "Successfully granted item request",
"health.breadcrumbs": "Health",
"health-page.heading" : "Health",
"health-page.info-tab" : "Info",
"health-page.status-tab" : "Status",
"health-page.error.msg": "The health check service is temporarily unavailable",
"health-page.property.status": "Status code",
"health-page.section.db.title": "Database",
"health-page.section.geoIp.title": "GeoIp",
"health-page.section.solrAuthorityCore.title": "Sor: authority core",
"health-page.section.solrOaiCore.title": "Sor: oai core",
"health-page.section.solrSearchCore.title": "Sor: search core",
"health-page.section.solrStatisticsCore.title": "Sor: statistics core",
"health-page.section-info.app.title": "Application Backend",
"health-page.section-info.java.title": "Java",
"health-page.status": "Status",
"health-page.status.ok.info": "Operational",
"health-page.status.error.info": "Problems detected",
"health-page.status.warning.info": "Possible issues detected",
"health-page.title": "Health",
"health-page.section.no-issues": "No issues detected",
"home.description": "",
@@ -2561,13 +2609,15 @@
"menu.section.icon.find": "Find menu section",
"menu.section.icon.health": "Health check menu section",
"menu.section.icon.import": "Import menu section",
"menu.section.icon.new": "New menu section",
"menu.section.icon.pin": "Pin sidebar",
"menu.section.icon.processes": "Processes menu section",
"menu.section.icon.processes": "Processes Health",
"menu.section.icon.registries": "Registries menu section",
@@ -2609,6 +2659,8 @@
"menu.section.processes": "Processes",
"menu.section.health": "Health",
"menu.section.registries": "Registries",
@@ -2812,6 +2864,8 @@
"person.page.lastname": "Last Name",
"person.page.name": "Name",
"person.page.link.full": "Show all metadata",
"person.page.orcid": "ORCID",
@@ -4018,10 +4072,15 @@
"submission.sections.submit.progressbar.license": "Deposit license",
"submission.sections.submit.progressbar.sherpapolicy": "Sherpa policies",
"submission.sections.submit.progressbar.upload": "Upload files",
"submission.sections.submit.progressbar.sherpaPolicies": "Publisher open access policy information",
"submission.sections.sherpa-policy.title-empty": "No publisher policy information available. If your work has an associated ISSN, please enter it above to see any related publisher open access policies.",
"submission.sections.status.errors.title": "Errors",
"submission.sections.status.valid.title": "Valid",
@@ -4034,6 +4093,10 @@
"submission.sections.status.warnings.aria": "has warnings",
"submission.sections.status.info.title": "Additional Information",
"submission.sections.status.info.aria": "Additional Information",
"submission.sections.toggle.open": "Open section",
"submission.sections.toggle.close": "Close section",
@@ -4133,6 +4196,60 @@
"submission.sections.accesses.form.until-placeholder": "Until",
"submission.sections.sherpa.publication.information": "Publication information",
"submission.sections.sherpa.publication.information.title": "Title",
"submission.sections.sherpa.publication.information.issns": "ISSNs",
"submission.sections.sherpa.publication.information.url": "URL",
"submission.sections.sherpa.publication.information.publishers": "Publisher",
"submission.sections.sherpa.publication.information.romeoPub": "Romeo Pub",
"submission.sections.sherpa.publication.information.zetoPub": "Zeto Pub",
"submission.sections.sherpa.publisher.policy": "Publisher Policy",
"submission.sections.sherpa.publisher.policy.description": "The below information was found via Sherpa Romeo. Based on the policies of your publisher, it provides advice regarding whether an embargo may be necessary and/or which files you are allowed to upload. If you have questions, please contact your site administrator via the feedback form in the footer.",
"submission.sections.sherpa.publisher.policy.openaccess": "Open Access pathways permitted by this journal's policy are listed below by article version. Click on a pathway for a more detailed view",
"submission.sections.sherpa.publisher.policy.more.information": "For more information, please see the following links:",
"submission.sections.sherpa.publisher.policy.version": "Version",
"submission.sections.sherpa.publisher.policy.embargo": "Embargo",
"submission.sections.sherpa.publisher.policy.noembargo": "No Embargo",
"submission.sections.sherpa.publisher.policy.nolocation": "None",
"submission.sections.sherpa.publisher.policy.license": "License",
"submission.sections.sherpa.publisher.policy.prerequisites": "Prerequisites",
"submission.sections.sherpa.publisher.policy.location": "Location",
"submission.sections.sherpa.publisher.policy.conditions": "Conditions",
"submission.sections.sherpa.publisher.policy.refresh": "Refresh",
"submission.sections.sherpa.record.information": "Record Information",
"submission.sections.sherpa.record.information.id": "ID",
"submission.sections.sherpa.record.information.date.created": "Date Created",
"submission.sections.sherpa.record.information.date.modified": "Last Modified",
"submission.sections.sherpa.record.information.uri": "URI",
"submission.sections.sherpa.error.message": "There was an error retrieving sherpa informations",
"submission.submit.breadcrumbs": "New submission",
"submission.submit.title": "New submission",
@@ -4324,6 +4441,8 @@
"researcher.profile.associated": "Researcher profile associated",
"researcher.profile.change-visibility.fail": "An unexpected error occurs while changing the profile visibility",
"researcher.profile.create.new": "Create new",
"researcher.profile.create.success": "Researcher profile created successfully",

View File

@@ -0,0 +1,11 @@
import { Config } from './config.interface';
/**
* Config that determines the spring Actuators options
*/
export class ActuatorsConfig implements Config {
/**
* The endpoint path
*/
public endpointPath: string;
}

Some files were not shown because too many files have changed in this diff Show More