Merge branch 'CST-5307' into CST-5249_suggestion

This commit is contained in:
Luca Giamminonni
2022-05-02 10:27:33 +02:00
25 changed files with 1013 additions and 19 deletions

View File

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

View File

@@ -125,7 +125,8 @@
"url-parse": "^1.5.6",
"uuid": "^8.3.2",
"webfontloader": "1.6.28",
"zone.js": "~0.11.5"
"zone.js": "~0.11.5",
"ngx-ui-switch": "^11.0.1"
},
"devDependencies": {
"@angular-builders/custom-webpack": "~13.1.0",

View File

@@ -1,5 +1,5 @@
import { Injectable } from '@angular/core';
import { hasValue } from '../../shared/empty.util';
import { hasValue, isEmpty } from '../../shared/empty.util';
import { DSpaceObject } from '../shared/dspace-object.model';
import { TranslateService } from '@ngx-translate/core';
@@ -27,7 +27,13 @@ export class DSONameService {
*/
private readonly factories = {
Person: (dso: DSpaceObject): string => {
return `${dso.firstMetadataValue('person.familyName')}, ${dso.firstMetadataValue('person.givenName')}`;
const familyName = dso.firstMetadataValue('person.familyName');
const givenName = dso.firstMetadataValue('person.givenName');
if (isEmpty(familyName) && isEmpty(givenName)) {
return dso.firstMetadataValue('dc.title') || dso.name;
} else {
return `${familyName}, ${givenName}`;
}
},
OrgUnit: (dso: DSpaceObject): string => {
return dso.firstMetadataValue('organization.legalName');

View File

@@ -162,10 +162,13 @@ import { SearchConfig } from './shared/search/search-filters/search-config.model
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 { OpenaireSuggestionTarget } from './openaire/reciter-suggestions/models/openaire-suggestion-target.model';
import { OpenaireSuggestion } from './openaire/reciter-suggestions/models/openaire-suggestion.model';
import { OpenaireSuggestionSource } from './openaire/reciter-suggestions/models/openaire-suggestion-source.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 {SubmissionAccessesModel} from "./config/models/config-submission-accesses.model";
/**
* When not in production, endpoint responses can be mocked for testing purposes
@@ -290,6 +293,8 @@ const PROVIDERS = [
SequenceService,
GroupDataService,
FeedbackDataService,
ResearcherProfileService,
ProfileClaimService
];
/**
@@ -352,7 +357,8 @@ export const models =
OpenaireSuggestionSource,
Root,
SearchConfig,
SubmissionAccessesModel
SubmissionAccessesModel,
ResearcherProfile
];
@NgModule({

View File

@@ -28,4 +28,6 @@ export enum FeatureID {
CanCreateVersion = 'canCreateVersion',
CanViewUsageStatistics = 'canViewUsageStatistics',
CanSendFeedback = 'canSendFeedback',
ShowClaimItem = 'showClaimItem',
CanClaimItem = 'canClaimItem',
}

View File

@@ -0,0 +1,49 @@
import { autoserialize, deserialize, deserializeAs } from 'cerialize';
import { 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';
/**
* Class the represents a Researcher Profile.
*/
@typedObject
export class ResearcherProfile extends CacheableObject {
static type = RESEARCHER_PROFILE;
/**
* The object type
*/
@excludeFromEquals
@autoserialize
type: ResourceType;
/**
* The identifier of this Researcher Profile
*/
@autoserialize
id: string;
@deserializeAs('id')
uuid: string;
/**
* The visibility of this Researcher Profile
*/
@autoserialize
visible: boolean;
/**
* The {@link HALLink}s for this Researcher Profile
*/
@deserialize
_links: {
self: HALLink,
item: HALLink,
eperson: HALLink
};
}

View File

@@ -0,0 +1,9 @@
import { ResourceType } from '../../shared/resource-type';
/**
* The resource type for ResearcherProfile
*
* Needs to be in a separate file to prevent circular
* dependencies in webpack.
*/
export const RESEARCHER_PROFILE = new ResourceType('profile');

View File

@@ -0,0 +1,182 @@
/* eslint-disable max-classes-per-file */
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { 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 { environment } from '../../../environments/environment';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { dataService } from '../cache/builders/build-decorators';
import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service';
import { ObjectCacheService } from '../cache/object-cache.service';
import { ConfigurationDataService } from '../data/configuration-data.service';
import { DataService } from '../data/data.service';
import { DefaultChangeAnalyzer } from '../data/default-change-analyzer.service';
import { ItemDataService } from '../data/item-data.service';
import { RemoteData } from '../data/remote-data';
import { RequestService } from '../data/request.service';
import { 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 {
getFinishedRemoteData,
getFirstCompletedRemoteData,
getFirstSucceededRemoteDataPayload
} from '../shared/operators';
import { ResearcherProfile } from './model/researcher-profile.model';
import { RESEARCHER_PROFILE } from './model/researcher-profile.resource-type';
import { HttpOptions } from '../dspace-rest/dspace-rest.service';
import { PostRequest } from '../data/request.models';
import { hasValue } from '../../shared/empty.util';
import {CoreState} from '../core-state.model';
/**
* A private DataService implementation to delegate specific methods to.
*/
class ResearcherProfileServiceImpl extends DataService<ResearcherProfile> {
protected linkPath = 'profiles';
constructor(
protected requestService: RequestService,
protected rdbService: RemoteDataBuildService,
protected store: Store<CoreState>,
protected objectCache: ObjectCacheService,
protected halService: HALEndpointService,
protected notificationsService: NotificationsService,
protected http: HttpClient,
protected comparator: DefaultChangeAnalyzer<ResearcherProfile>) {
super();
}
}
/**
* A service that provides methods to make REST requests with researcher profile endpoint.
*/
@Injectable()
@dataService(RESEARCHER_PROFILE)
export class ResearcherProfileService {
dataService: ResearcherProfileServiceImpl;
responseMsToLive: number = 10 * 1000;
constructor(
protected requestService: RequestService,
protected rdbService: RemoteDataBuildService,
protected store: Store<CoreState>,
protected objectCache: ObjectCacheService,
protected halService: HALEndpointService,
protected notificationsService: NotificationsService,
protected http: HttpClient,
protected router: Router,
protected comparator: DefaultChangeAnalyzer<ResearcherProfile>,
protected itemService: ItemDataService,
protected configurationService: ConfigurationDataService ) {
this.dataService = new ResearcherProfileServiceImpl(requestService, rdbService, store, objectCache, halService,
notificationsService, http, comparator);
}
/**
* Find the researcher profile with the given uuid.
*
* @param uuid the profile uuid
*/
findById(uuid: string): Observable<ResearcherProfile> {
return this.dataService.findById(uuid, false)
.pipe ( getFinishedRemoteData(),
map((remoteData) => remoteData.payload));
}
/**
* Create a new researcher profile for the current user.
*/
create(): Observable<RemoteData<ResearcherProfile>> {
return this.dataService.create( new ResearcherProfile());
}
/**
* Delete a researcher profile.
*
* @param researcherProfile the profile to delete
*/
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)
);
}
/**
* Find the item id related to the given researcher profile.
*
* @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 ));
}
/**
* Change the visibility of the given researcher profile setting the given value.
*
* @param researcherProfile the profile to update
* @param visible the visibility value to set
*/
setVisibility(researcherProfile: ResearcherProfile, visible: boolean): Observable<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);
}
/**
* Creates a researcher profile starting from an external source URI
* @param sourceUri URI of source item of researcher profile.
*/
public createFromExternalSource(sourceUri: string): Observable<RemoteData<ResearcherProfile>> {
const options: HttpOptions = Object.create({});
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'text/uri-list');
options.headers = headers;
const requestId = this.requestService.generateRequestId();
const href$ = this.halService.getEndpoint(this.dataService.getLinkPath());
href$.pipe(
find((href: string) => hasValue(href)),
map((href: string) => {
const request = new PostRequest(requestId, href, sourceUri, options);
this.requestService.send(request);
})
).subscribe();
return this.rdbService.buildFromRequestUUID(requestId);
}
}

View File

@@ -10,6 +10,7 @@
<div class="pl-2 space-children-mr">
<ds-dso-page-edit-button [pageRoute]="itemPageRoute$ | async" [dso]="item"
[tooltipMsg]="'item.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>
</div>
</div>
<div class="simple-view-link my-3" *ngIf="!fromWfi">
@@ -42,4 +43,4 @@
</div>
<ds-error *ngIf="itemRD?.hasFailed" message="{{'error.item' | translate}}"></ds-error>
<ds-loading *ngIf="itemRD?.isLoading" message="{{'loading.item' | translate}}"></ds-loading>
</div>
</div>

View File

@@ -16,6 +16,10 @@ import { hasValue } from '../../shared/empty.util';
import { AuthService } from '../../core/auth/auth.service';
import { Location } from '@angular/common';
import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service';
import { TranslateService } from '@ngx-translate/core';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { ResearcherProfileService } from '../../core/profile/researcher-profile.service';
import { CollectionDataService } from '../../core/data/collection-data.service';
/**
@@ -48,8 +52,11 @@ export class FullItemPageComponent extends ItemPageComponent implements OnInit,
items: ItemDataService,
authService: AuthService,
authorizationService: AuthorizationDataService,
translate: TranslateService,
notificationsService: NotificationsService,
researcherProfileService: ResearcherProfileService,
private _location: Location) {
super(route, router, items, authService, authorizationService);
super(route, router, items, authService, authorizationService, translate, notificationsService, researcherProfileService);
}
/*** AoT inheritance fix, will hopefully be resolved in the near future **/

View File

@@ -1,21 +1,27 @@
import { map } from 'rxjs/operators';
import { map, mergeMap, take, tap } from 'rxjs/operators';
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { BehaviorSubject, Observable } from 'rxjs';
import { ItemDataService } from '../../core/data/item-data.service';
import { RemoteData } from '../../core/data/remote-data';
import { Item } from '../../core/shared/item.model';
import { fadeInOut } from '../../shared/animations/fade';
import { getAllSucceededRemoteDataPayload} from '../../core/shared/operators';
import { getAllSucceededRemoteDataPayload, getFirstSucceededRemoteData } from '../../core/shared/operators';
import { ViewMode } from '../../core/shared/view-mode.model';
import { AuthService } from '../../core/auth/auth.service';
import { getItemPageRoute } from '../item-page-routing-paths';
import { redirectOn4xx } from '../../core/shared/authorized.operators';
import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service';
import { FeatureID } from '../../core/data/feature-authorization/feature-id';
import { TranslateService } from '@ngx-translate/core';
import { ResearcherProfileService } from '../../core/profile/researcher-profile.service';
import { ResearcherProfile } from '../../core/profile/model/researcher-profile.model';
import { isNotUndefined } from '../../shared/empty.util';
import { NotificationsService } from '../../shared/notifications/notifications.service';
/**
* This component renders a simple item page.
@@ -56,13 +62,27 @@ export class ItemPageComponent implements OnInit {
*/
isAdmin$: Observable<boolean>;
itemUrl: string;
public claimable$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
public isProcessing$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
constructor(
protected route: ActivatedRoute,
private router: Router,
private items: ItemDataService,
private authService: AuthService,
private authorizationService: AuthorizationDataService
) { }
private authorizationService: AuthorizationDataService,
private translate: TranslateService,
private notificationsService: NotificationsService,
private researcherProfileService: ResearcherProfileService
) {
this.route.data.pipe(
map((data) => data.dso as RemoteData<Item>)
).subscribe((data: RemoteData<Item>) => {
this.itemUrl = data?.payload?.self;
});
}
/**
* Initialize instance variables
@@ -78,5 +98,56 @@ export class ItemPageComponent implements OnInit {
);
this.isAdmin$ = this.authorizationService.isAuthorized(FeatureID.AdministratorOf);
this.authorizationService.isAuthorized(FeatureID.ShowClaimItem, this.itemUrl).pipe(
take(1)
).subscribe((isAuthorized: boolean) => {
this.claimable$.next(isAuthorized);
});
}
claim() {
this.isProcessing$.next(true);
this.authorizationService.isAuthorized(FeatureID.CanClaimItem, this.itemUrl).pipe(
take(1)
).subscribe((isAuthorized: boolean) => {
if (!isAuthorized) {
this.notificationsService.warning(this.translate.get('researcherprofile.claim.not-authorized'));
this.isProcessing$.next(false);
} else {
this.createFromExternalSource();
}
});
}
createFromExternalSource() {
this.researcherProfileService.createFromExternalSource(this.itemUrl).pipe(
tap((rd: any) => {
if (!rd.hasSucceeded) {
this.isProcessing$.next(false);
}
}),
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);
this.isProcessing$.next(false);
} else {
this.notificationsService.error(
this.translate.get('researcherprofile.error.claim.title'),
this.translate.get('researcherprofile.error.claim.body'));
}
});
}
isClaimable(): Observable<boolean> {
return this.claimable$;
}
}

View File

@@ -0,0 +1,70 @@
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { mergeMap, switchMap, take } from 'rxjs/operators';
import { ConfigurationDataService } from '../../core/data/configuration-data.service';
import { PaginatedList } from '../../core/data/paginated-list.model';
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 { PaginatedSearchOptions } from '../../shared/search/models/paginated-search-options.model';
import { SearchResult } from '../../shared/search/models/search-result.model';
import { getFirstSucceededRemoteData } from './../../core/shared/operators';
@Injectable()
export class ProfileClaimService {
constructor(private searchService: SearchService,
private configurationService: ConfigurationDataService) {
}
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))
);
}
search(eperson: EPerson): Observable<RemoteData<PaginatedList<SearchResult<DSpaceObject>>>> {
const query = this.personQueryData(eperson);
if (!hasValue(query) || query.length === 0) {
return of(null);
}
return this.lookup(query);
}
private lookup(query: string): Observable<RemoteData<PaginatedList<SearchResult<DSpaceObject>>>> {
if (!hasValue(query)) {
return of(null);
}
return this.searchService.search(new PaginatedSearchOptions({
configuration: 'eperson_claims',
query: query
}))
.pipe(
getFirstSucceededRemoteData(),
take(1));
}
private personQueryData(eperson: EPerson): string {
const querySections = [];
this.queryParam(querySections, 'dc.title', eperson.name);
this.queryParam(querySections, 'crisrp.name', eperson.name);
return querySections.join(' OR ');
}
private queryParam(query: string[], metadata: string, value: string) {
if (!hasValue(value)) {return;}
query.push(metadata + ':' + value);
}
}

View File

@@ -0,0 +1,35 @@
<div *ngVar="(researcherProfile$ | async) as researcherProfile">
<div *ngIf="researcherProfile">
<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>
</p>
</div>
<div *ngIf="!researcherProfile">
<p>{{'researcher.profile.not.associated' | translate}}</p>
</div>
<button class="btn btn-primary"
[disabled]="researcherProfile || (isProcessingCreate() | async)"
(click)="createProfile()">
<span *ngIf="(isProcessingCreate() | async)">
<i class='fas fa-circle-notch fa-spin'></i> {{'researcher.profile.action.processing' | translate}}
</span>
<span *ngIf="!(isProcessingCreate() | async)">
<i class="fas fa-plus"></i> &nbsp;{{'researcher.profile.create.new' | translate}}
</span>
</button>
<ng-container *ngIf="researcherProfile">
<button class="btn btn-primary" [disabled]="!researcherProfile" (click)="viewProfile(researcherProfile)">
<i class="fas fa-info-circle"></i> {{'researcher.profile.view' | translate}}
</button>
<button class="btn btn-danger" [disabled]="!researcherProfile" (click)="deleteProfile(researcherProfile)">
<span *ngIf="(isProcessingDelete() | async)">
<i class='fas fa-circle-notch fa-spin'></i> {{'researcher.profile.action.processing' | translate}}
</span>
<span *ngIf="!(isProcessingDelete() | async)">
<i class="fas fa-trash-alt"></i> &nbsp;{{'researcher.profile.delete' | translate}}
</span>
</button>
</ng-container>
</div>

View File

@@ -0,0 +1,141 @@
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 { 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';
describe('ProfilePageResearcherFormComponent', () => {
let component: ProfilePageResearcherFormComponent;
let fixture: ComponentFixture<ProfilePageResearcherFormComponent>;
let router: Router;
let user: EPerson;
let profile: ResearcherProfile;
let researcherProfileService: ResearcherProfileService;
let notificationsServiceStub: NotificationsServiceStub;
let profileClaimService: ProfileClaimService;
let authService: AuthService;
function init() {
user = Object.assign(new EPerson(), {
id: 'beef9946-f4ce-479e-8f11-b90cbe9f7241'
});
profile = Object.assign(new ResearcherProfile(), {
id: 'beef9946-f4ce-479e-8f11-b90cbe9f7241',
visible: false,
type: 'profile'
});
authService = jasmine.createSpyObj('authService', {
getAuthenticatedUserFromStore: observableOf(user)
});
researcherProfileService = jasmine.createSpyObj('researcherProfileService', {
findById: observableOf(profile),
create: observableOf(profile),
setVisibility: observableOf(profile),
delete: observableOf(true),
findRelatedItemId: observableOf('a42557ca-cbb8-4442-af9c-3bb5cad2d075')
});
notificationsServiceStub = new NotificationsServiceStub();
profileClaimService = jasmine.createSpyObj('profileClaimService', {
canClaimProfiles: observableOf(false),
});
}
beforeEach(waitForAsync(() => {
init();
TestBed.configureTestingModule({
declarations: [ProfilePageResearcherFormComponent, VarDirective],
imports: [TranslateModule.forRoot(), RouterTestingModule.withRoutes([])],
providers: [
NgbModal,
{ provide: ResearcherProfileService, useValue: researcherProfileService },
{ provide: NotificationsService, useValue: notificationsServiceStub },
{ provide: ProfileClaimService, useValue: profileClaimService },
{ provide: AuthService, useValue: authService }
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ProfilePageResearcherFormComponent);
component = fixture.componentInstance;
component.user = user;
router = TestBed.inject(Router);
fixture.detectChanges();
});
it('should search the researcher profile for the current user', () => {
expect(researcherProfileService.findById).toHaveBeenCalledWith(user.id);
});
describe('createProfile', () => {
it('should create the profile', () => {
component.createProfile();
expect(researcherProfileService.create).toHaveBeenCalledWith();
});
});
describe('toggleProfileVisibility', () => {
it('should set the profile visibility to true', () => {
profile.visible = false;
component.toggleProfileVisibility(profile);
expect(researcherProfileService.setVisibility).toHaveBeenCalledWith(profile, true);
});
it('should set the profile visibility to false', () => {
profile.visible = true;
component.toggleProfileVisibility(profile);
expect(researcherProfileService.setVisibility).toHaveBeenCalledWith(profile, false);
});
});
describe('deleteProfile', () => {
it('should delete the profile', () => {
component.deleteProfile(profile);
expect(researcherProfileService.delete).toHaveBeenCalledWith(profile);
});
});
describe('viewProfile', () => {
it('should open the item details page', () => {
spyOn(router, 'navigate');
component.viewProfile(profile);
expect(router.navigate).toHaveBeenCalledWith(['items', 'a42557ca-cbb8-4442-af9c-3bb5cad2d075']);
});
});
});

View File

@@ -0,0 +1,181 @@
import { Component, Input, OnInit } from '@angular/core';
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 { getFirstCompletedRemoteData } from '../../core/shared/operators';
import { ClaimItemSelectorComponent } from '../../shared/dso-selector/modal-wrappers/claim-item-selector/claim-item-selector.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 { isNotEmpty } from '../../shared/empty.util';
@Component({
selector: 'ds-profile-page-researcher-form',
templateUrl: './profile-page-researcher-form.component.html',
})
/**
* Component for a user to create/delete or change his researcher profile.
*/
export class ProfilePageResearcherFormComponent implements OnInit {
/**
* The user to display the form for.
*/
@Input() user: EPerson;
/**
* The researcher profile to show.
*/
researcherProfile$: BehaviorSubject<ResearcherProfile> = new BehaviorSubject<ResearcherProfile>(null);
/**
* A boolean representing if a delete operation is pending
* @type {BehaviorSubject<boolean>}
*/
processingDelete$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
/**
* A boolean representing if a create delete operation is pending
* @type {BehaviorSubject<boolean>}
*/
processingCreate$: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
/**
* If exists The uuid of the item associated to the researcher profile
*/
researcherProfileItemId: string;
constructor(protected researcherProfileService: ResearcherProfileService,
protected profileClaimService: ProfileClaimService,
protected translationService: TranslateService,
protected notificationService: NotificationsService,
protected authService: AuthService,
protected router: Router,
protected modalService: NgbModal) {
}
/**
* Initialize the component searching the current user researcher profile.
*/
ngOnInit(): void {
// Retrieve researcherProfile if exists
this.initResearchProfile();
}
/**
* Create a new profile for the current user.
*/
createProfile(): void {
this.processingCreate$.next(true);
this.authService.getAuthenticatedUserFromStore().pipe(
switchMap((currentUser) => this.profileClaimService.canClaimProfiles(currentUser)))
.subscribe((canClaimProfiles) => {
if (canClaimProfiles) {
this.processingCreate$.next(false);
const modal = this.modalService.open(ClaimItemSelectorComponent);
modal.componentInstance.dso = this.user;
modal.componentInstance.create.pipe(take(1)).subscribe(() => {
this.createProfileFromScratch();
});
} else {
this.createProfileFromScratch();
}
});
}
/**
* Navigate to the items section to show the profile item details.
*
* @param researcherProfile the current researcher profile
*/
viewProfile(researcherProfile: ResearcherProfile): void {
if (this.researcherProfileItemId != null) {
this.router.navigate(['items', this.researcherProfileItemId]);
}
}
/**
* Delete the given researcher profile.
*
* @param researcherProfile the profile to delete
*/
deleteProfile(researcherProfile: ResearcherProfile): void {
this.processingDelete$.next(true);
this.researcherProfileService.delete(researcherProfile)
.subscribe((deleted) => {
if (deleted) {
this.researcherProfile$.next(null);
this.researcherProfileItemId = null;
}
this.processingDelete$.next(false);
});
}
/**
* Toggle the visibility of the given researcher profile.
*
* @param researcherProfile the profile to update
*/
toggleProfileVisibility(researcherProfile: ResearcherProfile): void {
this.researcherProfileService.setVisibility(researcherProfile, !researcherProfile.visible)
.subscribe((updatedProfile) => {
this.researcherProfile$.next(updatedProfile);
});
}
/**
* Return a boolean representing if a delete operation is pending.
*
* @return {Observable<boolean>}
*/
isProcessingDelete(): Observable<boolean> {
return this.processingDelete$.asObservable();
}
/**
* Return a boolean representing if a create operation is pending.
*
* @return {Observable<boolean>}
*/
isProcessingCreate(): Observable<boolean> {
return this.processingCreate$.asObservable();
}
createProfileFromScratch() {
this.processingCreate$.next(true);
this.researcherProfileService.create().pipe(
getFirstCompletedRemoteData()
).subscribe((remoteData) => {
this.processingCreate$.next(false);
if (remoteData.isSuccess) {
this.initResearchProfile();
this.notificationService.success(this.translationService.get('researcher.profile.create.success'));
} else {
this.notificationService.error(this.translationService.get('researcher.profile.create.fail'));
}
});
}
private initResearchProfile(): void {
this.researcherProfileService.findById(this.user.id).pipe(
take(1),
filter((researcherProfile) => isNotEmpty(researcherProfile)),
tap((researcherProfile) => this.researcherProfile$.next(researcherProfile)),
mergeMap((researcherProfile) => this.researcherProfileService.findRelatedItemId(researcherProfile)),
).subscribe((itemId: string) => {
this.researcherProfileItemId = itemId;
});
}
}

View File

@@ -1,4 +1,4 @@
<div class="container-fluid mb-4">{{FORM_PREFIX + 'info' | translate}}</div>
<ds-alert class="mb-4" [type]="'alert-info'">{{FORM_PREFIX + 'info' | translate}}</ds-alert>
<ds-form *ngIf="formModel"
[formId]="FORM_PREFIX"
[formModel]="formModel"

View File

@@ -1,6 +1,15 @@
<ng-container *ngVar="(user$ | async) as user">
<div class="container" *ngIf="user">
<h3 class="mb-4">{{'profile.head' | translate}}</h3>
<div class="card mb-4">
<div class="card-header">{{'profile.card.researcher' | translate}}</div>
<div class="card-body">
<div class="mb-4">
<ds-profile-page-researcher-form [user]="user"></ds-profile-page-researcher-form>
</div>
<!-- <ds-suggestions-notification></ds-suggestions-notification> -->
</div>
</div>
<div class="card mb-4">
<div class="card-header">{{'profile.card.identify' | translate}}</div>
<div class="card-body">

View File

@@ -5,25 +5,33 @@ 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 { ThemedProfilePageComponent } from './themed-profile-page.component';
import { FormModule } from '../shared/form/form.module';
import { UiSwitchModule } from 'ngx-ui-switch';
@NgModule({
imports: [
ProfilePageRoutingModule,
CommonModule,
SharedModule,
FormModule
FormModule,
UiSwitchModule
],
exports: [
ProfilePageComponent,
ThemedProfilePageComponent,
ProfilePageMetadataFormComponent,
ProfilePageSecurityFormComponent,
ProfilePageMetadataFormComponent
ProfilePageResearcherFormComponent
],
declarations: [
ProfilePageComponent,
ThemedProfilePageComponent,
ProfilePageMetadataFormComponent,
ProfilePageSecurityFormComponent
ProfilePageSecurityFormComponent,
ProfilePageResearcherFormComponent
]
})
export class ProfilePageModule {

View File

@@ -0,0 +1,37 @@
<div>
<div class="modal-header"><h4>{{'dso-selector.claim.item.head' | translate}}</h4>
<button type="button" class="close" (click)="close()" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="alert alert-info" role="alert">
{{'dso-selector.claim.item.body' | translate}}
</div>
<div class="dropdown-divider"></div>
<div class="scrollable-menu list-group container">
<div *ngFor="let listEntry of (listEntries$ | async)?.payload.page" class="row">
<button class="list-group-item list-group-item-action border-0 list-entry"
title="{{ listEntry.indexableObject.name }}"
(click)="selectItem(listEntry.indexableObject)" #listEntryElement>
<ds-listable-object-component-loader [object]="listEntry" [viewMode]="viewMode"
[linkType]=linkTypes.None></ds-listable-object-component-loader>
</button>
</div>
<div class="row">
<div class="col-md mt-2">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="mr-5">
<input type="checkbox" [checked]="false" (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">
<i class="fas fa-plus"></i>
{{ 'dso-selector.claim.item.create-from-scratch' | translate }}
</button>
</div>
</div>

View File

@@ -0,0 +1,45 @@
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

@@ -0,0 +1,68 @@
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({
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

@@ -172,6 +172,7 @@ import { BitstreamRequestACopyPageComponent } from './bitstream-request-a-copy-p
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 { ExternalLinkMenuItemComponent } from './menu/menu-item/external-link-menu-item.component';
const MODULES = [
@@ -342,6 +343,8 @@ const COMPONENTS = [
CommunitySidebarSearchListElementComponent,
SearchNavbarComponent,
ScopeSelectorModalComponent,
ClaimItemSelectorComponent
];
const ENTRY_COMPONENTS = [
@@ -398,7 +401,8 @@ const ENTRY_COMPONENTS = [
OnClickMenuItemComponent,
TextMenuItemComponent,
ScopeSelectorModalComponent,
ExternalLinkMenuItemComponent,
ClaimItemSelectorComponent,
ExternalLinkMenuItemComponent
];
const SHARED_ITEM_PAGE_COMPONENTS = [

View File

@@ -1315,7 +1315,13 @@
"dso-selector.set-scope.community.input-header": "Search for a community or collection",
"dso-selector.claim.item.head": "Profile tips",
"dso-selector.claim.item.body": "These are existing profiles that may be related to you. If you recognize yourself in one of these profiles, select it and on the detail page, among the options, choose to claim it. Otherwise you can create a new profile from scratch using the button below.",
"dso-selector.claim.item.not-mine-label": "None of these are mine",
"dso-selector.claim.item.create-from-scratch": "Create a new one",
"confirmation-modal.export-metadata.header": "Export metadata for {{ dsoName }}",
@@ -2128,6 +2134,8 @@
"item.page.version.hasDraft": "A new version cannot be created because there is an inprogress submission in the version history",
"item.page.claim.button": "Claim",
"item.preview.dc.identifier.uri": "Identifier:",
"item.preview.dc.contributor.author": "Authors:",
@@ -2916,7 +2924,7 @@
"profile.title": "Update Profile",
"profile.card.researcher": "Researcher Profile",
"project.listelement.badge": "Research Project",
@@ -4232,5 +4240,41 @@
"idle-modal.log-out": "Log out",
"idle-modal.extend-session": "Extend session"
"idle-modal.extend-session": "Extend session",
"researcher.profile.action.processing" : "Processing...",
"researcher.profile.associated": "Researcher profile associated",
"researcher.profile.create.new": "Create new",
"researcher.profile.create.success": "Researcher profile created successfully",
"researcher.profile.create.fail": "An error occurs during the researcher profile creation",
"researcher.profile.delete": "Delete",
"researcher.profile.expose": "Expose",
"researcher.profile.hide": "Hide",
"researcher.profile.not.associated": "Researcher profile not yet associated",
"researcher.profile.view": "View",
"researcher.profile.private.visibility" : "PRIVATE",
"researcher.profile.public.visibility" : "PUBLIC",
"researcher.profile.status": "Status:",
"researcherprofile.claim.not-authorized": "You are not authorized to claim this item. For more details contact the administrator(s).",
"researcherprofile.error.claim.body" : "An error occurred while claiming the profile, please try again later",
"researcherprofile.error.claim.title" : "Error",
"researcherprofile.success.claim.body" : "Profile claimed with success",
"researcherprofile.success.claim.title" : "Success",
}

View File

@@ -93,6 +93,13 @@ ngb-modal-backdrop {
}
.researcher-profile-switch button:focus{
outline: none !important;
}
.researcher-profile-switch .switch.checked{
color: #fff;
}
/* Replicate default spacing look ~ preserveWhitespace=true
To be used e.g. on a div containing buttons that should have a bit of spacing in between
*/

View File

@@ -8879,6 +8879,16 @@ ngx-sortablejs@^11.1.0:
dependencies:
tslib "^2.0.0"
ngx-ui-switch@^11.0.1:
version "11.0.1"
resolved "https://registry.yarnpkg.com/ngx-ui-switch/-/ngx-ui-switch-11.0.1.tgz#c7f1e97ebe698f827a26f49951b50492b22c7839"
integrity sha512-N8QYT/wW+xJdyh/aeebTSLPA6Sgrwp69H6KAcW0XZueg/LF+FKiqyG6Po/gFHq2gDhLikwyJEMpny8sudTI08w==
nice-try@^1.0.4:
version "1.0.5"
resolved "https://registry.yarnpkg.com/nice-try/-/nice-try-1.0.5.tgz#a3378a7696ce7d223e88fc9b764bd7ef1089e366"
integrity sha512-1nh45deeb5olNY7eX82BkPO7SSxR5SSYJiPTrTdFUVYwAl8CKMA5N9PjTYkHiRjisVcxcQ1HXdLhx2qxxJzLNQ==
nice-napi@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/nice-napi/-/nice-napi-1.0.2.tgz#dc0ab5a1eac20ce548802fc5686eaa6bc654927b"