Merge pull request #1641 from 4Science/CST-5674

[CST-5674] Edit resource policy
This commit is contained in:
Tim Donohue
2022-05-25 14:33:36 -05:00
committed by GitHub
7 changed files with 206 additions and 53 deletions

View File

@@ -19,6 +19,8 @@ import { createSuccessfulRemoteDataObject } from '../../shared/remote-data.utils
import { RestResponse } from '../cache/response.models';
import { RequestEntry } from '../data/request-entry.model';
import { FindListOptions } from '../data/find-list-options.model';
import { EPersonDataService } from '../eperson/eperson-data.service';
import { GroupDataService } from '../eperson/group-data.service';
describe('ResourcePolicyService', () => {
let scheduler: TestScheduler;
@@ -28,6 +30,8 @@ describe('ResourcePolicyService', () => {
let objectCache: ObjectCacheService;
let halService: HALEndpointService;
let responseCacheEntry: RequestEntry;
let ePersonService: EPersonDataService;
let groupService: GroupDataService;
const resourcePolicy: any = {
id: '1',
@@ -88,6 +92,8 @@ describe('ResourcePolicyService', () => {
const resourcePolicyRD = createSuccessfulRemoteDataObject(resourcePolicy);
const paginatedListRD = createSuccessfulRemoteDataObject(paginatedList);
const ePersonEndpoint = 'EPERSON_EP';
beforeEach(() => {
scheduler = getTestScheduler();
@@ -105,6 +111,7 @@ describe('ResourcePolicyService', () => {
removeByHrefSubstring: {},
getByHref: observableOf(responseCacheEntry),
getByUUID: observableOf(responseCacheEntry),
setStaleByHrefSubstring: {},
});
rdbService = jasmine.createSpyObj('rdbService', {
buildSingle: hot('a|', {
@@ -117,6 +124,11 @@ describe('ResourcePolicyService', () => {
a: resourcePolicyRD
})
});
ePersonService = jasmine.createSpyObj('ePersonService', {
getBrowseEndpoint: hot('a', {
a: ePersonEndpoint
}),
});
objectCache = {} as ObjectCacheService;
const notificationsService = {} as NotificationsService;
const http = {} as HttpClient;
@@ -129,7 +141,9 @@ describe('ResourcePolicyService', () => {
halService,
notificationsService,
http,
comparator
comparator,
ePersonService,
groupService
);
spyOn((service as any).dataService, 'create').and.callThrough();
@@ -320,4 +334,17 @@ describe('ResourcePolicyService', () => {
expect(result).toBeObservable(expected);
});
});
describe('updateTarget', () => {
it('should create a new PUT request for eperson', () => {
const targetType = 'eperson';
const result = service.updateTarget(resourcePolicyId, requestURL, epersonUUID, targetType);
const expected = cold('a|', {
a: resourcePolicyRD
});
expect(result).toBeObservable(expected);
});
});
});

View File

@@ -1,6 +1,6 @@
/* eslint-disable max-classes-per-file */
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
@@ -23,11 +23,19 @@ import { PaginatedList } from '../data/paginated-list.model';
import { ActionType } from './models/action-type.model';
import { RequestParam } from '../cache/models/request-param.model';
import { isNotEmpty } from '../../shared/empty.util';
import { map } from 'rxjs/operators';
import { map, take } from 'rxjs/operators';
import { NoContent } from '../shared/NoContent.model';
import { getFirstCompletedRemoteData } from '../shared/operators';
import { CoreState } from '../core-state.model';
import { FindListOptions } from '../data/find-list-options.model';
import { HttpOptions } from '../dspace-rest/dspace-rest.service';
import { PutRequest } from '../data/request.models';
import { GenericConstructor } from '../shared/generic-constructor';
import { ResponseParsingService } from '../data/parsing.service';
import { StatusCodeOnlyResponseParsingService } from '../data/status-code-only-response-parsing.service';
import { HALLink } from '../shared/hal-link.model';
import { EPersonDataService } from '../eperson/eperson-data.service';
import { GroupDataService } from '../eperson/group-data.service';
/**
@@ -44,7 +52,8 @@ class DataServiceImpl extends DataService<ResourcePolicy> {
protected halService: HALEndpointService,
protected notificationsService: NotificationsService,
protected http: HttpClient,
protected comparator: ChangeAnalyzer<ResourcePolicy>) {
protected comparator: ChangeAnalyzer<ResourcePolicy>,
) {
super();
}
@@ -68,7 +77,10 @@ export class ResourcePolicyService {
protected halService: HALEndpointService,
protected notificationsService: NotificationsService,
protected http: HttpClient,
protected comparator: DefaultChangeAnalyzer<ResourcePolicy>) {
protected comparator: DefaultChangeAnalyzer<ResourcePolicy>,
protected ePersonService: EPersonDataService,
protected groupService: GroupDataService,
) {
this.dataService = new DataServiceImpl(requestService, rdbService, null, objectCache, halService, notificationsService, http, comparator);
}
@@ -221,4 +233,44 @@ export class ResourcePolicyService {
return this.dataService.searchBy(this.searchByResourceMethod, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow);
}
/**
* Update the target of the resource policy
* @param resourcePolicyId the ID of the resource policy
* @param resourcePolicyHref the link to the resource policy
* @param targetUUID the UUID of the target to which the permission is being granted
* @param targetType the type of the target (eperson or group) to which the permission is being granted
*/
updateTarget(resourcePolicyId: string, resourcePolicyHref: string, targetUUID: string, targetType: string): Observable<RemoteData<any>> {
const targetService = targetType === 'eperson' ? this.ePersonService : this.groupService;
const targetEndpoint$ = targetService.getBrowseEndpoint().pipe(
take(1),
map((endpoint: string) =>`${endpoint}/${targetUUID}`),
);
const options: HttpOptions = Object.create({});
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'text/uri-list');
options.headers = headers;
const requestId = this.requestService.generateRequestId();
this.requestService.setStaleByHrefSubstring(`${this.dataService.getLinkPath()}/${resourcePolicyId}/${targetType}`);
targetEndpoint$.subscribe((targetEndpoint) => {
const resourceEndpoint = resourcePolicyHref + '/' + targetType;
const request = new PutRequest(requestId, resourceEndpoint, targetEndpoint, options);
Object.assign(request, {
getResponseParser(): GenericConstructor<ResponseParsingService> {
return StatusCodeOnlyResponseParsingService;
}
});
this.requestService.send(request);
});
return this.rdbService.buildFromRequestUUID(requestId);
}
}

View File

@@ -1,7 +1,7 @@
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { BehaviorSubject, Observable } from 'rxjs';
import { BehaviorSubject, Observable, of, combineLatest as observableCombineLatest, } from 'rxjs';
import { map, take } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';
@@ -88,16 +88,33 @@ export class ResourcePolicyEditComponent implements OnInit {
type: RESOURCE_POLICY.value,
_links: this.resourcePolicy._links
});
this.resourcePolicyService.update(updatedObject).pipe(
const updateTargetSucceeded$ = event.updateTarget ? this.resourcePolicyService.updateTarget(
this.resourcePolicy.id, this.resourcePolicy._links.self.href, event.target.uuid, event.target.type
).pipe(
getFirstCompletedRemoteData(),
).subscribe((responseRD: RemoteData<ResourcePolicy>) => {
this.processing$.next(false);
if (responseRD && responseRD.hasSucceeded) {
this.notificationsService.success(null, this.translate.get('resource-policies.edit.page.success.content'));
this.redirectToAuthorizationsPage();
} else {
this.notificationsService.error(null, this.translate.get('resource-policies.edit.page.failure.content'));
map((responseRD) => responseRD && responseRD.hasSucceeded)
) : of(true);
const updateResourcePolicySucceeded$ = this.resourcePolicyService.update(updatedObject).pipe(
getFirstCompletedRemoteData(),
map((responseRD) => responseRD && responseRD.hasSucceeded)
);
observableCombineLatest([updateTargetSucceeded$, updateResourcePolicySucceeded$]).subscribe(
([updateTargetSucceeded, updateResourcePolicySucceeded]) => {
this.processing$.next(false);
if (updateTargetSucceeded && updateResourcePolicySucceeded) {
this.notificationsService.success(null, this.translate.get('resource-policies.edit.page.success.content'));
this.redirectToAuthorizationsPage();
} else if (updateResourcePolicySucceeded) { // everything except target has been updated
this.notificationsService.error(null, this.translate.get('resource-policies.edit.page.target-failure.content'));
} else if (updateTargetSucceeded) { // only target has been updated
this.notificationsService.error(null, this.translate.get('resource-policies.edit.page.other-failure.content'));
} else { // nothing has been updated
this.notificationsService.error(null, this.translate.get('resource-policies.edit.page.failure.content'));
}
}
});
);
}
}

View File

@@ -7,25 +7,23 @@
[displayCancel]="false"></ds-form>
<div class="container-fluid">
<label for="ResourcePolicyObject">{{'resource-policies.form.eperson-group-list.label' | translate}}</label>
<input id="ResourcePolicyObject" class="form-control mb-3" type="text" readonly [value]="resourcePolicyTargetName$ | async">
<ng-container *ngIf="canSetGrant()">
<ul ngbNav #nav="ngbNav" class="nav-pills">
<li ngbNavItem>
<a ngbNavLink>{{'resource-policies.form.eperson-group-list.tab.eperson' | translate}}</a>
<ng-template ngbNavContent>
<ds-eperson-group-list (select)="updateObjectSelected($event, true)"></ds-eperson-group-list>
</ng-template>
</li>
<li ngbNavItem>
<a ngbNavLink>{{'resource-policies.form.eperson-group-list.tab.group' | translate}}</a>
<ng-template ngbNavContent>
<ds-eperson-group-list [isListOfEPerson]="false"
(select)="updateObjectSelected($event, false)"></ds-eperson-group-list>
</ng-template>
</li>
</ul>
<div [ngbNavOutlet]="nav"></div>
</ng-container>
<input id="ResourcePolicyObject" class="form-control mb-3" type="text" [value]="resourcePolicyTargetName$ | async">
<ul ngbNav #nav="ngbNav" class="nav-pills" [(activeId)]="navActiveId" (navChange)="onNavChange($event)">
<li [ngbNavItem]="'eperson'">
<a ngbNavLink>{{'resource-policies.form.eperson-group-list.tab.eperson' | translate}}</a>
<ng-template ngbNavContent>
<ds-eperson-group-list (select)="updateObjectSelected($event, true)"></ds-eperson-group-list>
</ng-template>
</li>
<li [ngbNavItem]="'group'">
<a ngbNavLink>{{'resource-policies.form.eperson-group-list.tab.group' | translate}}</a>
<ng-template ngbNavContent>
<ds-eperson-group-list [isListOfEPerson]="false"
(select)="updateObjectSelected($event, false)"></ds-eperson-group-list>
</ng-template>
</li>
</ul>
<div [ngbNavOutlet]="nav"></div>
<div>
<hr>
<div class="form-group row">
@@ -51,3 +49,28 @@
</div>
</div>
</div>
<ng-template #content let-modal>
<div class="modal-header">
<h4 class="modal-title" id="modal-basic-title">{{ 'resource-policies.form.eperson-group-list.modal.header' | translate }}</h4>
<button type="button" class="close" aria-label="Close" (click)="modal.close()">
<span aria-hidden="true">&times;</span>
</button>
</div>
<div class="modal-body">
<div class="d-flex flex-row">
<div class="mr-3">
<i class="fas fa-info-circle fa-2x text-info"></i>
</div>
<div>
<p [innerHTML]="(navActiveId === 'eperson' ? 'resource-policies.form.eperson-group-list.modal.text1.toGroup' :
'resource-policies.form.eperson-group-list.modal.text1.toEPerson') | translate" class="font-weight-bold"></p>
<p [innerHTML]="'resource-policies.form.eperson-group-list.modal.text2' | translate"></p>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" (click)="modal.close()">{{ 'resource-policies.form.eperson-group-list.modal.close' | translate }}</button>
</div>
</ng-template>

View File

@@ -242,6 +242,7 @@ describe('ResourcePolicyFormComponent test suite', () => {
fixture = TestBed.createComponent(ResourcePolicyFormComponent);
comp = fixture.componentInstance;
compAsAny = fixture.componentInstance;
compAsAny.resourcePolicy = resourcePolicy;
comp.isProcessing = observableOf(false);
});
@@ -253,6 +254,8 @@ describe('ResourcePolicyFormComponent test suite', () => {
});
it('should init form model properly', () => {
epersonService.findByHref.and.returnValue(observableOf(undefined));
groupService.findByHref.and.returnValue(observableOf(undefined));
spyOn(compAsAny, 'isFormValid').and.returnValue(observableOf(false));
spyOn(compAsAny, 'initModelsValue').and.callThrough();
spyOn(compAsAny, 'buildResourcePolicyForm').and.callThrough();
@@ -261,12 +264,12 @@ describe('ResourcePolicyFormComponent test suite', () => {
expect(compAsAny.buildResourcePolicyForm).toHaveBeenCalled();
expect(compAsAny.initModelsValue).toHaveBeenCalled();
expect(compAsAny.formModel.length).toBe(5);
expect(compAsAny.subs.length).toBe(0);
expect(compAsAny.subs.length).toBe(1);
});
it('should can set grant', () => {
expect(comp.canSetGrant()).toBeTruthy();
expect(comp.isBeingEdited()).toBeTruthy();
});
it('should not have a target name', () => {
@@ -279,7 +282,7 @@ describe('ResourcePolicyFormComponent test suite', () => {
expect(compAsAny.reset.emit).toHaveBeenCalled();
});
it('should update resource policy grant object properly', () => {
it('should update resource policy grant object properly', () => {
comp.updateObjectSelected(EPersonMock, true);
expect(comp.resourcePolicyGrant).toEqual(EPersonMock);
@@ -301,6 +304,7 @@ describe('ResourcePolicyFormComponent test suite', () => {
comp = fixture.componentInstance;
compAsAny = fixture.componentInstance;
comp.resourcePolicy = resourcePolicy;
compAsAny.resourcePolicy = resourcePolicy;
comp.isProcessing = observableOf(false);
compAsAny.ePersonService.findByHref.and.returnValue(
observableOf(createSuccessfulRemoteDataObject({})).pipe(delay(100))
@@ -343,8 +347,8 @@ describe('ResourcePolicyFormComponent test suite', () => {
});
});
it('should not can set grant', () => {
expect(comp.canSetGrant()).toBeFalsy();
it('should be being edited', () => {
expect(comp.isBeingEdited()).toBeTrue();
});
it('should have a target name', () => {
@@ -398,6 +402,7 @@ describe('ResourcePolicyFormComponent test suite', () => {
type: 'group',
uuid: GroupMock.id
};
eventPayload.updateTarget = false;
scheduler = getTestScheduler();
scheduler.schedule(() => comp.onSubmit());

View File

@@ -1,4 +1,4 @@
import { Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core';
import { Component, ElementRef, EventEmitter, Input, OnDestroy, OnInit, Output, ViewChild } from '@angular/core';
import {
Observable,
@@ -41,6 +41,7 @@ import { EPersonDataService } from '../../../core/eperson/eperson-data.service';
import { GroupDataService } from '../../../core/eperson/group-data.service';
import { getFirstSucceededRemoteData } from '../../../core/shared/operators';
import { RequestService } from '../../../core/data/request.service';
import { NgbModal, NgbNavChangeEvent } from '@ng-bootstrap/ng-bootstrap';
export interface ResourcePolicyEvent {
object: ResourcePolicy;
@@ -48,6 +49,7 @@ export interface ResourcePolicyEvent {
type: string,
uuid: string
};
updateTarget: boolean;
}
@Component({
@@ -83,6 +85,8 @@ export class ResourcePolicyFormComponent implements OnInit, OnDestroy {
*/
@Output() submit: EventEmitter<ResourcePolicyEvent> = new EventEmitter<ResourcePolicyEvent>();
@ViewChild('content') content: ElementRef;
/**
* The form id
* @type {string}
@@ -125,6 +129,10 @@ export class ResourcePolicyFormComponent implements OnInit, OnDestroy {
*/
private subs: Subscription[] = [];
navActiveId: string;
resourcePolicyTargetUpdated = false;
/**
* Initialize instance variables
*
@@ -133,6 +141,7 @@ export class ResourcePolicyFormComponent implements OnInit, OnDestroy {
* @param {FormService} formService
* @param {GroupDataService} groupService
* @param {RequestService} requestService
* @param modalService
*/
constructor(
private dsoNameService: DSONameService,
@@ -140,6 +149,7 @@ export class ResourcePolicyFormComponent implements OnInit, OnDestroy {
private formService: FormService,
private groupService: GroupDataService,
private requestService: RequestService,
private modalService: NgbModal,
) {
}
@@ -151,7 +161,7 @@ export class ResourcePolicyFormComponent implements OnInit, OnDestroy {
this.formId = this.formService.getUniqueId('resource-policy-form');
this.formModel = this.buildResourcePolicyForm();
if (!this.canSetGrant()) {
if (this.isBeingEdited()) {
const epersonRD$ = this.ePersonService.findByHref(this.resourcePolicy._links.eperson.href, false).pipe(
getFirstSucceededRemoteData()
);
@@ -169,6 +179,7 @@ export class ResourcePolicyFormComponent implements OnInit, OnDestroy {
filter(() => this.isActive),
).subscribe((dsoRD: RemoteData<DSpaceObject>) => {
this.resourcePolicyGrant = dsoRD.payload;
this.navActiveId = String(dsoRD.payload.type);
this.resourcePolicyTargetName$.next(this.getResourcePolicyTargetName());
})
);
@@ -193,19 +204,12 @@ export class ResourcePolicyFormComponent implements OnInit, OnDestroy {
*/
private buildResourcePolicyForm(): DynamicFormControlModel[] {
const formModel: DynamicFormControlModel[] = [];
// TODO to be removed when https://jira.lyrasis.org/browse/DS-4477 will be implemented
const policyTypeConf = Object.assign({}, RESOURCE_POLICY_FORM_POLICY_TYPE_CONFIG, {
disabled: isNotEmpty(this.resourcePolicy)
});
// TODO to be removed when https://jira.lyrasis.org/browse/DS-4477 will be implemented
const actionConf = Object.assign({}, RESOURCE_POLICY_FORM_ACTION_TYPE_CONFIG, {
disabled: isNotEmpty(this.resourcePolicy)
});
formModel.push(
new DsDynamicInputModel(RESOURCE_POLICY_FORM_NAME_CONFIG),
new DsDynamicTextAreaModel(RESOURCE_POLICY_FORM_DESCRIPTION_CONFIG),
new DynamicSelectModel(policyTypeConf),
new DynamicSelectModel(actionConf)
new DynamicSelectModel(RESOURCE_POLICY_FORM_POLICY_TYPE_CONFIG),
new DynamicSelectModel(RESOURCE_POLICY_FORM_ACTION_TYPE_CONFIG)
);
const startDateModel = new DynamicDatePickerModel(
@@ -255,8 +259,8 @@ export class ResourcePolicyFormComponent implements OnInit, OnDestroy {
*
* @return true if is possible, false otherwise
*/
canSetGrant(): boolean {
return isEmpty(this.resourcePolicy);
isBeingEdited(): boolean {
return !isEmpty(this.resourcePolicy);
}
/**
@@ -272,8 +276,10 @@ export class ResourcePolicyFormComponent implements OnInit, OnDestroy {
* Update reference to the eperson or group that will be granted the permission
*/
updateObjectSelected(object: DSpaceObject, isEPerson: boolean): void {
this.resourcePolicyTargetUpdated = true;
this.resourcePolicyGrant = object;
this.resourcePolicyGrantType = isEPerson ? 'eperson' : 'group';
this.resourcePolicyTargetName$.next(this.getResourcePolicyTargetName());
}
/**
@@ -297,6 +303,7 @@ export class ResourcePolicyFormComponent implements OnInit, OnDestroy {
type: this.resourcePolicyGrantType,
uuid: this.resourcePolicyGrant.id
};
eventPayload.updateTarget = this.resourcePolicyTargetUpdated;
this.submit.emit(eventPayload);
});
}
@@ -329,4 +336,12 @@ export class ResourcePolicyFormComponent implements OnInit, OnDestroy {
.filter((subscription) => hasValue(subscription))
.forEach((subscription) => subscription.unsubscribe());
}
onNavChange(changeEvent: NgbNavChangeEvent) {
// if a policy is being edited it should not be possible to switch between group and eperson
if (this.isBeingEdited()) {
changeEvent.preventDefault();
this.modalService.open(this.content);
}
}
}

View File

@@ -3161,6 +3161,10 @@
"resource-policies.edit.page.failure.content": "An error occurred while editing the resource policy.",
"resource-policies.edit.page.target-failure.content": "An error occurred while editing the target (ePerson or group) of the resource policy.",
"resource-policies.edit.page.other-failure.content": "An error occurred while editing the resource policy. The target (ePerson or group) has been successfully updated.",
"resource-policies.edit.page.success.content": "Operation successful",
"resource-policies.edit.page.title": "Edit resource policy",
@@ -3183,6 +3187,16 @@
"resource-policies.form.eperson-group-list.table.headers.name": "Name",
"resource-policies.form.eperson-group-list.modal.header": "Cannot change type",
"resource-policies.form.eperson-group-list.modal.text1.toGroup": "It is not possible to replace an ePerson with a group.",
"resource-policies.form.eperson-group-list.modal.text1.toEPerson": "It is not possible to replace a group with an ePerson.",
"resource-policies.form.eperson-group-list.modal.text2": "Delete the current resource policy and create a new one with the desired type.",
"resource-policies.form.eperson-group-list.modal.close": "Ok",
"resource-policies.form.date.end.label": "End Date",
"resource-policies.form.date.start.label": "Start Date",