mirror of
https://github.com/DSpace/dspace-angular.git
synced 2025-10-17 23:13:04 +00:00
Merge remote-tracking branch 'origin/main' into more-eslint
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
<div class="container">
|
||||
<h1>{{ 'admin.access-control.bulk-access.title' | translate }}</h1>
|
||||
<ds-bulk-access-browse [listId]="listId"></ds-bulk-access-browse>
|
||||
<div class="clearfix mb-3"></div>
|
||||
<ds-bulk-access-settings #dsBulkSettings ></ds-bulk-access-settings>
|
||||
|
@@ -1,41 +1,16 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import {
|
||||
DebugElement,
|
||||
NO_ERRORS_SCHEMA,
|
||||
} from '@angular/core';
|
||||
import {
|
||||
ComponentFixture,
|
||||
fakeAsync,
|
||||
TestBed,
|
||||
tick,
|
||||
waitForAsync,
|
||||
} from '@angular/core/testing';
|
||||
import {
|
||||
FormsModule,
|
||||
ReactiveFormsModule,
|
||||
} from '@angular/forms';
|
||||
import {
|
||||
BrowserModule,
|
||||
By,
|
||||
} from '@angular/platform-browser';
|
||||
import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
import { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing';
|
||||
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
|
||||
import { BrowserModule, By } from '@angular/platform-browser';
|
||||
import { Router } from '@angular/router';
|
||||
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
|
||||
import {
|
||||
TranslateLoader,
|
||||
TranslateModule,
|
||||
TranslateService,
|
||||
} from '@ngx-translate/core';
|
||||
import {
|
||||
Observable,
|
||||
of as observableOf,
|
||||
} from 'rxjs';
|
||||
import { NgbModal, NgbModule } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
import { Observable, of as observableOf } from 'rxjs';
|
||||
|
||||
import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service';
|
||||
import { FindListOptions } from '../../core/data/find-list-options.model';
|
||||
import {
|
||||
buildPaginatedList,
|
||||
PaginatedList,
|
||||
} from '../../core/data/paginated-list.model';
|
||||
import { buildPaginatedList, PaginatedList } from '../../core/data/paginated-list.model';
|
||||
import { RemoteData } from '../../core/data/remote-data';
|
||||
import { RequestService } from '../../core/data/request.service';
|
||||
import { EPersonDataService } from '../../core/eperson/eperson-data.service';
|
||||
@@ -44,14 +19,9 @@ import { PaginationService } from '../../core/pagination/pagination.service';
|
||||
import { PageInfo } from '../../core/shared/page-info.model';
|
||||
import { FormBuilderService } from '../../shared/form/builder/form-builder.service';
|
||||
import { getMockFormBuilderService } from '../../shared/mocks/form-builder-service.mock';
|
||||
import { getMockTranslateService } from '../../shared/mocks/translate.service.mock';
|
||||
import { TranslateLoaderMock } from '../../shared/mocks/translate-loader.mock';
|
||||
import { NotificationsService } from '../../shared/notifications/notifications.service';
|
||||
import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
|
||||
import {
|
||||
EPersonMock,
|
||||
EPersonMock2,
|
||||
} from '../../shared/testing/eperson.mock';
|
||||
import { EPersonMock, EPersonMock2 } from '../../shared/testing/eperson.mock';
|
||||
import { NotificationsServiceStub } from '../../shared/testing/notifications-service.stub';
|
||||
import { PaginationServiceStub } from '../../shared/testing/pagination-service.stub';
|
||||
import { RouterStub } from '../../shared/testing/router.stub';
|
||||
@@ -60,17 +30,15 @@ import { EPeopleRegistryComponent } from './epeople-registry.component';
|
||||
describe('EPeopleRegistryComponent', () => {
|
||||
let component: EPeopleRegistryComponent;
|
||||
let fixture: ComponentFixture<EPeopleRegistryComponent>;
|
||||
let translateService: TranslateService;
|
||||
let builderService: FormBuilderService;
|
||||
|
||||
let mockEPeople;
|
||||
let mockEPeople: EPerson[];
|
||||
let ePersonDataServiceStub: any;
|
||||
let authorizationService: AuthorizationDataService;
|
||||
let modalService;
|
||||
let modalService: NgbModal;
|
||||
let paginationService: PaginationServiceStub;
|
||||
|
||||
let paginationService;
|
||||
|
||||
beforeEach(waitForAsync(() => {
|
||||
beforeEach(waitForAsync(async () => {
|
||||
jasmine.getEnv().allowRespy(true);
|
||||
mockEPeople = [EPersonMock, EPersonMock2];
|
||||
ePersonDataServiceStub = {
|
||||
@@ -148,17 +116,11 @@ describe('EPeopleRegistryComponent', () => {
|
||||
isAuthorized: observableOf(true),
|
||||
});
|
||||
builderService = getMockFormBuilderService();
|
||||
translateService = getMockTranslateService();
|
||||
|
||||
paginationService = new PaginationServiceStub();
|
||||
TestBed.configureTestingModule({
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule,
|
||||
TranslateModule.forRoot({
|
||||
loader: {
|
||||
provide: TranslateLoader,
|
||||
useClass: TranslateLoaderMock,
|
||||
},
|
||||
}),
|
||||
TranslateModule.forRoot(),
|
||||
],
|
||||
declarations: [EPeopleRegistryComponent],
|
||||
providers: [
|
||||
@@ -177,7 +139,7 @@ describe('EPeopleRegistryComponent', () => {
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(EPeopleRegistryComponent);
|
||||
component = fixture.componentInstance;
|
||||
modalService = (component as any).modalService;
|
||||
modalService = TestBed.inject(NgbModal);
|
||||
spyOn(modalService, 'open').and.returnValue(Object.assign({ componentInstance: Object.assign({ response: observableOf(true) }) }));
|
||||
fixture.detectChanges();
|
||||
});
|
||||
@@ -187,10 +149,10 @@ describe('EPeopleRegistryComponent', () => {
|
||||
});
|
||||
|
||||
it('should display list of ePeople', () => {
|
||||
const ePeopleIdsFound = fixture.debugElement.queryAll(By.css('#epeople tr td:first-child'));
|
||||
const ePeopleIdsFound: DebugElement[] = fixture.debugElement.queryAll(By.css('#epeople tr td:first-child'));
|
||||
expect(ePeopleIdsFound.length).toEqual(2);
|
||||
mockEPeople.map((ePerson: EPerson) => {
|
||||
expect(ePeopleIdsFound.find((foundEl) => {
|
||||
expect(ePeopleIdsFound.find((foundEl: DebugElement) => {
|
||||
return (foundEl.nativeElement.textContent.trim() === ePerson.uuid);
|
||||
})).toBeTruthy();
|
||||
});
|
||||
@@ -198,7 +160,7 @@ describe('EPeopleRegistryComponent', () => {
|
||||
|
||||
describe('search', () => {
|
||||
describe('when searching with scope/query (scope metadata)', () => {
|
||||
let ePeopleIdsFound;
|
||||
let ePeopleIdsFound: DebugElement[];
|
||||
beforeEach(fakeAsync(() => {
|
||||
component.search({ scope: 'metadata', query: EPersonMock2.name });
|
||||
tick();
|
||||
@@ -208,14 +170,14 @@ describe('EPeopleRegistryComponent', () => {
|
||||
|
||||
it('should display search result', () => {
|
||||
expect(ePeopleIdsFound.length).toEqual(1);
|
||||
expect(ePeopleIdsFound.find((foundEl) => {
|
||||
expect(ePeopleIdsFound.find((foundEl: DebugElement) => {
|
||||
return (foundEl.nativeElement.textContent.trim() === EPersonMock2.uuid);
|
||||
})).toBeTruthy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('when searching with scope/query (scope email)', () => {
|
||||
let ePeopleIdsFound;
|
||||
let ePeopleIdsFound: DebugElement[];
|
||||
beforeEach(fakeAsync(() => {
|
||||
component.search({ scope: 'email', query: EPersonMock.email });
|
||||
tick();
|
||||
@@ -225,7 +187,7 @@ describe('EPeopleRegistryComponent', () => {
|
||||
|
||||
it('should display search result', () => {
|
||||
expect(ePeopleIdsFound.length).toEqual(1);
|
||||
expect(ePeopleIdsFound.find((foundEl) => {
|
||||
expect(ePeopleIdsFound.find((foundEl: DebugElement) => {
|
||||
return (foundEl.nativeElement.textContent.trim() === EPersonMock.uuid);
|
||||
})).toBeTruthy();
|
||||
});
|
||||
@@ -257,19 +219,12 @@ describe('EPeopleRegistryComponent', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete EPerson button when the isAuthorized returns false', () => {
|
||||
let ePeopleDeleteButton;
|
||||
beforeEach(() => {
|
||||
spyOn(authorizationService, 'isAuthorized').and.returnValue(observableOf(false));
|
||||
component.initialisePage();
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should be disabled', () => {
|
||||
ePeopleDeleteButton = fixture.debugElement.queryAll(By.css('#epeople tr td div button.delete-button'));
|
||||
ePeopleDeleteButton.forEach((deleteButton: DebugElement) => {
|
||||
expect(deleteButton.nativeElement.disabled).toBe(true);
|
||||
});
|
||||
});
|
||||
it('should hide delete EPerson button when the isAuthorized returns false', () => {
|
||||
spyOn(authorizationService, 'isAuthorized').and.returnValue(observableOf(false));
|
||||
component.initialisePage();
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(fixture.debugElement.query(By.css('#epeople tr td div button.delete-button'))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
@@ -1,31 +1,15 @@
|
||||
import {
|
||||
Component,
|
||||
OnDestroy,
|
||||
OnInit,
|
||||
} from '@angular/core';
|
||||
import { Component, OnDestroy, OnInit } from '@angular/core';
|
||||
import { UntypedFormBuilder } from '@angular/forms';
|
||||
import { Router } from '@angular/router';
|
||||
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
import {
|
||||
BehaviorSubject,
|
||||
combineLatest,
|
||||
Observable,
|
||||
Subscription,
|
||||
} from 'rxjs';
|
||||
import {
|
||||
map,
|
||||
switchMap,
|
||||
take,
|
||||
} from 'rxjs/operators';
|
||||
import { BehaviorSubject, combineLatest, Observable, Subscription } from 'rxjs';
|
||||
import { map, switchMap, take } from 'rxjs/operators';
|
||||
|
||||
import { DSONameService } from '../../core/breadcrumbs/dso-name.service';
|
||||
import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service';
|
||||
import { FeatureID } from '../../core/data/feature-authorization/feature-id';
|
||||
import {
|
||||
buildPaginatedList,
|
||||
PaginatedList,
|
||||
} from '../../core/data/paginated-list.model';
|
||||
import { buildPaginatedList, PaginatedList } from '../../core/data/paginated-list.model';
|
||||
import { RemoteData } from '../../core/data/remote-data';
|
||||
import { RequestService } from '../../core/data/request.service';
|
||||
import { EPersonDataService } from '../../core/eperson/eperson-data.service';
|
||||
@@ -33,19 +17,13 @@ import { EPerson } from '../../core/eperson/models/eperson.model';
|
||||
import { EpersonDtoModel } from '../../core/eperson/models/eperson-dto.model';
|
||||
import { PaginationService } from '../../core/pagination/pagination.service';
|
||||
import { NoContent } from '../../core/shared/NoContent.model';
|
||||
import {
|
||||
getAllSucceededRemoteData,
|
||||
getFirstCompletedRemoteData,
|
||||
} from '../../core/shared/operators';
|
||||
import { getAllSucceededRemoteData, getFirstCompletedRemoteData } from '../../core/shared/operators';
|
||||
import { PageInfo } from '../../core/shared/page-info.model';
|
||||
import { ConfirmationModalComponent } from '../../shared/confirmation-modal/confirmation-modal.component';
|
||||
import { hasValue } from '../../shared/empty.util';
|
||||
import { NotificationsService } from '../../shared/notifications/notifications.service';
|
||||
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
|
||||
import {
|
||||
getEPersonEditRoute,
|
||||
getEPersonsRoute,
|
||||
} from '../access-control-routing-paths';
|
||||
import { getEPersonEditRoute, getEPersonsRoute } from '../access-control-routing-paths';
|
||||
|
||||
@Component({
|
||||
selector: 'ds-epeople-registry',
|
||||
@@ -224,7 +202,7 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
|
||||
deleteEPerson(ePerson: EPerson) {
|
||||
if (hasValue(ePerson.id)) {
|
||||
const modalRef = this.modalService.open(ConfirmationModalComponent);
|
||||
modalRef.componentInstance.dso = ePerson;
|
||||
modalRef.componentInstance.name = this.dsoNameService.getName(ePerson);
|
||||
modalRef.componentInstance.headerLabel = 'confirmation-modal.delete-eperson.header';
|
||||
modalRef.componentInstance.infoLabel = 'confirmation-modal.delete-eperson.info';
|
||||
modalRef.componentInstance.cancelLabel = 'confirmation-modal.delete-eperson.cancel';
|
||||
|
@@ -1,37 +1,11 @@
|
||||
import {
|
||||
ChangeDetectorRef,
|
||||
Component,
|
||||
EventEmitter,
|
||||
OnDestroy,
|
||||
OnInit,
|
||||
Output,
|
||||
} from '@angular/core';
|
||||
import { ChangeDetectorRef, Component, EventEmitter, OnDestroy, OnInit, Output } from '@angular/core';
|
||||
import { UntypedFormGroup } from '@angular/forms';
|
||||
import {
|
||||
ActivatedRoute,
|
||||
Router,
|
||||
} from '@angular/router';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
|
||||
import {
|
||||
DynamicCheckboxModel,
|
||||
DynamicFormControlModel,
|
||||
DynamicFormLayout,
|
||||
DynamicInputModel,
|
||||
} from '@ng-dynamic-forms/core';
|
||||
import { DynamicCheckboxModel, DynamicFormControlModel, DynamicFormLayout, DynamicInputModel } from '@ng-dynamic-forms/core';
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
import {
|
||||
combineLatest as observableCombineLatest,
|
||||
Observable,
|
||||
of as observableOf,
|
||||
Subscription,
|
||||
} from 'rxjs';
|
||||
import {
|
||||
debounceTime,
|
||||
finalize,
|
||||
map,
|
||||
switchMap,
|
||||
take,
|
||||
} from 'rxjs/operators';
|
||||
import { combineLatest as observableCombineLatest, Observable, of as observableOf, Subscription } from 'rxjs';
|
||||
import { debounceTime, finalize, map, switchMap, take } from 'rxjs/operators';
|
||||
|
||||
import { AuthService } from '../../../core/auth/auth.service';
|
||||
import { DSONameService } from '../../../core/breadcrumbs/dso-name.service';
|
||||
@@ -47,11 +21,7 @@ import { EPerson } from '../../../core/eperson/models/eperson.model';
|
||||
import { Group } from '../../../core/eperson/models/group.model';
|
||||
import { PaginationService } from '../../../core/pagination/pagination.service';
|
||||
import { NoContent } from '../../../core/shared/NoContent.model';
|
||||
import {
|
||||
getFirstCompletedRemoteData,
|
||||
getFirstSucceededRemoteData,
|
||||
getRemoteDataPayload,
|
||||
} from '../../../core/shared/operators';
|
||||
import { getFirstCompletedRemoteData, getFirstSucceededRemoteData, getRemoteDataPayload } from '../../../core/shared/operators';
|
||||
import { PageInfo } from '../../../core/shared/page-info.model';
|
||||
import { Registration } from '../../../core/shared/registration.model';
|
||||
import { TYPE_REQUEST_FORGOT } from '../../../register-email-form/register-email-form.component';
|
||||
@@ -510,7 +480,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
|
||||
take(1),
|
||||
switchMap((eperson: EPerson) => {
|
||||
const modalRef = this.modalService.open(ConfirmationModalComponent);
|
||||
modalRef.componentInstance.dso = eperson;
|
||||
modalRef.componentInstance.name = this.dsoNameService.getName(eperson);
|
||||
modalRef.componentInstance.headerLabel = 'confirmation-modal.delete-eperson.header';
|
||||
modalRef.componentInstance.infoLabel = 'confirmation-modal.delete-eperson.info';
|
||||
modalRef.componentInstance.cancelLabel = 'confirmation-modal.delete-eperson.cancel';
|
||||
|
@@ -1,40 +1,12 @@
|
||||
import {
|
||||
ChangeDetectorRef,
|
||||
Component,
|
||||
EventEmitter,
|
||||
HostListener,
|
||||
OnDestroy,
|
||||
OnInit,
|
||||
Output,
|
||||
} from '@angular/core';
|
||||
import { ChangeDetectorRef, Component, EventEmitter, HostListener, OnDestroy, OnInit, Output } from '@angular/core';
|
||||
import { UntypedFormGroup } from '@angular/forms';
|
||||
import {
|
||||
ActivatedRoute,
|
||||
Router,
|
||||
} from '@angular/router';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
|
||||
import {
|
||||
DynamicFormControlModel,
|
||||
DynamicFormLayout,
|
||||
DynamicInputModel,
|
||||
DynamicTextAreaModel,
|
||||
} from '@ng-dynamic-forms/core';
|
||||
import { DynamicFormControlModel, DynamicFormLayout, DynamicInputModel, DynamicTextAreaModel } from '@ng-dynamic-forms/core';
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
import { Operation } from 'fast-json-patch';
|
||||
import {
|
||||
combineLatest as observableCombineLatest,
|
||||
Observable,
|
||||
of as observableOf,
|
||||
Subscription,
|
||||
} from 'rxjs';
|
||||
import {
|
||||
catchError,
|
||||
debounceTime,
|
||||
filter,
|
||||
map,
|
||||
switchMap,
|
||||
take,
|
||||
} from 'rxjs/operators';
|
||||
import { combineLatest as observableCombineLatest, Observable, of as observableOf, Subscription } from 'rxjs';
|
||||
import { catchError, debounceTime, filter, map, switchMap, take } from 'rxjs/operators';
|
||||
|
||||
import { environment } from '../../../../environments/environment';
|
||||
import { getCollectionEditRolesRoute } from '../../../collection-page/collection-page-routing-paths';
|
||||
@@ -53,26 +25,14 @@ import { Collection } from '../../../core/shared/collection.model';
|
||||
import { Community } from '../../../core/shared/community.model';
|
||||
import { DSpaceObject } from '../../../core/shared/dspace-object.model';
|
||||
import { NoContent } from '../../../core/shared/NoContent.model';
|
||||
import {
|
||||
getFirstCompletedRemoteData,
|
||||
getFirstSucceededRemoteData,
|
||||
getFirstSucceededRemoteDataPayload,
|
||||
getRemoteDataPayload,
|
||||
} from '../../../core/shared/operators';
|
||||
import { getFirstCompletedRemoteData, getFirstSucceededRemoteData, getFirstSucceededRemoteDataPayload, getRemoteDataPayload } from '../../../core/shared/operators';
|
||||
import { AlertType } from '../../../shared/alert/alert-type';
|
||||
import { ConfirmationModalComponent } from '../../../shared/confirmation-modal/confirmation-modal.component';
|
||||
import {
|
||||
hasValue,
|
||||
hasValueOperator,
|
||||
isNotEmpty,
|
||||
} from '../../../shared/empty.util';
|
||||
import { hasValue, hasValueOperator, isNotEmpty } from '../../../shared/empty.util';
|
||||
import { FormBuilderService } from '../../../shared/form/builder/form-builder.service';
|
||||
import { NotificationsService } from '../../../shared/notifications/notifications.service';
|
||||
import { followLink } from '../../../shared/utils/follow-link-config.model';
|
||||
import {
|
||||
getGroupEditRoute,
|
||||
getGroupsRoute,
|
||||
} from '../../access-control-routing-paths';
|
||||
import { getGroupEditRoute, getGroupsRoute } from '../../access-control-routing-paths';
|
||||
import { ValidateGroupExists } from './validators/group-exists.validator';
|
||||
|
||||
@Component({
|
||||
@@ -446,7 +406,7 @@ export class GroupFormComponent implements OnInit, OnDestroy {
|
||||
delete() {
|
||||
this.groupDataService.getActiveGroup().pipe(take(1)).subscribe((group: Group) => {
|
||||
const modalRef = this.modalService.open(ConfirmationModalComponent);
|
||||
modalRef.componentInstance.dso = group;
|
||||
modalRef.componentInstance.name = this.dsoNameService.getName(group);
|
||||
modalRef.componentInstance.headerLabel = this.messagePrefix + '.delete-group.modal.header';
|
||||
modalRef.componentInstance.infoLabel = this.messagePrefix + '.delete-group.modal.info';
|
||||
modalRef.componentInstance.cancelLabel = this.messagePrefix + '.delete-group.modal.cancel';
|
||||
|
@@ -1,5 +1,5 @@
|
||||
<div class="container">
|
||||
<h2 id="header">{{'admin.batch-import.page.header' | translate}}</h2>
|
||||
<h1 id="header">{{'admin.batch-import.page.header' | translate}}</h1>
|
||||
<p>{{'admin.batch-import.page.help' | translate}}</p>
|
||||
<p *ngIf="dso">
|
||||
selected collection: <b>{{getDspaceObjectName()}}</b>
|
||||
@@ -28,7 +28,7 @@
|
||||
<small class="form-text text-muted">
|
||||
{{'admin.batch-import.page.toggle.help' | translate}}
|
||||
</small>
|
||||
|
||||
|
||||
|
||||
<ds-file-dropzone-no-uploader
|
||||
*ngIf="isUpload"
|
||||
|
@@ -0,0 +1,46 @@
|
||||
import { NgModule } from '@angular/core';
|
||||
import { RouterModule, Routes } from '@angular/router';
|
||||
import { LdnServicesOverviewComponent } from './ldn-services-directory/ldn-services-directory.component';
|
||||
import { NavigationBreadcrumbResolver } from '../../core/breadcrumbs/navigation-breadcrumb.resolver';
|
||||
import { I18nBreadcrumbResolver } from '../../core/breadcrumbs/i18n-breadcrumb.resolver';
|
||||
import { LdnServiceFormComponent } from './ldn-service-form/ldn-service-form.component';
|
||||
|
||||
const moduleRoutes: Routes = [
|
||||
{
|
||||
path: '',
|
||||
pathMatch: 'full',
|
||||
component: LdnServicesOverviewComponent,
|
||||
resolve: {breadcrumb: I18nBreadcrumbResolver},
|
||||
data: {title: 'ldn-registered-services.title', breadcrumbKey: 'ldn-registered-services.new'},
|
||||
},
|
||||
{
|
||||
path: 'new',
|
||||
resolve: {breadcrumb: NavigationBreadcrumbResolver},
|
||||
component: LdnServiceFormComponent,
|
||||
data: {title: 'ldn-register-new-service.title', breadcrumbKey: 'ldn-register-new-service'}
|
||||
},
|
||||
{
|
||||
path: 'edit/:serviceId',
|
||||
resolve: {breadcrumb: NavigationBreadcrumbResolver},
|
||||
component: LdnServiceFormComponent,
|
||||
data: {title: 'ldn-edit-service.title', breadcrumbKey: 'ldn-edit-service'}
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
RouterModule.forChild(moduleRoutes.map(route => {
|
||||
return {...route, data: {
|
||||
...route.data,
|
||||
relatedRoutes: moduleRoutes.filter(relatedRoute => relatedRoute.path !== route.path)
|
||||
.map((relatedRoute) => {
|
||||
return {path: relatedRoute.path, data: relatedRoute.data};
|
||||
})
|
||||
}};
|
||||
}))
|
||||
]
|
||||
})
|
||||
export class AdminLdnServicesRoutingModule {
|
||||
|
||||
}
|
@@ -0,0 +1,24 @@
|
||||
import { NgModule } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { AdminLdnServicesRoutingModule } from './admin-ldn-services-routing.module';
|
||||
import { LdnServicesOverviewComponent } from './ldn-services-directory/ldn-services-directory.component';
|
||||
import { SharedModule } from '../../shared/shared.module';
|
||||
import { LdnServiceFormComponent } from './ldn-service-form/ldn-service-form.component';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { LdnItemfiltersService } from './ldn-services-data/ldn-itemfilters-data.service';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
CommonModule,
|
||||
SharedModule,
|
||||
AdminLdnServicesRoutingModule,
|
||||
FormsModule
|
||||
],
|
||||
declarations: [
|
||||
LdnServicesOverviewComponent,
|
||||
LdnServiceFormComponent,
|
||||
],
|
||||
providers: [LdnItemfiltersService]
|
||||
})
|
||||
export class AdminLdnServicesModule {
|
||||
}
|
@@ -0,0 +1,315 @@
|
||||
<div class="container">
|
||||
<form (ngSubmit)="onSubmit()" [formGroup]="formModel">
|
||||
<div class="d-flex">
|
||||
<h1 class="flex-grow-1">{{ isNewService ? ('ldn-create-service.title' | translate) : ('ldn-edit-registered-service.title' | translate) }}</h1>
|
||||
</div>
|
||||
<!-- In the toggle section -->
|
||||
<div class="toggle-switch-container" *ngIf="!isNewService">
|
||||
<label class="status-label font-weight-bold" for="enabled">{{ 'ldn-service-status' | translate }}</label>
|
||||
<div>
|
||||
<input formControlName="enabled" hidden id="enabled" name="enabled" type="checkbox">
|
||||
<div (click)="toggleEnabled()" [class.checked]="formModel.get('enabled').value" class="toggle-switch">
|
||||
<div class="slider"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- In the Name section -->
|
||||
<div class="mb-5">
|
||||
<label for="name" class="font-weight-bold">{{ 'ldn-new-service.form.label.name' | translate }}</label>
|
||||
<input [class.invalid-field]="formModel.get('name').invalid && formModel.get('name').touched"
|
||||
[placeholder]="'ldn-new-service.form.placeholder.name' | translate" class="form-control"
|
||||
formControlName="name"
|
||||
id="name"
|
||||
name="name"
|
||||
type="text">
|
||||
<div *ngIf="formModel.get('name').invalid && formModel.get('name').touched" class="error-text">
|
||||
{{ 'ldn-new-service.form.error.name' | translate }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- In the description section -->
|
||||
<div class="mb-5 mt-5 d-flex flex-column">
|
||||
<label for="description" class="font-weight-bold">{{ 'ldn-new-service.form.label.description' | translate }}</label>
|
||||
<textarea [placeholder]="'ldn-new-service.form.placeholder.description' | translate"
|
||||
class="form-control" formControlName="description" id="description" name="description"></textarea>
|
||||
</div>
|
||||
|
||||
<div class="mb-5 mt-5">
|
||||
<!-- In the url section -->
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="d-flex flex-column w-50 mr-2">
|
||||
<label for="url" class="font-weight-bold">{{ 'ldn-new-service.form.label.url' | translate }}</label>
|
||||
<input [class.invalid-field]="formModel.get('url').invalid && formModel.get('url').touched"
|
||||
[placeholder]="'ldn-new-service.form.placeholder.url' | translate" class="form-control"
|
||||
formControlName="url"
|
||||
id="url"
|
||||
name="url"
|
||||
type="text">
|
||||
<div *ngIf="formModel.get('url').invalid && formModel.get('url').touched" class="error-text">
|
||||
{{ 'ldn-new-service.form.error.url' | translate }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex flex-column w-50">
|
||||
<label for="score" class="font-weight-bold">{{ 'ldn-new-service.form.label.score' | translate }}</label>
|
||||
<input [class.invalid-field]="formModel.get('score').invalid && formModel.get('score').touched"
|
||||
[placeholder]="'ldn-new-service.form.placeholder.score' | translate" formControlName="score"
|
||||
id="score"
|
||||
name="score"
|
||||
min="0"
|
||||
max="1"
|
||||
step=".01"
|
||||
class="form-control"
|
||||
type="number">
|
||||
<div *ngIf="formModel.get('score').invalid && formModel.get('score').touched" class="error-text">
|
||||
{{ 'ldn-new-service.form.error.score' | translate }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- In the IP range section -->
|
||||
<div class="mb-5 mt-5">
|
||||
<label for="lowerIp" class="font-weight-bold">{{ 'ldn-new-service.form.label.ip-range' | translate }}</label>
|
||||
<div class="d-flex">
|
||||
<input [class.invalid-field]="formModel.get('lowerIp').invalid && formModel.get('lowerIp').touched"
|
||||
[placeholder]="'ldn-new-service.form.placeholder.lowerIp' | translate" class="form-control mr-2"
|
||||
formControlName="lowerIp"
|
||||
id="lowerIp"
|
||||
name="lowerIp"
|
||||
type="text">
|
||||
<input [class.invalid-field]="formModel.get('upperIp').invalid && formModel.get('upperIp').touched"
|
||||
[placeholder]="'ldn-new-service.form.placeholder.upperIp' | translate" class="form-control"
|
||||
formControlName="upperIp"
|
||||
id="upperIp"
|
||||
name="upperIp"
|
||||
type="text">
|
||||
</div>
|
||||
<div *ngIf="(formModel.get('lowerIp').invalid && formModel.get('lowerIp').touched) || (formModel.get('upperIp').invalid && formModel.get('upperIp').touched)" class="error-text">
|
||||
{{ 'ldn-new-service.form.error.ipRange' | translate }}
|
||||
</div>
|
||||
<div class="text-muted">
|
||||
{{ 'ldn-new-service.form.hint.ipRange' | translate }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- In the ldnUrl section -->
|
||||
<div class="mb-5 mt-5">
|
||||
<label for="ldnUrl" class="font-weight-bold">{{ 'ldn-new-service.form.label.ldnUrl' | translate }}</label>
|
||||
<input [class.invalid-field]="formModel.get('ldnUrl').invalid && formModel.get('ldnUrl').touched"
|
||||
[placeholder]="'ldn-new-service.form.placeholder.ldnUrl' | translate" class="form-control"
|
||||
formControlName="ldnUrl"
|
||||
id="ldnUrl"
|
||||
name="ldnUrl"
|
||||
type="text">
|
||||
<div *ngIf="formModel.get('ldnUrl').invalid && formModel.get('ldnUrl').touched" >
|
||||
<div *ngIf="formModel.get('ldnUrl').errors['required']" class="error-text">
|
||||
{{ 'ldn-new-service.form.error.ldnurl' | translate }}
|
||||
</div>
|
||||
<div *ngIf="formModel.get('ldnUrl').errors['ldnUrlAlreadyAssociated']" class="error-text">
|
||||
{{ 'ldn-new-service.form.error.ldnurl.ldnUrlAlreadyAssociated' | translate }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- In the Inbound Patterns Labels section -->
|
||||
<div class="row mb-1 mt-5" *ngIf="areControlsInitialized">
|
||||
<div class="col">
|
||||
<label class="font-weight-bold">{{ 'ldn-new-service.form.label.inboundPattern' | translate }} </label>
|
||||
</div>
|
||||
<ng-container *ngIf="formModel.get('notifyServiceInboundPatterns')['controls'][0]?.value?.pattern">
|
||||
<div class="col">
|
||||
<label class="font-weight-bold">{{ 'ldn-new-service.form.label.ItemFilter' | translate }}</label>
|
||||
</div>
|
||||
<div class="col-sm-1">
|
||||
<label class="font-weight-bold">{{ 'ldn-new-service.form.label.automatic' | translate }}</label>
|
||||
</div>
|
||||
</ng-container>
|
||||
<div class="col-sm-2">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- In the Inbound Patterns section -->
|
||||
<div *ngIf="areControlsInitialized">
|
||||
<div *ngFor="let patternGroup of formModel.get('notifyServiceInboundPatterns')['controls']; let i = index"
|
||||
[class.marked-for-deletion]="markedForDeletionInboundPattern.includes(i)"
|
||||
formGroupName="notifyServiceInboundPatterns">
|
||||
|
||||
<ng-container [formGroupName]="i">
|
||||
|
||||
|
||||
<div class="row mb-1 align-items-center">
|
||||
<div class="col">
|
||||
<div #inboundPatternDropdown="ngbDropdown" class="w-80" display="dynamic"
|
||||
id="additionalInboundPattern{{i}}"
|
||||
ngbDropdown placement="top-start">
|
||||
<div class="position-relative right-addon" role="combobox" aria-expanded="false" aria-controls="inboundPatternDropdownButton">
|
||||
<i aria-hidden="true" class="position-absolute scrollable-dropdown-toggle"
|
||||
ngbDropdownToggle></i>
|
||||
<input
|
||||
(click)="inboundPatternDropdown.open();"
|
||||
[readonly]="true"
|
||||
[value]="selectedInboundPatterns"
|
||||
class="form-control w-80 scrollable-dropdown-input"
|
||||
formControlName="patternLabel"
|
||||
id="inboundPatternDropdownButton"
|
||||
ngbDropdownAnchor
|
||||
type="text"
|
||||
[attr.aria-label]="'ldn-service-input-inbound-pattern-dropdown' | translate"
|
||||
/>
|
||||
<div aria-labelledby="inboundPatternDropdownButton"
|
||||
class="dropdown-menu dropdown-menu-top w-100 "
|
||||
ngbDropdownMenu>
|
||||
<div class="scrollable-menu" role="listbox">
|
||||
<button (click)="selectInboundPattern(pattern, i); $event.stopPropagation()"
|
||||
*ngFor="let pattern of inboundPatterns; let internalIndex = index"
|
||||
[title]="'ldn-service.form.pattern.' + pattern + '.description' | translate"
|
||||
class="dropdown-item collection-item text-truncate w-100"
|
||||
ngbDropdownItem
|
||||
type="button">
|
||||
<div>{{ 'ldn-service.form.pattern.' + pattern + '.label' | translate }}</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col">
|
||||
<ng-container
|
||||
*ngIf="formModel.get('notifyServiceInboundPatterns')['controls'][i].value.pattern">
|
||||
<div #inboundItemfilterDropdown="ngbDropdown" class="w-100" id="constraint{{i}}" ngbDropdown
|
||||
placement="top-start">
|
||||
<div class="position-relative right-addon" aria-expanded="false" aria-controls="inboundItemfilterDropdown" role="combobox">
|
||||
<i aria-hidden="true" class="position-absolute scrollable-dropdown-toggle"
|
||||
ngbDropdownToggle></i>
|
||||
<input
|
||||
[readonly]="true"
|
||||
class="form-control d-none w-100 scrollable-dropdown-input"
|
||||
formControlName="constraint"
|
||||
id="inboundItemfilterDropdown"
|
||||
ngbDropdownAnchor
|
||||
type="text"
|
||||
[attr.aria-label]="'ldn-service-input-inbound-item-filter-dropdown' | translate"
|
||||
/>
|
||||
<input
|
||||
(click)="inboundItemfilterDropdown.open();"
|
||||
[readonly]="true"
|
||||
class="form-control w-100 scrollable-dropdown-input"
|
||||
formControlName="constraintFormatted"
|
||||
id="inboundItemfilterDropdownPrettified"
|
||||
ngbDropdownAnchor
|
||||
type="text"
|
||||
[attr.aria-label]="'ldn-service-input-inbound-item-filter-dropdown' | translate"
|
||||
/>
|
||||
<div aria-labelledby="inboundItemfilterDropdownButton"
|
||||
class="dropdown-menu scrollable-dropdown-menu w-100 "
|
||||
ngbDropdownMenu>
|
||||
<div class="scrollable-menu" role="listbox">
|
||||
<button (click)="selectInboundItemFilter('', i); $event.stopPropagation()"
|
||||
class="dropdown-item collection-item text-truncate w-100" ngbDropdownItem type="button">
|
||||
<span> {{'ldn-service.control-constaint-select-none' | translate}} </span>
|
||||
</button>
|
||||
<button (click)="selectInboundItemFilter(constraint.id, i); $event.stopPropagation()"
|
||||
*ngFor="let constraint of (itemfiltersRD$ | async)?.payload?.page; let internalIndex = index"
|
||||
class="dropdown-item collection-item text-truncate w-100"
|
||||
ngbDropdownItem
|
||||
type="button">
|
||||
<div>{{ constraint.id + '.label' | translate }}</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
</div>
|
||||
|
||||
<div
|
||||
[style.visibility]="formModel.get('notifyServiceInboundPatterns')['controls'][i].value.pattern ? 'visible' : 'hidden'"
|
||||
class="col-sm-1">
|
||||
<input formControlName="automatic" hidden id="automatic{{i}}" name="automatic{{i}}"
|
||||
type="checkbox">
|
||||
<div (click)="toggleAutomatic(i)"
|
||||
[class.checked]="formModel.get('notifyServiceInboundPatterns.' + i + '.automatic').value"
|
||||
class="toggle-switch">
|
||||
<div class="slider"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="col-sm-2">
|
||||
<div class="btn-group">
|
||||
<button (click)="markForInboundPatternDeletion(i)" class="btn btn-outline-dark trash-button"
|
||||
[title]="'ldn-service-button-mark-inbound-deletion' | translate"
|
||||
type="button">
|
||||
<i class="fas fa-trash"></i>
|
||||
</button>
|
||||
|
||||
|
||||
<button (click)="unmarkForInboundPatternDeletion(i)"
|
||||
*ngIf="markedForDeletionInboundPattern.includes(i)"
|
||||
[title]="'ldn-service-button-unmark-inbound-deletion' | translate"
|
||||
class="btn btn-warning "
|
||||
type="button">
|
||||
<i class="fas fa-undo"></i>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ng-container>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<span (click)="addInboundPattern()"
|
||||
class="add-pattern-link mb-2">{{ 'ldn-new-service.form.label.addPattern' | translate }}</span>
|
||||
|
||||
<div class="submission-form-footer my-1 position-sticky d-flex justify-content-between" role="group">
|
||||
<button (click)="resetFormAndLeave()" class="btn btn-primary" type="button">
|
||||
<span> {{ 'submission.general.back.submit' | translate }}</span>
|
||||
</button>
|
||||
<button class="btn btn-primary" type="submit">
|
||||
<span><i class="fas fa-save"></i> {{ 'ldn-new-service.form.label.submit' | translate }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
<ng-template #confirmModal>
|
||||
<div class="modal-header">
|
||||
<h4 *ngIf="!isNewService">{{'service.overview.edit.modal' | translate }}</h4>
|
||||
<h4 *ngIf="isNewService">{{'service.overview.create.modal' | translate }}</h4>
|
||||
<button (click)="closeModal()" aria-label="Close"
|
||||
class="close" type="button">
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="modal-body">
|
||||
<div *ngIf="!isNewService">
|
||||
{{ 'service.overview.edit.body' | translate }}
|
||||
</div>
|
||||
<span *ngIf="isNewService">
|
||||
{{ 'service.overview.create.body' | translate }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<div *ngIf="!isNewService">
|
||||
<button (click)="closeModal()" class="btn btn-danger mr-2"
|
||||
id="delete-confirm-edit">{{ 'service.detail.return' | translate }}
|
||||
</button>
|
||||
<button *ngIf="!isNewService" (click)="patchService()"
|
||||
class="btn btn-primary">{{ 'service.detail.update' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
<div *ngIf="isNewService">
|
||||
<button (click)="closeModal()" class="btn btn-danger mr-2 "
|
||||
id="delete-confirm-new">{{ 'service.refuse.create' | translate }}
|
||||
</button>
|
||||
<button (click)="createService()"
|
||||
class="btn btn-primary">{{ 'service.confirm.create' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</ng-template>
|
||||
|
||||
|
@@ -0,0 +1,143 @@
|
||||
@import '../../../shared/form/builder/ds-dynamic-form-ui/models/scrollable-dropdown/dynamic-scrollable-dropdown.component.scss';
|
||||
@import '../../../shared/form/form.component.scss';
|
||||
|
||||
form {
|
||||
font-size: 14px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
input,
|
||||
select {
|
||||
max-width: 100%;
|
||||
width: 100%;
|
||||
padding: 8px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
option:not(:first-child) {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.trash-button {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
}
|
||||
|
||||
textarea {
|
||||
height: 200px;
|
||||
resize: none;
|
||||
}
|
||||
|
||||
.add-pattern-link {
|
||||
color: #0048ff;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.remove-pattern-link {
|
||||
color: #e34949;
|
||||
cursor: pointer;
|
||||
margin-left: 10px;
|
||||
}
|
||||
|
||||
.status-checkbox {
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
|
||||
.invalid-field {
|
||||
border: 1px solid red;
|
||||
color: #000000;
|
||||
}
|
||||
|
||||
.error-text {
|
||||
color: red;
|
||||
font-size: 0.8em;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.toggle-switch {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
opacity: 0.8;
|
||||
position: relative;
|
||||
width: 60px;
|
||||
height: 30px;
|
||||
background-color: #ccc;
|
||||
border-radius: 15px;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.3s;
|
||||
}
|
||||
|
||||
.toggle-switch.checked {
|
||||
background-color: #24cc9a;
|
||||
}
|
||||
|
||||
.slider {
|
||||
position: absolute;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: 50%;
|
||||
background-color: #fff;
|
||||
transition: transform 0.3s;
|
||||
}
|
||||
|
||||
|
||||
.toggle-switch .slider {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
border-radius: 50%;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.toggle-switch.checked .slider {
|
||||
transform: translateX(30px);
|
||||
}
|
||||
|
||||
.toggle-switch-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
justify-content: flex-start;
|
||||
align-items: flex-end;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.small-text {
|
||||
font-size: 0.7em;
|
||||
color: #888;
|
||||
}
|
||||
|
||||
.toggle-switch {
|
||||
cursor: pointer;
|
||||
margin-top: 3px;
|
||||
margin-right: 3px
|
||||
}
|
||||
|
||||
.label-box {
|
||||
margin-left: 11px;
|
||||
}
|
||||
|
||||
.label-box-2 {
|
||||
margin-left: 14px;
|
||||
}
|
||||
|
||||
.label-box-3 {
|
||||
margin-left: 5px;
|
||||
}
|
||||
|
||||
.submission-form-footer {
|
||||
border-radius: var(--bs-card-border-radius);
|
||||
bottom: 0;
|
||||
background-color: var(--bs-gray-400);
|
||||
padding: calc(var(--bs-spacer) / 2);
|
||||
z-index: calc(var(--ds-submission-footer-z-index) + 1);
|
||||
}
|
||||
|
||||
.marked-for-deletion {
|
||||
background-color: lighten($red, 30%);
|
||||
}
|
||||
|
||||
.dropdown-menu-top, .scrollable-dropdown-menu {
|
||||
z-index: var(--ds-submission-footer-z-index);
|
||||
}
|
||||
|
||||
|
@@ -0,0 +1,241 @@
|
||||
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
|
||||
|
||||
import { NgbDropdownModule, NgbModal } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { LdnServiceFormComponent } from './ldn-service-form.component';
|
||||
import { ChangeDetectorRef, EventEmitter } from '@angular/core';
|
||||
import { FormArray, FormBuilder, FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { TranslateModule, TranslateService } from '@ngx-translate/core';
|
||||
import { PaginationService } from 'ngx-pagination';
|
||||
import { NotificationsService } from '../../../shared/notifications/notifications.service';
|
||||
import { LdnItemfiltersService } from '../ldn-services-data/ldn-itemfilters-data.service';
|
||||
import { LdnServicesService } from '../ldn-services-data/ldn-services-data.service';
|
||||
import { RouterStub } from '../../../shared/testing/router.stub';
|
||||
import { MockActivatedRoute } from '../../../shared/mocks/active-router.mock';
|
||||
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
|
||||
import { of as observableOf, of } from 'rxjs';
|
||||
import { RouteService } from '../../../core/services/route.service';
|
||||
import { provideMockStore } from '@ngrx/store/testing';
|
||||
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
|
||||
import { By } from '@angular/platform-browser';
|
||||
|
||||
describe('LdnServiceFormEditComponent', () => {
|
||||
let component: LdnServiceFormComponent;
|
||||
let fixture: ComponentFixture<LdnServiceFormComponent>;
|
||||
|
||||
let ldnServicesService: LdnServicesService;
|
||||
let ldnItemfiltersService: any;
|
||||
let cdRefStub: any;
|
||||
let modalService: any;
|
||||
let activatedRoute: MockActivatedRoute;
|
||||
|
||||
const testId = '1234';
|
||||
const routeParams = {
|
||||
serviceId: testId,
|
||||
};
|
||||
const routeUrlSegments = [{path: 'path'}];
|
||||
const formMockValue = {
|
||||
'id': '',
|
||||
'name': 'name',
|
||||
'description': 'description',
|
||||
'url': 'www.test.com',
|
||||
'ldnUrl': 'https://test.com',
|
||||
'lowerIp': '127.0.0.1',
|
||||
'upperIp': '100.100.100.100',
|
||||
'score': 1,
|
||||
'inboundPattern': '',
|
||||
'constraintPattern': '',
|
||||
'enabled': '',
|
||||
'type': 'ldnservice',
|
||||
'notifyServiceInboundPatterns': [
|
||||
{
|
||||
'pattern': '',
|
||||
'patternLabel': 'Select a pattern',
|
||||
'constraint': '',
|
||||
'automatic': false
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
|
||||
const translateServiceStub = {
|
||||
get: () => of('translated-text'),
|
||||
instant: () => 'translated-text',
|
||||
onLangChange: new EventEmitter(),
|
||||
onTranslationChange: new EventEmitter(),
|
||||
onDefaultLangChange: new EventEmitter()
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
ldnServicesService = jasmine.createSpyObj('ldnServicesService', {
|
||||
create: observableOf(null),
|
||||
update: observableOf(null),
|
||||
findById: createSuccessfulRemoteDataObject$({}),
|
||||
});
|
||||
|
||||
ldnItemfiltersService = {
|
||||
findAll: () => of(['item1', 'item2']),
|
||||
};
|
||||
cdRefStub = Object.assign({
|
||||
detectChanges: () => fixture.detectChanges()
|
||||
});
|
||||
modalService = {
|
||||
open: () => {/*comment*/
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
activatedRoute = new MockActivatedRoute(routeParams, routeUrlSegments);
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [ReactiveFormsModule, TranslateModule.forRoot(), NgbDropdownModule],
|
||||
declarations: [LdnServiceFormComponent],
|
||||
providers: [
|
||||
{provide: LdnServicesService, useValue: ldnServicesService},
|
||||
{provide: LdnItemfiltersService, useValue: ldnItemfiltersService},
|
||||
{provide: Router, useValue: new RouterStub()},
|
||||
{provide: ActivatedRoute, useValue: activatedRoute},
|
||||
{provide: ChangeDetectorRef, useValue: cdRefStub},
|
||||
{provide: NgbModal, useValue: modalService},
|
||||
{provide: NotificationsService, useValue: new NotificationsServiceStub()},
|
||||
{provide: TranslateService, useValue: translateServiceStub},
|
||||
{provide: PaginationService, useValue: {}},
|
||||
FormBuilder,
|
||||
RouteService,
|
||||
provideMockStore({}),
|
||||
]
|
||||
})
|
||||
.compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(LdnServiceFormComponent);
|
||||
component = fixture.componentInstance;
|
||||
spyOn(component, 'filterPatternObjectsAndAssignLabel').and.callFake((a) => a);
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
expect(component.formModel instanceof FormGroup).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should init properties correctly', fakeAsync(() => {
|
||||
spyOn(component, 'fetchServiceData');
|
||||
spyOn(component, 'setItemfilters');
|
||||
component.ngOnInit();
|
||||
tick(100);
|
||||
expect((component as any).serviceId).toEqual(testId);
|
||||
expect(component.isNewService).toBeFalsy();
|
||||
expect(component.areControlsInitialized).toBeTruthy();
|
||||
expect(component.formModel.controls.notifyServiceInboundPatterns).toBeDefined();
|
||||
expect(component.fetchServiceData).toHaveBeenCalledWith(testId);
|
||||
expect(component.setItemfilters).toHaveBeenCalled();
|
||||
}));
|
||||
|
||||
it('should unsubscribe on destroy', () => {
|
||||
spyOn((component as any).routeSubscription, 'unsubscribe');
|
||||
component.ngOnDestroy();
|
||||
expect((component as any).routeSubscription.unsubscribe).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle create service with valid form', () => {
|
||||
spyOn(component, 'fetchServiceData').and.callFake((a) => a);
|
||||
component.formModel.addControl('notifyServiceInboundPatterns', (component as any).formBuilder.array([{pattern: 'patternValue'}]));
|
||||
const nameInput = fixture.debugElement.query(By.css('#name'));
|
||||
const descriptionInput = fixture.debugElement.query(By.css('#description'));
|
||||
const urlInput = fixture.debugElement.query(By.css('#url'));
|
||||
const scoreInput = fixture.debugElement.query(By.css('#score'));
|
||||
const lowerIpInput = fixture.debugElement.query(By.css('#lowerIp'));
|
||||
const upperIpInput = fixture.debugElement.query(By.css('#upperIp'));
|
||||
const ldnUrlInput = fixture.debugElement.query(By.css('#ldnUrl'));
|
||||
component.formModel.patchValue(formMockValue);
|
||||
|
||||
nameInput.nativeElement.value = 'testName';
|
||||
descriptionInput.nativeElement.value = 'testDescription';
|
||||
urlInput.nativeElement.value = 'tetsUrl.com';
|
||||
ldnUrlInput.nativeElement.value = 'tetsLdnUrl.com';
|
||||
scoreInput.nativeElement.value = 1;
|
||||
lowerIpInput.nativeElement.value = '127.0.0.1';
|
||||
upperIpInput.nativeElement.value = '127.0.0.1';
|
||||
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(component.formModel.valid).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should handle create service with invalid form', () => {
|
||||
const nameInput = fixture.debugElement.query(By.css('#name'));
|
||||
|
||||
nameInput.nativeElement.value = 'testName';
|
||||
fixture.detectChanges();
|
||||
|
||||
expect(component.formModel.valid).toBeFalsy();
|
||||
});
|
||||
|
||||
it('should not create service with invalid form', () => {
|
||||
spyOn(component.formModel, 'markAllAsTouched');
|
||||
spyOn(component, 'closeModal');
|
||||
component.createService();
|
||||
|
||||
expect(component.formModel.markAllAsTouched).toHaveBeenCalled();
|
||||
expect(component.closeModal).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should create service with valid form', () => {
|
||||
spyOn(component.formModel, 'markAllAsTouched');
|
||||
spyOn(component, 'closeModal');
|
||||
spyOn(component, 'checkPatterns').and.callFake(() => true);
|
||||
component.formModel.addControl('notifyServiceInboundPatterns', (component as any).formBuilder.array([{pattern: 'patternValue'}]));
|
||||
component.formModel.patchValue(formMockValue);
|
||||
component.createService();
|
||||
|
||||
expect(component.formModel.markAllAsTouched).toHaveBeenCalled();
|
||||
expect(component.closeModal).not.toHaveBeenCalled();
|
||||
expect(ldnServicesService.create).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should check patterns', () => {
|
||||
const arrValid = new FormArray([
|
||||
new FormGroup({
|
||||
pattern: new FormControl('pattern')
|
||||
}),
|
||||
]);
|
||||
|
||||
const arrInvalid = new FormArray([
|
||||
new FormGroup({
|
||||
pattern: new FormControl('')
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(component.checkPatterns(arrValid)).toBeTruthy();
|
||||
expect(component.checkPatterns(arrInvalid)).toBeFalsy();
|
||||
});
|
||||
|
||||
it('should fetch service data', () => {
|
||||
component.fetchServiceData(testId);
|
||||
expect(ldnServicesService.findById).toHaveBeenCalledWith(testId);
|
||||
expect(component.filterPatternObjectsAndAssignLabel).toHaveBeenCalled();
|
||||
expect((component as any).ldnService).toEqual({});
|
||||
});
|
||||
|
||||
it('should generate patch operations', () => {
|
||||
spyOn(component as any, 'createReplaceOperation');
|
||||
spyOn(component as any, 'handlePatterns');
|
||||
component.generatePatchOperations();
|
||||
expect((component as any).createReplaceOperation).toHaveBeenCalledTimes(7);
|
||||
expect((component as any).handlePatterns).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should open modal on submit', () => {
|
||||
spyOn(component, 'openConfirmModal');
|
||||
component.onSubmit();
|
||||
expect(component.openConfirmModal).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
|
||||
it('should reset form and leave', () => {
|
||||
spyOn(component as any, 'sendBack');
|
||||
|
||||
component.resetFormAndLeave();
|
||||
expect((component as any).sendBack).toHaveBeenCalled();
|
||||
});
|
||||
});
|
@@ -0,0 +1,565 @@
|
||||
import { ChangeDetectorRef, Component, OnDestroy, OnInit, TemplateRef, ViewChild } from '@angular/core';
|
||||
import { FormArray, FormBuilder, FormGroup, Validators } from '@angular/forms';
|
||||
import { LDN_SERVICE } from '../ldn-services-model/ldn-service.resource-type';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { LdnServicesService } from '../ldn-services-data/ldn-services-data.service';
|
||||
import { notifyPatterns } from '../ldn-services-patterns/ldn-service-coar-patterns';
|
||||
import { animate, state, style, transition, trigger } from '@angular/animations';
|
||||
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { NotificationsService } from '../../../shared/notifications/notifications.service';
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
import { LdnService } from '../ldn-services-model/ldn-services.model';
|
||||
import { RemoteData } from 'src/app/core/data/remote-data';
|
||||
import { Operation } from 'fast-json-patch';
|
||||
import { getFirstCompletedRemoteData } from '../../../core/shared/operators';
|
||||
import { LdnItemfiltersService } from '../ldn-services-data/ldn-itemfilters-data.service';
|
||||
import { Itemfilter } from '../ldn-services-model/ldn-service-itemfilters';
|
||||
import { PaginatedList } from '../../../core/data/paginated-list.model';
|
||||
import { combineLatestWith, Observable, Subscription } from 'rxjs';
|
||||
import { PaginationService } from '../../../core/pagination/pagination.service';
|
||||
import { FindListOptions } from '../../../core/data/find-list-options.model';
|
||||
import { NotifyServicePattern } from '../ldn-services-model/ldn-service-patterns.model';
|
||||
import { IpV4Validator } from '../../../shared/utils/ipV4.validator';
|
||||
|
||||
/**
|
||||
* Component for editing LDN service through a form that allows to create or edit the properties of a service
|
||||
*/
|
||||
@Component({
|
||||
selector: 'ds-ldn-service-form',
|
||||
templateUrl: './ldn-service-form.component.html',
|
||||
styleUrls: ['./ldn-service-form.component.scss'],
|
||||
animations: [
|
||||
trigger('toggleAnimation', [
|
||||
state('true', style({})),
|
||||
state('false', style({})),
|
||||
transition('true <=> false', animate('300ms ease-in')),
|
||||
]),
|
||||
],
|
||||
})
|
||||
export class LdnServiceFormComponent implements OnInit, OnDestroy {
|
||||
formModel: FormGroup;
|
||||
|
||||
@ViewChild('confirmModal', {static: true}) confirmModal: TemplateRef<any>;
|
||||
@ViewChild('resetFormModal', {static: true}) resetFormModal: TemplateRef<any>;
|
||||
|
||||
public inboundPatterns: string[] = notifyPatterns;
|
||||
public isNewService: boolean;
|
||||
public areControlsInitialized: boolean;
|
||||
public itemfiltersRD$: Observable<RemoteData<PaginatedList<Itemfilter>>>;
|
||||
public config: FindListOptions = Object.assign(new FindListOptions(), {
|
||||
elementsPerPage: 20
|
||||
});
|
||||
public markedForDeletionInboundPattern: number[] = [];
|
||||
public selectedInboundPatterns: string[];
|
||||
|
||||
protected serviceId: string;
|
||||
|
||||
private deletedInboundPatterns: number[] = [];
|
||||
private modalRef: any;
|
||||
private ldnService: LdnService;
|
||||
private selectPatternDefaultLabeli18Key = 'ldn-service.form.label.placeholder.default-select';
|
||||
private routeSubscription: Subscription;
|
||||
|
||||
constructor(
|
||||
protected ldnServicesService: LdnServicesService,
|
||||
private ldnItemfiltersService: LdnItemfiltersService,
|
||||
private formBuilder: FormBuilder,
|
||||
private router: Router,
|
||||
private route: ActivatedRoute,
|
||||
private cdRef: ChangeDetectorRef,
|
||||
protected modalService: NgbModal,
|
||||
private notificationService: NotificationsService,
|
||||
private translateService: TranslateService,
|
||||
protected paginationService: PaginationService
|
||||
) {
|
||||
|
||||
this.formModel = this.formBuilder.group({
|
||||
id: [''],
|
||||
name: ['', Validators.required],
|
||||
description: [''],
|
||||
url: ['', Validators.required],
|
||||
ldnUrl: ['', Validators.required],
|
||||
lowerIp: ['', [Validators.required, new IpV4Validator()]],
|
||||
upperIp: ['', [Validators.required, new IpV4Validator()]],
|
||||
score: ['', [Validators.required, Validators.pattern('^0*(\.[0-9]+)?$|^1(\.0+)?$')]], inboundPattern: [''],
|
||||
constraintPattern: [''],
|
||||
enabled: [''],
|
||||
type: LDN_SERVICE.value,
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.routeSubscription = this.route.params.pipe(
|
||||
combineLatestWith(this.route.url)
|
||||
).subscribe(([params, segment]) => {
|
||||
this.serviceId = params.serviceId;
|
||||
this.isNewService = segment[0].path === 'new';
|
||||
this.formModel.addControl('notifyServiceInboundPatterns', this.formBuilder.array([this.createInboundPatternFormGroup()]));
|
||||
this.areControlsInitialized = true;
|
||||
if (this.serviceId && !this.isNewService) {
|
||||
this.fetchServiceData(this.serviceId);
|
||||
}
|
||||
});
|
||||
this.setItemfilters();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.routeSubscription.unsubscribe();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets item filters using LDN item filters service
|
||||
*/
|
||||
setItemfilters() {
|
||||
this.itemfiltersRD$ = this.ldnItemfiltersService.findAll().pipe(
|
||||
getFirstCompletedRemoteData());
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles the creation of an LDN service by retrieving and validating form fields,
|
||||
* and submitting the form data to the LDN services endpoint.
|
||||
*/
|
||||
createService() {
|
||||
this.formModel.markAllAsTouched();
|
||||
const notifyServiceInboundPatterns = this.formModel.get('notifyServiceInboundPatterns') as FormArray;
|
||||
const hasInboundPattern = notifyServiceInboundPatterns?.length > 0 ? this.checkPatterns(notifyServiceInboundPatterns) : false;
|
||||
|
||||
if (this.formModel.invalid) {
|
||||
this.closeModal();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!hasInboundPattern) {
|
||||
this.notificationService.warning(this.translateService.get('ldn-service-notification.created.warning.title'));
|
||||
this.closeModal();
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
this.formModel.value.notifyServiceInboundPatterns = this.formModel.value.notifyServiceInboundPatterns.map((pattern: {
|
||||
pattern: string;
|
||||
patternLabel: string,
|
||||
constraintFormatted: string;
|
||||
}) => {
|
||||
const {patternLabel, ...rest} = pattern;
|
||||
delete rest.constraintFormatted;
|
||||
return rest;
|
||||
});
|
||||
|
||||
const values = {...this.formModel.value, enabled: true};
|
||||
|
||||
const ldnServiceData = this.ldnServicesService.create(values);
|
||||
|
||||
ldnServiceData.pipe(
|
||||
getFirstCompletedRemoteData()
|
||||
).subscribe((rd: RemoteData<LdnService>) => {
|
||||
if (rd.hasSucceeded) {
|
||||
this.notificationService.success(this.translateService.get('ldn-service-notification.created.success.title'),
|
||||
this.translateService.get('ldn-service-notification.created.success.body'));
|
||||
this.closeModal();
|
||||
this.sendBack();
|
||||
} else {
|
||||
if (!this.formModel.errors) {
|
||||
this.setLdnUrlError();
|
||||
}
|
||||
this.notificationService.error(this.translateService.get('ldn-service-notification.created.failure.title'),
|
||||
this.translateService.get('ldn-service-notification.created.failure.body'));
|
||||
this.closeModal();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if at least one pattern in the specified form array has a value.
|
||||
*
|
||||
* @param {FormArray} formArray - The form array containing patterns to check.
|
||||
* @returns {boolean} - True if at least one pattern has a value, otherwise false.
|
||||
*/
|
||||
checkPatterns(formArray: FormArray): boolean {
|
||||
for (let i = 0; i < formArray.length; i++) {
|
||||
const pattern = formArray.at(i).get('pattern').value;
|
||||
if (pattern) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches LDN service data by ID and updates the form
|
||||
* @param serviceId - The ID of the LDN service
|
||||
*/
|
||||
fetchServiceData(serviceId: string): void {
|
||||
this.ldnServicesService.findById(serviceId).pipe(
|
||||
getFirstCompletedRemoteData()
|
||||
).subscribe(
|
||||
(data: RemoteData<LdnService>) => {
|
||||
if (data.hasSucceeded) {
|
||||
this.ldnService = data.payload;
|
||||
this.formModel.patchValue({
|
||||
id: this.ldnService.id,
|
||||
name: this.ldnService.name,
|
||||
description: this.ldnService.description,
|
||||
url: this.ldnService.url,
|
||||
score: this.ldnService.score,
|
||||
ldnUrl: this.ldnService.ldnUrl,
|
||||
type: this.ldnService.type,
|
||||
enabled: this.ldnService.enabled,
|
||||
lowerIp: this.ldnService.lowerIp,
|
||||
upperIp: this.ldnService.upperIp
|
||||
});
|
||||
this.filterPatternObjectsAndAssignLabel('notifyServiceInboundPatterns');
|
||||
let notifyServiceInboundPatternsFormArray = this.formModel.get('notifyServiceInboundPatterns') as FormArray;
|
||||
notifyServiceInboundPatternsFormArray.controls.forEach(
|
||||
control => {
|
||||
const controlFormGroup = control as FormGroup;
|
||||
const controlConstraint = controlFormGroup.get('constraint').value;
|
||||
controlFormGroup.patchValue({
|
||||
constraintFormatted: controlConstraint ? this.translateService.instant((controlConstraint as string) + '.label') : ''
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filters pattern objects, initializes form groups, assigns labels, and adds them to the specified form array so the correct string is shown in the dropdown..
|
||||
* @param formArrayName - The name of the form array to be populated
|
||||
*/
|
||||
filterPatternObjectsAndAssignLabel(formArrayName: string) {
|
||||
const PatternsArray = this.formModel.get(formArrayName) as FormArray;
|
||||
PatternsArray.clear();
|
||||
|
||||
let servicesToUse = this.ldnService.notifyServiceInboundPatterns;
|
||||
|
||||
servicesToUse.forEach((patternObj: NotifyServicePattern) => {
|
||||
let patternFormGroup;
|
||||
patternFormGroup = this.initializeInboundPatternFormGroup();
|
||||
const newPatternObjWithLabel = Object.assign(new NotifyServicePattern(), {
|
||||
...patternObj,
|
||||
patternLabel: this.translateService.instant('ldn-service.form.pattern.' + patternObj?.pattern + '.label')
|
||||
});
|
||||
patternFormGroup.patchValue(newPatternObjWithLabel);
|
||||
|
||||
PatternsArray.push(patternFormGroup);
|
||||
this.cdRef.detectChanges();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates an array of patch operations based on form changes
|
||||
* @returns Array of patch operations
|
||||
*/
|
||||
generatePatchOperations(): any[] {
|
||||
const patchOperations: any[] = [];
|
||||
|
||||
this.createReplaceOperation(patchOperations, 'name', '/name');
|
||||
this.createReplaceOperation(patchOperations, 'description', '/description');
|
||||
this.createReplaceOperation(patchOperations, 'ldnUrl', '/ldnurl');
|
||||
this.createReplaceOperation(patchOperations, 'url', '/url');
|
||||
this.createReplaceOperation(patchOperations, 'score', '/score');
|
||||
this.createReplaceOperation(patchOperations, 'lowerIp', '/lowerIp');
|
||||
this.createReplaceOperation(patchOperations, 'upperIp', '/upperIp');
|
||||
|
||||
this.handlePatterns(patchOperations, 'notifyServiceInboundPatterns');
|
||||
this.deletedInboundPatterns.forEach(index => {
|
||||
const removeOperation: Operation = {
|
||||
op: 'remove',
|
||||
path: `notifyServiceInboundPatterns[${index}]`
|
||||
};
|
||||
patchOperations.push(removeOperation);
|
||||
});
|
||||
|
||||
return patchOperations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Submits the form by opening the confirmation modal
|
||||
*/
|
||||
onSubmit() {
|
||||
this.openConfirmModal(this.confirmModal);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a new inbound pattern form group to the array of inbound patterns in the form
|
||||
*/
|
||||
addInboundPattern() {
|
||||
const notifyServiceInboundPatternsArray = this.formModel.get('notifyServiceInboundPatterns') as FormArray;
|
||||
notifyServiceInboundPatternsArray.push(this.createInboundPatternFormGroup());
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects an inbound pattern by updating its values based on the provided pattern value and index
|
||||
* @param patternValue - The selected pattern value
|
||||
* @param index - The index of the inbound pattern in the array
|
||||
*/
|
||||
selectInboundPattern(patternValue: string, index: number): void {
|
||||
const patternArray = (this.formModel.get('notifyServiceInboundPatterns') as FormArray);
|
||||
patternArray.controls[index].patchValue({pattern: patternValue});
|
||||
patternArray.controls[index].patchValue({patternLabel: this.translateService.instant('ldn-service.form.pattern.' + patternValue + '.label')});
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects an inbound item filter by updating its value based on the provided filter value and index
|
||||
* @param filterValue - The selected filter value
|
||||
* @param index - The index of the inbound pattern in the array
|
||||
*/
|
||||
selectInboundItemFilter(filterValue: string, index: number): void {
|
||||
const filterArray = (this.formModel.get('notifyServiceInboundPatterns') as FormArray);
|
||||
filterArray.controls[index].patchValue({
|
||||
constraint: filterValue,
|
||||
constraintFormatted: this.translateService.instant((filterValue !== '' ? filterValue : 'ldn.no-filter') + '.label')
|
||||
});
|
||||
filterArray.markAllAsTouched();
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggles the automatic property of an inbound pattern at the specified index
|
||||
* @param i - The index of the inbound pattern in the array
|
||||
*/
|
||||
toggleAutomatic(i: number) {
|
||||
const automaticControl = this.formModel.get(`notifyServiceInboundPatterns.${i}.automatic`);
|
||||
if (automaticControl) {
|
||||
automaticControl.markAsTouched();
|
||||
automaticControl.setValue(!automaticControl.value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggles the enabled status of the LDN service by sending a patch request
|
||||
*/
|
||||
toggleEnabled() {
|
||||
const newStatus = !this.formModel.get('enabled').value;
|
||||
|
||||
const patchOperation: Operation = {
|
||||
op: 'replace',
|
||||
path: '/enabled',
|
||||
value: newStatus,
|
||||
};
|
||||
|
||||
this.ldnServicesService.patch(this.ldnService, [patchOperation]).pipe(
|
||||
getFirstCompletedRemoteData()
|
||||
).subscribe(
|
||||
() => {
|
||||
this.formModel.get('enabled').setValue(newStatus);
|
||||
this.cdRef.detectChanges();
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the modal
|
||||
*/
|
||||
closeModal() {
|
||||
this.modalRef.close();
|
||||
this.cdRef.detectChanges();
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a confirmation modal with the specified content
|
||||
* @param content - The content to be displayed in the modal
|
||||
*/
|
||||
openConfirmModal(content) {
|
||||
this.modalRef = this.modalService.open(content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Patches the LDN service by retrieving and sending patch operations geenrated in generatePatchOperations()
|
||||
*/
|
||||
patchService() {
|
||||
this.deleteMarkedInboundPatterns();
|
||||
|
||||
const patchOperations = this.generatePatchOperations();
|
||||
this.formModel.markAllAsTouched();
|
||||
// If the form is invalid, close the modal and return
|
||||
if (this.formModel.invalid) {
|
||||
this.closeModal();
|
||||
return;
|
||||
}
|
||||
|
||||
const notifyServiceInboundPatterns = this.formModel.get('notifyServiceInboundPatterns') as FormArray;
|
||||
const deletedInboundPatternsLength = this.deletedInboundPatterns.length;
|
||||
// If no inbound patterns are specified, close the modal and return
|
||||
// notify the user that no patterns are specified
|
||||
if (notifyServiceInboundPatterns.length === deletedInboundPatternsLength) {
|
||||
this.notificationService.warning(this.translateService.get('ldn-service-notification.created.warning.title'));
|
||||
this.deletedInboundPatterns = [];
|
||||
this.closeModal();
|
||||
return;
|
||||
}
|
||||
|
||||
this.ldnServicesService.patch(this.ldnService, patchOperations).pipe(
|
||||
getFirstCompletedRemoteData()
|
||||
).subscribe(
|
||||
(rd: RemoteData<LdnService>) => {
|
||||
if (rd.hasSucceeded) {
|
||||
this.closeModal();
|
||||
this.sendBack();
|
||||
this.notificationService.success(this.translateService.get('admin.registries.services-formats.modify.success.head'),
|
||||
this.translateService.get('admin.registries.services-formats.modify.success.content'));
|
||||
} else {
|
||||
if (!this.formModel.errors) {
|
||||
this.setLdnUrlError();
|
||||
}
|
||||
this.notificationService.error(this.translateService.get('admin.registries.services-formats.modify.failure.head'),
|
||||
this.translateService.get('admin.registries.services-formats.modify.failure.content'));
|
||||
this.closeModal();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resets the form and navigates back to the LDN services page
|
||||
*/
|
||||
resetFormAndLeave() {
|
||||
this.sendBack();
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the specified inbound pattern for deletion
|
||||
* @param index - The index of the inbound pattern in the array
|
||||
*/
|
||||
markForInboundPatternDeletion(index: number) {
|
||||
if (!this.markedForDeletionInboundPattern.includes(index)) {
|
||||
this.markedForDeletionInboundPattern.push(index);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unmarks the specified inbound pattern for deletion
|
||||
* @param index - The index of the inbound pattern in the array
|
||||
*/
|
||||
unmarkForInboundPatternDeletion(index: number) {
|
||||
const i = this.markedForDeletionInboundPattern.indexOf(index);
|
||||
if (i !== -1) {
|
||||
this.markedForDeletionInboundPattern.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes marked inbound patterns from the form model
|
||||
*/
|
||||
deleteMarkedInboundPatterns() {
|
||||
this.markedForDeletionInboundPattern.sort((a, b) => b - a);
|
||||
const patternsArray = this.formModel.get('notifyServiceInboundPatterns') as FormArray;
|
||||
|
||||
for (const index of this.markedForDeletionInboundPattern) {
|
||||
if (index >= 0 && index < patternsArray.length) {
|
||||
const patternGroup = patternsArray.at(index) as FormGroup;
|
||||
const patternValue = patternGroup.value;
|
||||
if (patternValue.isNew) {
|
||||
patternsArray.removeAt(index);
|
||||
} else {
|
||||
this.deletedInboundPatterns.push(index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.markedForDeletionInboundPattern = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a replace operation and adds it to the patch operations if the form control is dirty
|
||||
* @param patchOperations - The array to store patch operations
|
||||
* @param formControlName - The name of the form control
|
||||
* @param path - The JSON Patch path for the operation
|
||||
*/
|
||||
private createReplaceOperation(patchOperations: any[], formControlName: string, path: string): void {
|
||||
if (this.formModel.get(formControlName).dirty) {
|
||||
patchOperations.push({
|
||||
op: 'replace',
|
||||
path,
|
||||
value: this.formModel.get(formControlName).value.toString(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles patterns in the form array, checking if an add or replace operations is required
|
||||
* @param patchOperations - The array to store patch operations
|
||||
* @param formArrayName - The name of the form array
|
||||
*/
|
||||
private handlePatterns(patchOperations: any[], formArrayName: string): void {
|
||||
const patternsArray = this.formModel.get(formArrayName) as FormArray;
|
||||
|
||||
for (let i = 0; i < patternsArray.length; i++) {
|
||||
const patternGroup = patternsArray.at(i) as FormGroup;
|
||||
|
||||
const patternValue = patternGroup.value;
|
||||
delete patternValue.constraintFormatted;
|
||||
if (patternGroup.touched && patternGroup.valid) {
|
||||
delete patternValue?.patternLabel;
|
||||
if (patternValue.isNew) {
|
||||
delete patternValue.isNew;
|
||||
const addOperation = {
|
||||
op: 'add',
|
||||
path: `${formArrayName}/-`,
|
||||
value: patternValue,
|
||||
};
|
||||
patchOperations.push(addOperation);
|
||||
} else {
|
||||
const replaceOperation = {
|
||||
op: 'replace',
|
||||
path: `${formArrayName}[${i}]`,
|
||||
value: patternValue,
|
||||
};
|
||||
patchOperations.push(replaceOperation);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigates back to the LDN services page
|
||||
*/
|
||||
private sendBack() {
|
||||
this.router.navigateByUrl('admin/ldn/services');
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a form group for inbound patterns
|
||||
* @returns The form group for inbound patterns
|
||||
*/
|
||||
private createInboundPatternFormGroup(): FormGroup {
|
||||
const inBoundFormGroup = {
|
||||
pattern: '',
|
||||
patternLabel: this.translateService.instant(this.selectPatternDefaultLabeli18Key),
|
||||
constraint: '',
|
||||
constraintFormatted: '',
|
||||
automatic: false,
|
||||
isNew: true
|
||||
};
|
||||
|
||||
if (this.isNewService) {
|
||||
delete inBoundFormGroup.isNew;
|
||||
}
|
||||
|
||||
return this.formBuilder.group(inBoundFormGroup);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes an existing form group for inbound patterns
|
||||
* @returns The initialized form group for inbound patterns
|
||||
*/
|
||||
private initializeInboundPatternFormGroup(): FormGroup {
|
||||
return this.formBuilder.group({
|
||||
pattern: '',
|
||||
patternLabel: '',
|
||||
constraint: '',
|
||||
constraintFormatted: '',
|
||||
automatic: '',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* set ldnUrl error in case of unprocessable entity and provided value
|
||||
*/
|
||||
private setLdnUrlError(): void {
|
||||
const control = this.formModel.controls.ldnUrl;
|
||||
const controlErrors = control.errors || {};
|
||||
control.setErrors({...controlErrors, ldnUrlAlreadyAssociated: true });
|
||||
}
|
||||
}
|
@@ -0,0 +1,111 @@
|
||||
import { LdnService } from '../ldn-services-model/ldn-services.model';
|
||||
import { LDN_SERVICE } from '../ldn-services-model/ldn-service.resource-type';
|
||||
import { RemoteData } from '../../../core/data/remote-data';
|
||||
import { PaginatedList } from '../../../core/data/paginated-list.model';
|
||||
import { Observable, of } from 'rxjs';
|
||||
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
|
||||
|
||||
export const mockLdnService: LdnService = {
|
||||
uuid: '1',
|
||||
enabled: false,
|
||||
score: 0,
|
||||
id: 1,
|
||||
lowerIp: '192.0.2.146',
|
||||
upperIp: '192.0.2.255',
|
||||
name: 'Service Name',
|
||||
description: 'Service Description',
|
||||
url: 'Service URL',
|
||||
ldnUrl: 'Service LDN URL',
|
||||
notifyServiceInboundPatterns: [
|
||||
{
|
||||
pattern: 'patternA',
|
||||
constraint: 'itemFilterA',
|
||||
automatic: 'false',
|
||||
},
|
||||
{
|
||||
pattern: 'patternB',
|
||||
constraint: 'itemFilterB',
|
||||
automatic: 'true',
|
||||
},
|
||||
],
|
||||
type: LDN_SERVICE,
|
||||
_links: {
|
||||
self: {
|
||||
href: 'http://localhost/api/ldn/ldnservices/1'
|
||||
},
|
||||
},
|
||||
get self(): string {
|
||||
return '';
|
||||
},
|
||||
};
|
||||
|
||||
export const mockLdnServiceRD$ = createSuccessfulRemoteDataObject$(mockLdnService);
|
||||
|
||||
|
||||
export const mockLdnServices: LdnService[] = [{
|
||||
uuid: '1',
|
||||
enabled: false,
|
||||
score: 0,
|
||||
id: 1,
|
||||
lowerIp: '192.0.2.146',
|
||||
upperIp: '192.0.2.255',
|
||||
name: 'Service Name',
|
||||
description: 'Service Description',
|
||||
url: 'Service URL',
|
||||
ldnUrl: 'Service LDN URL',
|
||||
notifyServiceInboundPatterns: [
|
||||
{
|
||||
pattern: 'patternA',
|
||||
constraint: 'itemFilterA',
|
||||
automatic: 'false',
|
||||
},
|
||||
{
|
||||
pattern: 'patternB',
|
||||
constraint: 'itemFilterB',
|
||||
automatic: 'true',
|
||||
},
|
||||
],
|
||||
type: LDN_SERVICE,
|
||||
_links: {
|
||||
self: {
|
||||
href: 'http://localhost/api/ldn/ldnservices/1'
|
||||
},
|
||||
},
|
||||
get self(): string {
|
||||
return '';
|
||||
},
|
||||
}, {
|
||||
uuid: '2',
|
||||
enabled: false,
|
||||
score: 0,
|
||||
id: 2,
|
||||
lowerIp: '192.0.2.146',
|
||||
upperIp: '192.0.2.255',
|
||||
name: 'Service Name',
|
||||
description: 'Service Description',
|
||||
url: 'Service URL',
|
||||
ldnUrl: 'Service LDN URL',
|
||||
notifyServiceInboundPatterns: [
|
||||
{
|
||||
pattern: 'patternA',
|
||||
constraint: 'itemFilterA',
|
||||
automatic: 'false',
|
||||
},
|
||||
{
|
||||
pattern: 'patternB',
|
||||
constraint: 'itemFilterB',
|
||||
automatic: 'true',
|
||||
},
|
||||
],
|
||||
type: LDN_SERVICE,
|
||||
_links: {
|
||||
self: {
|
||||
href: 'http://localhost/api/ldn/ldnservices/1'
|
||||
},
|
||||
},
|
||||
get self(): string {
|
||||
return '';
|
||||
},
|
||||
}
|
||||
];
|
||||
export const mockLdnServicesRD$: Observable<RemoteData<PaginatedList<LdnService>>> = of((mockLdnServices as unknown) as RemoteData<PaginatedList<LdnService>>);
|
@@ -0,0 +1,89 @@
|
||||
import { TestScheduler } from 'rxjs/testing';
|
||||
import { LdnItemfiltersService } from './ldn-itemfilters-data.service';
|
||||
import { RequestService } from '../../../core/data/request.service';
|
||||
import { RemoteDataBuildService } from '../../../core/cache/builders/remote-data-build.service';
|
||||
import { ObjectCacheService } from '../../../core/cache/object-cache.service';
|
||||
import { HALEndpointService } from '../../../core/shared/hal-endpoint.service';
|
||||
import { NotificationsService } from '../../../shared/notifications/notifications.service';
|
||||
import { RequestEntry } from '../../../core/data/request-entry.model';
|
||||
import { RemoteData } from '../../../core/data/remote-data';
|
||||
import { RequestEntryState } from '../../../core/data/request-entry-state.model';
|
||||
import { cold, getTestScheduler } from 'jasmine-marbles';
|
||||
import { RestResponse } from '../../../core/cache/response.models';
|
||||
import { of } from 'rxjs';
|
||||
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
|
||||
import { FindAllData } from '../../../core/data/base/find-all-data';
|
||||
import { testFindAllDataImplementation } from '../../../core/data/base/find-all-data.spec';
|
||||
|
||||
describe('LdnItemfiltersService test', () => {
|
||||
let scheduler: TestScheduler;
|
||||
let service: LdnItemfiltersService;
|
||||
let requestService: RequestService;
|
||||
let rdbService: RemoteDataBuildService;
|
||||
let objectCache: ObjectCacheService;
|
||||
let halService: HALEndpointService;
|
||||
let notificationsService: NotificationsService;
|
||||
let responseCacheEntry: RequestEntry;
|
||||
|
||||
const endpointURL = `https://rest.api/rest/api/ldn/itemfilters`;
|
||||
const requestUUID = '8b3c613a-5a4b-438b-9686-be1d5b4a1c5a';
|
||||
|
||||
const remoteDataMocks = {
|
||||
Success: new RemoteData(null, null, null, RequestEntryState.Success, null, null, 200),
|
||||
};
|
||||
|
||||
function initTestService() {
|
||||
return new LdnItemfiltersService(
|
||||
requestService,
|
||||
rdbService,
|
||||
objectCache,
|
||||
halService,
|
||||
notificationsService,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
scheduler = getTestScheduler();
|
||||
|
||||
objectCache = {} as ObjectCacheService;
|
||||
notificationsService = {} as NotificationsService;
|
||||
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: of(responseCacheEntry),
|
||||
getByUUID: of(responseCacheEntry),
|
||||
});
|
||||
|
||||
halService = jasmine.createSpyObj('halService', {
|
||||
getEndpoint: of(endpointURL)
|
||||
});
|
||||
|
||||
rdbService = jasmine.createSpyObj('rdbService', {
|
||||
buildSingle: createSuccessfulRemoteDataObject$({}, 500),
|
||||
buildList: cold('a', { a: remoteDataMocks.Success })
|
||||
});
|
||||
|
||||
|
||||
service = initTestService();
|
||||
});
|
||||
|
||||
describe('composition', () => {
|
||||
const initFindAllService = () => new LdnItemfiltersService(null, null, null, null, null) as unknown as FindAllData<any>;
|
||||
testFindAllDataImplementation(initFindAllService);
|
||||
});
|
||||
|
||||
describe('get endpoint', () => {
|
||||
it('should retrieve correct endpoint', (done) => {
|
||||
service.getEndpoint().subscribe(() => {
|
||||
expect(halService.getEndpoint).toHaveBeenCalledWith('itemfilters');
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
});
|
@@ -0,0 +1,60 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { dataService } from '../../../core/data/base/data-service.decorator';
|
||||
import { LDN_SERVICE_CONSTRAINT_FILTERS } from '../ldn-services-model/ldn-service.resource-type';
|
||||
import { IdentifiableDataService } from '../../../core/data/base/identifiable-data.service';
|
||||
import { FindAllData, FindAllDataImpl } from '../../../core/data/base/find-all-data';
|
||||
|
||||
import { RequestService } from '../../../core/data/request.service';
|
||||
import { RemoteDataBuildService } from '../../../core/cache/builders/remote-data-build.service';
|
||||
import { ObjectCacheService } from '../../../core/cache/object-cache.service';
|
||||
import { HALEndpointService } from '../../../core/shared/hal-endpoint.service';
|
||||
import { NotificationsService } from '../../../shared/notifications/notifications.service';
|
||||
import { FindListOptions } from '../../../core/data/find-list-options.model';
|
||||
import { FollowLinkConfig } from '../../../shared/utils/follow-link-config.model';
|
||||
import { Observable } from 'rxjs';
|
||||
import { RemoteData } from '../../../core/data/remote-data';
|
||||
import { Itemfilter } from '../ldn-services-model/ldn-service-itemfilters';
|
||||
import { PaginatedList } from '../../../core/data/paginated-list.model';
|
||||
|
||||
/**
|
||||
* A service responsible for fetching/sending data from/to the REST API on the itemfilters endpoint
|
||||
*/
|
||||
@Injectable()
|
||||
@dataService(LDN_SERVICE_CONSTRAINT_FILTERS)
|
||||
export class LdnItemfiltersService extends IdentifiableDataService<Itemfilter> implements FindAllData<Itemfilter> {
|
||||
private findAllData: FindAllDataImpl<Itemfilter>;
|
||||
|
||||
constructor(
|
||||
protected requestService: RequestService,
|
||||
protected rdbService: RemoteDataBuildService,
|
||||
protected objectCache: ObjectCacheService,
|
||||
protected halService: HALEndpointService,
|
||||
protected notificationsService: NotificationsService,
|
||||
) {
|
||||
super('itemfilters', requestService, rdbService, objectCache, halService);
|
||||
|
||||
this.findAllData = new FindAllDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the endpoint URL for the itemfilters.
|
||||
*
|
||||
* @returns {string} - The endpoint URL.
|
||||
*/
|
||||
getEndpoint() {
|
||||
return this.halService.getEndpoint(this.linkPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds all itemfilters based on the provided options and link configurations.
|
||||
*
|
||||
* @param {FindListOptions} options - The options for finding a list of itemfilters.
|
||||
* @param {boolean} useCachedVersionIfAvailable - Whether to use the cached version if available.
|
||||
* @param {boolean} reRequestOnStale - Whether to re-request the data if it's stale.
|
||||
* @param {...FollowLinkConfig<Itemfilter>[]} linksToFollow - Configurations for following specific links.
|
||||
* @returns {Observable<RemoteData<PaginatedList<Itemfilter>>>} - An observable of remote data containing a paginated list of itemfilters.
|
||||
*/
|
||||
findAll(options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig<Itemfilter>[]): Observable<RemoteData<PaginatedList<Itemfilter>>> {
|
||||
return this.findAllData.findAll(options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow);
|
||||
}
|
||||
}
|
@@ -0,0 +1,130 @@
|
||||
import { TestScheduler } from 'rxjs/testing';
|
||||
import { RequestService } from '../../../core/data/request.service';
|
||||
import { RemoteDataBuildService } from '../../../core/cache/builders/remote-data-build.service';
|
||||
import { ObjectCacheService } from '../../../core/cache/object-cache.service';
|
||||
import { HALEndpointService } from '../../../core/shared/hal-endpoint.service';
|
||||
import { NotificationsService } from '../../../shared/notifications/notifications.service';
|
||||
import { RequestEntry } from '../../../core/data/request-entry.model';
|
||||
import { RemoteData } from '../../../core/data/remote-data';
|
||||
import { RequestEntryState } from '../../../core/data/request-entry-state.model';
|
||||
import { cold, getTestScheduler } from 'jasmine-marbles';
|
||||
import { RestResponse } from '../../../core/cache/response.models';
|
||||
import { of as observableOf } from 'rxjs';
|
||||
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
|
||||
import { FindAllData } from '../../../core/data/base/find-all-data';
|
||||
import { testFindAllDataImplementation } from '../../../core/data/base/find-all-data.spec';
|
||||
import { LdnServicesService } from './ldn-services-data.service';
|
||||
import { testDeleteDataImplementation } from '../../../core/data/base/delete-data.spec';
|
||||
import { DeleteData } from '../../../core/data/base/delete-data';
|
||||
import { testSearchDataImplementation } from '../../../core/data/base/search-data.spec';
|
||||
import { SearchData } from '../../../core/data/base/search-data';
|
||||
import { testPatchDataImplementation } from '../../../core/data/base/patch-data.spec';
|
||||
import { PatchData } from '../../../core/data/base/patch-data';
|
||||
import { CreateData } from '../../../core/data/base/create-data';
|
||||
import { testCreateDataImplementation } from '../../../core/data/base/create-data.spec';
|
||||
import { FindListOptions } from '../../../core/data/find-list-options.model';
|
||||
import { RequestParam } from '../../../core/cache/models/request-param.model';
|
||||
import { mockLdnService } from '../ldn-service-serviceMock/ldnServicesRD$-mock';
|
||||
import { createPaginatedList } from '../../../shared/testing/utils.test';
|
||||
|
||||
describe('LdnServicesService test', () => {
|
||||
let scheduler: TestScheduler;
|
||||
let service: LdnServicesService;
|
||||
let requestService: RequestService;
|
||||
let rdbService: RemoteDataBuildService;
|
||||
let objectCache: ObjectCacheService;
|
||||
let halService: HALEndpointService;
|
||||
let notificationsService: NotificationsService;
|
||||
let responseCacheEntry: RequestEntry;
|
||||
|
||||
const endpointURL = `https://rest.api/rest/api/ldn/ldnservices`;
|
||||
const requestUUID = '8b3c613a-5a4b-438b-9686-be1d5b4a1c5a';
|
||||
|
||||
const remoteDataMocks = {
|
||||
Success: new RemoteData(null, null, null, RequestEntryState.Success, null, null, 200),
|
||||
};
|
||||
|
||||
function initTestService() {
|
||||
return new LdnServicesService(
|
||||
requestService,
|
||||
rdbService,
|
||||
objectCache,
|
||||
halService,
|
||||
notificationsService,
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
scheduler = getTestScheduler();
|
||||
|
||||
objectCache = {} as ObjectCacheService;
|
||||
notificationsService = {} as NotificationsService;
|
||||
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),
|
||||
});
|
||||
|
||||
halService = jasmine.createSpyObj('halService', {
|
||||
getEndpoint: observableOf(endpointURL)
|
||||
});
|
||||
|
||||
rdbService = jasmine.createSpyObj('rdbService', {
|
||||
buildSingle: createSuccessfulRemoteDataObject$({}, 500),
|
||||
buildFromRequestUUID: createSuccessfulRemoteDataObject$({}, 500),
|
||||
buildList: cold('a', { a: remoteDataMocks.Success })
|
||||
});
|
||||
|
||||
|
||||
service = initTestService();
|
||||
});
|
||||
|
||||
describe('composition', () => {
|
||||
const initFindAllService = () => new LdnServicesService(null, null, null, null, null) as unknown as FindAllData<any>;
|
||||
const initDeleteService = () => new LdnServicesService(null, null, null, null, null) as unknown as DeleteData<any>;
|
||||
const initSearchService = () => new LdnServicesService(null, null, null, null, null) as unknown as SearchData<any>;
|
||||
const initPatchService = () => new LdnServicesService(null, null, null, null, null) as unknown as PatchData<any>;
|
||||
const initCreateService = () => new LdnServicesService(null, null, null, null, null) as unknown as CreateData<any>;
|
||||
|
||||
testFindAllDataImplementation(initFindAllService);
|
||||
testDeleteDataImplementation(initDeleteService);
|
||||
testSearchDataImplementation(initSearchService);
|
||||
testPatchDataImplementation(initPatchService);
|
||||
testCreateDataImplementation(initCreateService);
|
||||
});
|
||||
|
||||
describe('custom methods', () => {
|
||||
it('should find service by inbound pattern', (done) => {
|
||||
const params = [new RequestParam('pattern', 'testPattern')];
|
||||
const findListOptions = Object.assign(new FindListOptions(), {}, {searchParams: params});
|
||||
spyOn(service, 'searchBy').and.returnValue(observableOf(null));
|
||||
spyOn((service as any).searchData, 'searchBy').and.returnValue(createSuccessfulRemoteDataObject$(createPaginatedList([mockLdnService])));
|
||||
|
||||
service.findByInboundPattern('testPattern').subscribe(() => {
|
||||
expect(service.searchBy).toHaveBeenCalledWith('byInboundPattern', findListOptions, undefined, undefined );
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should invoke service', (done) => {
|
||||
const constraints = [{void: true}];
|
||||
const files = [new File([],'fileName')];
|
||||
spyOn(service as any, 'getInvocationFormData');
|
||||
spyOn(service, 'getBrowseEndpoint').and.returnValue(observableOf('testEndpoint'));
|
||||
service.invoke('serviceName', 'serviceId', constraints, files).subscribe(result => {
|
||||
expect((service as any).getInvocationFormData).toHaveBeenCalledWith(constraints, files);
|
||||
expect(service.getBrowseEndpoint).toHaveBeenCalled();
|
||||
expect(result).toBeInstanceOf(RemoteData);
|
||||
done();
|
||||
});
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
});
|
@@ -0,0 +1,216 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { dataService } from '../../../core/data/base/data-service.decorator';
|
||||
import { LDN_SERVICE } from '../ldn-services-model/ldn-service.resource-type';
|
||||
import { IdentifiableDataService } from '../../../core/data/base/identifiable-data.service';
|
||||
import { FindAllData, FindAllDataImpl } from '../../../core/data/base/find-all-data';
|
||||
import { DeleteData, DeleteDataImpl } from '../../../core/data/base/delete-data';
|
||||
import { RequestService } from '../../../core/data/request.service';
|
||||
import { RemoteDataBuildService } from '../../../core/cache/builders/remote-data-build.service';
|
||||
import { ObjectCacheService } from '../../../core/cache/object-cache.service';
|
||||
import { HALEndpointService } from '../../../core/shared/hal-endpoint.service';
|
||||
import { NotificationsService } from '../../../shared/notifications/notifications.service';
|
||||
import { FindListOptions } from '../../../core/data/find-list-options.model';
|
||||
import { FollowLinkConfig } from '../../../shared/utils/follow-link-config.model';
|
||||
import { Observable } from 'rxjs';
|
||||
import { RemoteData } from '../../../core/data/remote-data';
|
||||
import { PaginatedList } from '../../../core/data/paginated-list.model';
|
||||
import { NoContent } from '../../../core/shared/NoContent.model';
|
||||
import { map, take } from 'rxjs/operators';
|
||||
import { URLCombiner } from '../../../core/url-combiner/url-combiner';
|
||||
import { MultipartPostRequest } from '../../../core/data/request.models';
|
||||
import { RestRequest } from '../../../core/data/rest-request.model';
|
||||
|
||||
import { LdnService } from '../ldn-services-model/ldn-services.model';
|
||||
|
||||
import { PatchData, PatchDataImpl } from '../../../core/data/base/patch-data';
|
||||
import { ChangeAnalyzer } from '../../../core/data/change-analyzer';
|
||||
import { Operation } from 'fast-json-patch';
|
||||
import { RestRequestMethod } from '../../../core/data/rest-request-method';
|
||||
import { CreateData, CreateDataImpl } from '../../../core/data/base/create-data';
|
||||
import { LdnServiceConstrain } from '../ldn-services-model/ldn-service.constrain.model';
|
||||
import { SearchDataImpl } from '../../../core/data/base/search-data';
|
||||
import { RequestParam } from '../../../core/cache/models/request-param.model';
|
||||
|
||||
/**
|
||||
* Injectable service responsible for fetching/sending data from/to the REST API on the ldnservices endpoint.
|
||||
*
|
||||
* @export
|
||||
* @class LdnServicesService
|
||||
* @extends {IdentifiableDataService<LdnService>}
|
||||
* @implements {FindAllData<LdnService>}
|
||||
* @implements {DeleteData<LdnService>}
|
||||
* @implements {PatchData<LdnService>}
|
||||
* @implements {CreateData<LdnService>}
|
||||
*/
|
||||
@Injectable()
|
||||
@dataService(LDN_SERVICE)
|
||||
export class LdnServicesService extends IdentifiableDataService<LdnService> implements FindAllData<LdnService>, DeleteData<LdnService>, PatchData<LdnService>, CreateData<LdnService> {
|
||||
createData: CreateDataImpl<LdnService>;
|
||||
private findAllData: FindAllDataImpl<LdnService>;
|
||||
private deleteData: DeleteDataImpl<LdnService>;
|
||||
private patchData: PatchDataImpl<LdnService>;
|
||||
private comparator: ChangeAnalyzer<LdnService>;
|
||||
private searchData: SearchDataImpl<LdnService>;
|
||||
|
||||
private findByPatternEndpoint = 'byInboundPattern';
|
||||
|
||||
constructor(
|
||||
protected requestService: RequestService,
|
||||
protected rdbService: RemoteDataBuildService,
|
||||
protected objectCache: ObjectCacheService,
|
||||
protected halService: HALEndpointService,
|
||||
protected notificationsService: NotificationsService,
|
||||
) {
|
||||
super('ldnservices', requestService, rdbService, objectCache, halService);
|
||||
|
||||
this.findAllData = new FindAllDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive);
|
||||
this.searchData = new SearchDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive);
|
||||
this.deleteData = new DeleteDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, notificationsService, this.responseMsToLive, this.constructIdEndpoint);
|
||||
this.patchData = new PatchDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.comparator, this.responseMsToLive, this.constructIdEndpoint);
|
||||
this.createData = new CreateDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, notificationsService, this.responseMsToLive);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an LDN service by sending a POST request to the REST API.
|
||||
*
|
||||
* @param {LdnService} object - The LDN service object to be created.
|
||||
* @param params Array with additional params to combine with query string
|
||||
* @returns {Observable<RemoteData<LdnService>>} - Observable containing the result of the creation operation.
|
||||
*/
|
||||
create(object: LdnService, ...params: RequestParam[]): Observable<RemoteData<LdnService>> {
|
||||
return this.createData.create(object, ...params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates an LDN service by applying a set of operations through a PATCH request to the REST API.
|
||||
*
|
||||
* @param {LdnService} object - The LDN service object to be updated.
|
||||
* @param {Operation[]} operations - The patch operations to be applied.
|
||||
* @returns {Observable<RemoteData<LdnService>>} - Observable containing the result of the update operation.
|
||||
*/
|
||||
patch(object: LdnService, operations: Operation[]): Observable<RemoteData<LdnService>> {
|
||||
return this.patchData.patch(object, operations);
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates an LDN service by sending a PUT request to the REST API.
|
||||
*
|
||||
* @param {LdnService} object - The LDN service object to be updated.
|
||||
* @returns {Observable<RemoteData<LdnService>>} - Observable containing the result of the update operation.
|
||||
*/
|
||||
update(object: LdnService): Observable<RemoteData<LdnService>> {
|
||||
return this.patchData.update(object);
|
||||
}
|
||||
|
||||
/**
|
||||
* Commits pending updates by sending a PATCH request to the REST API.
|
||||
*
|
||||
* @param {RestRequestMethod} [method] - The HTTP method to be used for the request.
|
||||
*/
|
||||
commitUpdates(method?: RestRequestMethod): void {
|
||||
return this.patchData.commitUpdates(method);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a patch representing the changes made to the LDN service in the cache.
|
||||
*
|
||||
* @param {LdnService} object - The LDN service object for which to create the patch.
|
||||
* @returns {Observable<Operation[]>} - Observable containing the patch operations.
|
||||
*/
|
||||
createPatchFromCache(object: LdnService): Observable<Operation[]> {
|
||||
return this.patchData.createPatchFromCache(object);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves all LDN services from the REST API based on the provided options.
|
||||
*
|
||||
* @param {FindListOptions} [options] - The options to be applied to the request.
|
||||
* @param {boolean} [useCachedVersionIfAvailable] - Flag indicating whether to use cached data if available.
|
||||
* @param {boolean} [reRequestOnStale] - Flag indicating whether to re-request data if it's stale.
|
||||
* @param {...FollowLinkConfig<LdnService>[]} linksToFollow - Optional links to follow during the request.
|
||||
* @returns {Observable<RemoteData<PaginatedList<LdnService>>>} - Observable containing the result of the request.
|
||||
*/
|
||||
findAll(options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig<LdnService>[]): Observable<RemoteData<PaginatedList<LdnService>>> {
|
||||
return this.findAllData.findAll(options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow);
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves LDN services based on the inbound pattern from the REST API.
|
||||
*
|
||||
* @param {string} pattern - The inbound pattern to be used in the search.
|
||||
* @param {FindListOptions} [options] - The options to be applied to the request.
|
||||
* @param {boolean} [useCachedVersionIfAvailable] - Flag indicating whether to use cached data if available.
|
||||
* @param {boolean} [reRequestOnStale] - Flag indicating whether to re-request data if it's stale.
|
||||
* @param {...FollowLinkConfig<LdnService>[]} linksToFollow - Optional links to follow during the request.
|
||||
* @returns {Observable<RemoteData<PaginatedList<LdnService>>>} - Observable containing the result of the request.
|
||||
*/
|
||||
findByInboundPattern(pattern: string, options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig<LdnService>[]): Observable<RemoteData<PaginatedList<LdnService>>> {
|
||||
const params = [new RequestParam('pattern', pattern)];
|
||||
const findListOptions = Object.assign(new FindListOptions(), options, {searchParams: params});
|
||||
return this.searchBy(this.findByPatternEndpoint, findListOptions, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an LDN service by sending a DELETE request to the REST API.
|
||||
*
|
||||
* @param {string} objectId - The ID of the LDN service to be deleted.
|
||||
* @param {string[]} [copyVirtualMetadata] - Optional virtual metadata to be copied during the deletion.
|
||||
* @returns {Observable<RemoteData<NoContent>>} - Observable containing the result of the deletion operation.
|
||||
*/
|
||||
public delete(objectId: string, copyVirtualMetadata?: string[]): Observable<RemoteData<NoContent>> {
|
||||
return this.deleteData.delete(objectId, copyVirtualMetadata);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes an LDN service by its HATEOAS link.
|
||||
*
|
||||
* @param {string} href - The HATEOAS link of the LDN service to be deleted.
|
||||
* @param {string[]} [copyVirtualMetadata] - Optional virtual metadata to be copied during the deletion.
|
||||
* @returns {Observable<RemoteData<NoContent>>} - Observable containing the result of the deletion operation.
|
||||
*/
|
||||
public deleteByHref(href: string, copyVirtualMetadata?: string[]): Observable<RemoteData<NoContent>> {
|
||||
return this.deleteData.deleteByHref(href, copyVirtualMetadata);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Make a new FindListRequest with given search method
|
||||
*
|
||||
* @param searchMethod The search method for the object
|
||||
* @param options The [[FindListOptions]] object
|
||||
* @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
|
||||
* @return {Observable<RemoteData<PaginatedList<T>>}
|
||||
* Return an observable that emits response from the server
|
||||
*/
|
||||
public searchBy(searchMethod: string, options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig<LdnService>[]): Observable<RemoteData<PaginatedList<LdnService>>> {
|
||||
return this.searchData.searchBy(searchMethod, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow);
|
||||
}
|
||||
|
||||
public invoke(serviceName: string, serviceId: string, parameters: LdnServiceConstrain[], files: File[]): Observable<RemoteData<LdnService>> {
|
||||
const requestId = this.requestService.generateRequestId();
|
||||
this.getBrowseEndpoint().pipe(
|
||||
take(1),
|
||||
map((endpoint: string) => new URLCombiner(endpoint, serviceName, 'processes', serviceId).toString()),
|
||||
map((endpoint: string) => {
|
||||
const body = this.getInvocationFormData(parameters, files);
|
||||
return new MultipartPostRequest(requestId, endpoint, body);
|
||||
})
|
||||
).subscribe((request: RestRequest) => this.requestService.send(request));
|
||||
|
||||
return this.rdbService.buildFromRequestUUID<LdnService>(requestId);
|
||||
}
|
||||
|
||||
private getInvocationFormData(constrain: LdnServiceConstrain[], files: File[]): FormData {
|
||||
const form: FormData = new FormData();
|
||||
form.set('properties', JSON.stringify(constrain));
|
||||
files.forEach((file: File) => {
|
||||
form.append('file', file);
|
||||
});
|
||||
return form;
|
||||
}
|
||||
}
|
@@ -0,0 +1,99 @@
|
||||
<div class="container">
|
||||
<div class="d-flex">
|
||||
<h1 class="flex-grow-1">{{ 'ldn-registered-services.title' | translate }}</h1>
|
||||
</div>
|
||||
<div class="d-flex justify-content-end">
|
||||
<button class="btn btn-success" routerLink="/admin/ldn/services/new"><i
|
||||
class="fas fa-plus pr-2"></i>{{ 'process.overview.new' | translate }}</button>
|
||||
</div>
|
||||
<ds-pagination *ngIf="(ldnServicesRD$ | async)?.payload?.totalElements > 0"
|
||||
[collectionSize]="(ldnServicesRD$ | async)?.payload?.totalElements"
|
||||
[hideGear]="true"
|
||||
[hidePagerWhenSinglePage]="true"
|
||||
[pageInfoState]="(ldnServicesRD$ | async)?.payload"
|
||||
[paginationOptions]="pageConfig">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-striped table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">{{ 'service.overview.table.name' | translate }}</th>
|
||||
<th scope="col">{{ 'service.overview.table.description' | translate }}</th>
|
||||
<th scope="col">{{ 'service.overview.table.status' | translate }}</th>
|
||||
<th scope="col">{{ 'service.overview.table.actions' | translate }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr *ngFor="let ldnService of (ldnServicesRD$ | async)?.payload?.page">
|
||||
<td class="col-3">{{ ldnService.name }}</td>
|
||||
<td>
|
||||
<ds-truncatable [id]="ldnService.id">
|
||||
<ds-truncatable-part [id]="ldnService.id" [minLines]="2">
|
||||
<div>
|
||||
{{ ldnService.description }}
|
||||
</div>
|
||||
</ds-truncatable-part>
|
||||
</ds-truncatable>
|
||||
</td>
|
||||
<td>
|
||||
<span (click)="toggleStatus(ldnService, ldnServicesService)"
|
||||
[ngClass]="{ 'status-enabled': ldnService.enabled, 'status-disabled': !ldnService.enabled }"
|
||||
[title]="ldnService.enabled ? ('ldn-service.overview.table.clickToDisable' | translate) : ('ldn-service.overview.table.clickToEnable' | translate)"
|
||||
class="status-indicator">
|
||||
{{ ldnService.enabled ? ('ldn-service.overview.table.enabled' | translate) : ('ldn-service.overview.table.disabled' | translate) }}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<div class="btn-group">
|
||||
<button
|
||||
(click)="selectServiceToDelete(ldnService.id)"
|
||||
[attr.aria-label]="'ldn-service-overview-select-delete' | translate"
|
||||
class="btn btn-outline-danger">
|
||||
<i class="fas fa-trash"></i>
|
||||
</button>
|
||||
<button [routerLink]="['/admin/ldn/services/edit/', ldnService.id]"
|
||||
[attr.aria-label]="'ldn-service-overview-select-edit' | translate"
|
||||
class="btn btn-outline-dark">
|
||||
<i class="fas fa-edit"></i>
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</ds-pagination>
|
||||
</div>
|
||||
|
||||
<ng-template #deleteModal>
|
||||
|
||||
<div>
|
||||
|
||||
<div class="modal-header">
|
||||
<div>
|
||||
<h4>{{'service.overview.delete.header' | translate }}</h4>
|
||||
</div>
|
||||
<button (click)="closeModal()" aria-label="Close"
|
||||
[attr.aria-label]="'ldn-service-overview-close-modal' | translate"
|
||||
class="close" type="button">
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="modal-body">
|
||||
<div>
|
||||
{{ 'service.overview.delete.body' | translate }}
|
||||
</div>
|
||||
<div class="mt-4">
|
||||
<button (click)="closeModal()"
|
||||
[attr.aria-label]="'ldn-service-overview-close-modal' | translate"
|
||||
class="btn btn-primary mr-2">{{ 'service.detail.delete.cancel' | translate }}</button>
|
||||
<button (click)="deleteSelected(this.selectedServiceId.toString(), ldnServicesService)"
|
||||
class="btn btn-danger"
|
||||
[attr.aria-label]="'ldn-service-overview-select-delete' | translate"
|
||||
id="delete-confirm">{{ 'service.overview.delete' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</ng-template>
|
||||
|
@@ -0,0 +1,29 @@
|
||||
.status-indicator {
|
||||
padding: 2.5px 25px 2.5px 25px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.5s;
|
||||
}
|
||||
|
||||
.status-enabled {
|
||||
background-color: #daf7a6;
|
||||
color: #4f5359;
|
||||
font-size: 85%;
|
||||
font-weight: bold;
|
||||
|
||||
}
|
||||
|
||||
.status-enabled:hover {
|
||||
background-color: #faa0a0;
|
||||
}
|
||||
|
||||
.status-disabled {
|
||||
background-color: #faa0a0;
|
||||
color: #4f5359;
|
||||
font-size: 85%;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.status-disabled:hover {
|
||||
background-color: #daf7a6;
|
||||
}
|
@@ -0,0 +1,163 @@
|
||||
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
|
||||
import { ChangeDetectorRef, EventEmitter, NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
import { NotificationsService } from '../../../shared/notifications/notifications.service';
|
||||
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
|
||||
import { TranslateModule, TranslateService } from '@ngx-translate/core';
|
||||
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { LdnServicesService } from '../ldn-services-data/ldn-services-data.service';
|
||||
import { PaginationService } from '../../../core/pagination/pagination.service';
|
||||
import { PaginationServiceStub } from '../../../shared/testing/pagination-service.stub';
|
||||
import { of } from 'rxjs';
|
||||
import { LdnService } from '../ldn-services-model/ldn-services.model';
|
||||
import { PaginatedList } from '../../../core/data/paginated-list.model';
|
||||
import { RemoteData } from '../../../core/data/remote-data';
|
||||
import { LdnServicesOverviewComponent } from './ldn-services-directory.component';
|
||||
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
|
||||
import { createPaginatedList } from '../../../shared/testing/utils.test';
|
||||
|
||||
describe('LdnServicesOverviewComponent', () => {
|
||||
let component: LdnServicesOverviewComponent;
|
||||
let fixture: ComponentFixture<LdnServicesOverviewComponent>;
|
||||
let ldnServicesService;
|
||||
let paginationService;
|
||||
let modalService: NgbModal;
|
||||
|
||||
const translateServiceStub = {
|
||||
get: () => of('translated-text'),
|
||||
onLangChange: new EventEmitter(),
|
||||
onTranslationChange: new EventEmitter(),
|
||||
onDefaultLangChange: new EventEmitter()
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
paginationService = new PaginationServiceStub();
|
||||
ldnServicesService = jasmine.createSpyObj('ldnServicesService', {
|
||||
'findAll': createSuccessfulRemoteDataObject$({}),
|
||||
'delete': createSuccessfulRemoteDataObject$({}),
|
||||
'patch': createSuccessfulRemoteDataObject$({}),
|
||||
});
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [TranslateModule.forRoot()],
|
||||
declarations: [LdnServicesOverviewComponent],
|
||||
providers: [
|
||||
{
|
||||
provide: LdnServicesService,
|
||||
useValue: ldnServicesService
|
||||
},
|
||||
{provide: PaginationService, useValue: paginationService},
|
||||
{
|
||||
provide: NgbModal, useValue: {
|
||||
open: () => { /*comment*/
|
||||
}
|
||||
}
|
||||
},
|
||||
{provide: ChangeDetectorRef, useValue: {}},
|
||||
{provide: NotificationsService, useValue: new NotificationsServiceStub()},
|
||||
{provide: TranslateService, useValue: translateServiceStub},
|
||||
],
|
||||
schemas: [NO_ERRORS_SCHEMA]
|
||||
}).compileComponents();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(LdnServicesOverviewComponent);
|
||||
component = fixture.componentInstance;
|
||||
ldnServicesService = TestBed.inject(LdnServicesService);
|
||||
paginationService = TestBed.inject(PaginationService);
|
||||
modalService = TestBed.inject(NgbModal);
|
||||
component.modalRef = jasmine.createSpyObj({close: null});
|
||||
component.isProcessingSub = jasmine.createSpyObj({unsubscribe: null});
|
||||
component.ldnServicesRD$ = of({} as RemoteData<PaginatedList<LdnService>>);
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
|
||||
describe('ngOnInit', () => {
|
||||
it('should call setLdnServices', fakeAsync(() => {
|
||||
spyOn(component, 'setLdnServices').and.callThrough();
|
||||
component.ngOnInit();
|
||||
tick();
|
||||
expect(component.setLdnServices).toHaveBeenCalled();
|
||||
}));
|
||||
|
||||
it('should set ldnServicesRD$ with mock data', fakeAsync(() => {
|
||||
spyOn(component, 'setLdnServices').and.callThrough();
|
||||
const testData: LdnService[] = Object.assign([new LdnService()], [
|
||||
{id: 1, name: 'Service 1', description: 'Description 1', enabled: true},
|
||||
{id: 2, name: 'Service 2', description: 'Description 2', enabled: false},
|
||||
{id: 3, name: 'Service 3', description: 'Description 3', enabled: true}]);
|
||||
|
||||
const mockLdnServicesRD = createPaginatedList(testData);
|
||||
component.ldnServicesRD$ = createSuccessfulRemoteDataObject$(mockLdnServicesRD);
|
||||
fixture.detectChanges();
|
||||
|
||||
const tableRows = fixture.debugElement.nativeElement.querySelectorAll('tbody tr');
|
||||
expect(tableRows.length).toBe(testData.length);
|
||||
const firstRowContent = tableRows[0].textContent;
|
||||
expect(firstRowContent).toContain('Service 1');
|
||||
expect(firstRowContent).toContain('Description 1');
|
||||
}));
|
||||
});
|
||||
|
||||
describe('ngOnDestroy', () => {
|
||||
it('should call paginationService.clearPagination and unsubscribe', () => {
|
||||
// spyOn(paginationService, 'clearPagination');
|
||||
// spyOn(component.isProcessingSub, 'unsubscribe');
|
||||
component.ngOnDestroy();
|
||||
expect(paginationService.clearPagination).toHaveBeenCalledWith(component.pageConfig.id);
|
||||
expect(component.isProcessingSub.unsubscribe).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('openDeleteModal', () => {
|
||||
it('should open delete modal', () => {
|
||||
spyOn(modalService, 'open');
|
||||
component.openDeleteModal(component.deleteModal);
|
||||
expect(modalService.open).toHaveBeenCalledWith(component.deleteModal);
|
||||
});
|
||||
});
|
||||
|
||||
describe('closeModal', () => {
|
||||
it('should close modal and detect changes', () => {
|
||||
// spyOn(component.modalRef, 'close');
|
||||
spyOn(component.cdRef, 'detectChanges');
|
||||
component.closeModal();
|
||||
expect(component.modalRef.close).toHaveBeenCalled();
|
||||
expect(component.cdRef.detectChanges).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteSelected', () => {
|
||||
it('should delete selected service and update data', fakeAsync(() => {
|
||||
const serviceId = '123';
|
||||
const mockRemoteData = { /* just an empty object to retrieve as as RemoteData<PaginatedList<LdnService>> */};
|
||||
spyOn(component, 'setLdnServices').and.callThrough();
|
||||
const deleteSpy = ldnServicesService.delete.and.returnValue(of(mockRemoteData as RemoteData<PaginatedList<LdnService>>));
|
||||
component.selectedServiceId = serviceId;
|
||||
component.deleteSelected(serviceId, ldnServicesService);
|
||||
tick();
|
||||
expect(deleteSpy).toHaveBeenCalledWith(serviceId);
|
||||
}));
|
||||
});
|
||||
|
||||
describe('selectServiceToDelete', () => {
|
||||
it('should set service to delete', fakeAsync(() => {
|
||||
spyOn(component, 'openDeleteModal');
|
||||
const serviceId = 123;
|
||||
component.selectServiceToDelete(serviceId);
|
||||
expect(component.selectedServiceId).toEqual(serviceId);
|
||||
expect(component.openDeleteModal).toHaveBeenCalled();
|
||||
}));
|
||||
});
|
||||
|
||||
describe('toggleStatus', () => {
|
||||
it('should toggle status', (() => {
|
||||
component.toggleStatus({enabled: false}, ldnServicesService);
|
||||
expect(ldnServicesService.patch).toHaveBeenCalled();
|
||||
}));
|
||||
});
|
||||
|
||||
});
|
@@ -0,0 +1,167 @@
|
||||
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnDestroy, OnInit, TemplateRef, ViewChild } from '@angular/core';
|
||||
import { Observable, Subscription } from 'rxjs';
|
||||
import { RemoteData } from '../../../core/data/remote-data';
|
||||
import { PaginatedList } from '../../../core/data/paginated-list.model';
|
||||
import { FindListOptions } from '../../../core/data/find-list-options.model';
|
||||
import { LdnService } from '../ldn-services-model/ldn-services.model';
|
||||
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
|
||||
import { map, switchMap } from 'rxjs/operators';
|
||||
import { LdnServicesService } from 'src/app/admin/admin-ldn-services/ldn-services-data/ldn-services-data.service';
|
||||
import { PaginationService } from 'src/app/core/pagination/pagination.service';
|
||||
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { hasValue } from '../../../shared/empty.util';
|
||||
import { Operation } from 'fast-json-patch';
|
||||
import { getFirstCompletedRemoteData } from '../../../core/shared/operators';
|
||||
import { NotificationsService } from '../../../shared/notifications/notifications.service';
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
|
||||
/**
|
||||
* The `LdnServicesOverviewComponent` is a component that provides an overview of LDN (Linked Data Notifications) services.
|
||||
* It displays a paginated list of LDN services, allows users to edit and delete services,
|
||||
* toggle the status of each service directly form the page and allows for creation of new services redirecting the user on the creation/edit form
|
||||
*/
|
||||
@Component({
|
||||
selector: 'ds-ldn-services-directory',
|
||||
templateUrl: './ldn-services-directory.component.html',
|
||||
styleUrls: ['./ldn-services-directory.component.scss'],
|
||||
changeDetection: ChangeDetectionStrategy.Default
|
||||
})
|
||||
export class LdnServicesOverviewComponent implements OnInit, OnDestroy {
|
||||
|
||||
selectedServiceId: string | number | null = null;
|
||||
servicesData: any[] = [];
|
||||
@ViewChild('deleteModal', {static: true}) deleteModal: TemplateRef<any>;
|
||||
ldnServicesRD$: Observable<RemoteData<PaginatedList<LdnService>>>;
|
||||
config: FindListOptions = Object.assign(new FindListOptions(), {
|
||||
elementsPerPage: 10
|
||||
});
|
||||
pageConfig: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), {
|
||||
id: 'po',
|
||||
pageSize: 10
|
||||
});
|
||||
isProcessingSub: Subscription;
|
||||
modalRef: any;
|
||||
|
||||
|
||||
constructor(
|
||||
protected ldnServicesService: LdnServicesService,
|
||||
protected paginationService: PaginationService,
|
||||
protected modalService: NgbModal,
|
||||
public cdRef: ChangeDetectorRef,
|
||||
private notificationService: NotificationsService,
|
||||
private translateService: TranslateService,
|
||||
) {
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
this.setLdnServices();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up the LDN services by fetching and observing the paginated list of services.
|
||||
*/
|
||||
setLdnServices() {
|
||||
this.ldnServicesRD$ = this.paginationService.getFindListOptions(this.pageConfig.id, this.config).pipe(
|
||||
switchMap((config) => this.ldnServicesService.findAll(config, false, false).pipe(
|
||||
getFirstCompletedRemoteData()
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.paginationService.clearPagination(this.pageConfig.id);
|
||||
if (hasValue(this.isProcessingSub)) {
|
||||
this.isProcessingSub.unsubscribe();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the delete confirmation modal.
|
||||
*
|
||||
* @param {any} content - The content of the modal.
|
||||
*/
|
||||
openDeleteModal(content) {
|
||||
this.modalRef = this.modalService.open(content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes the currently open modal and triggers change detection.
|
||||
*/
|
||||
closeModal() {
|
||||
this.modalRef.close();
|
||||
this.cdRef.detectChanges();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the selected LDN service ID for deletion and opens the delete confirmation modal.
|
||||
*
|
||||
* @param {number} serviceId - The ID of the service to be deleted.
|
||||
*/
|
||||
selectServiceToDelete(serviceId: number) {
|
||||
this.selectedServiceId = serviceId;
|
||||
this.openDeleteModal(this.deleteModal);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the selected LDN service.
|
||||
*
|
||||
* @param {string} serviceId - The ID of the service to be deleted.
|
||||
* @param {LdnServicesService} ldnServicesService - The service for managing LDN services.
|
||||
*/
|
||||
deleteSelected(serviceId: string, ldnServicesService: LdnServicesService): void {
|
||||
if (this.selectedServiceId !== null) {
|
||||
ldnServicesService.delete(serviceId).pipe(getFirstCompletedRemoteData()).subscribe((rd: RemoteData<LdnService>) => {
|
||||
if (rd.hasSucceeded) {
|
||||
this.servicesData = this.servicesData.filter(service => service.id !== serviceId);
|
||||
this.ldnServicesRD$ = this.ldnServicesRD$.pipe(
|
||||
map((remoteData: RemoteData<PaginatedList<LdnService>>) => {
|
||||
if (remoteData.hasSucceeded) {
|
||||
remoteData.payload.page = remoteData.payload.page.filter(service => service.id.toString() !== serviceId);
|
||||
}
|
||||
return remoteData;
|
||||
})
|
||||
);
|
||||
this.cdRef.detectChanges();
|
||||
this.closeModal();
|
||||
this.notificationService.success(this.translateService.get('ldn-service-delete.notification.success.title'),
|
||||
this.translateService.get('ldn-service-delete.notification.success.content'));
|
||||
} else {
|
||||
this.notificationService.error(this.translateService.get('ldn-service-delete.notification.error.title'),
|
||||
this.translateService.get('ldn-service-delete.notification.error.content'));
|
||||
this.cdRef.detectChanges();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggles the status (enabled/disabled) of an LDN service.
|
||||
*
|
||||
* @param {any} ldnService - The LDN service object.
|
||||
* @param {LdnServicesService} ldnServicesService - The service for managing LDN services.
|
||||
*/
|
||||
toggleStatus(ldnService: any, ldnServicesService: LdnServicesService): void {
|
||||
const newStatus = !ldnService.enabled;
|
||||
const originalStatus = ldnService.enabled;
|
||||
|
||||
const patchOperation: Operation = {
|
||||
op: 'replace',
|
||||
path: '/enabled',
|
||||
value: newStatus,
|
||||
};
|
||||
|
||||
ldnServicesService.patch(ldnService, [patchOperation]).pipe(getFirstCompletedRemoteData()).subscribe(
|
||||
(rd: RemoteData<LdnService>) => {
|
||||
if (rd.hasSucceeded) {
|
||||
ldnService.enabled = newStatus;
|
||||
this.notificationService.success(this.translateService.get('ldn-enable-service.notification.success.title'),
|
||||
this.translateService.get('ldn-enable-service.notification.success.content'));
|
||||
} else {
|
||||
ldnService.enabled = originalStatus;
|
||||
this.notificationService.error(this.translateService.get('ldn-enable-service.notification.error.title'),
|
||||
this.translateService.get('ldn-enable-service.notification.error.content'));
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
@@ -0,0 +1,31 @@
|
||||
import { autoserialize, deserialize, inheritSerialization } from 'cerialize';
|
||||
import { LDN_SERVICE_CONSTRAINT_FILTER } from './ldn-service.resource-type';
|
||||
import { CacheableObject } from '../../../core/cache/cacheable-object.model';
|
||||
import { typedObject } from '../../../core/cache/builders/build-decorators';
|
||||
import { excludeFromEquals } from '../../../core/utilities/equals.decorators';
|
||||
import { ResourceType } from '../../../core/shared/resource-type';
|
||||
|
||||
/** A single filter value and its properties. */
|
||||
@typedObject
|
||||
@inheritSerialization(CacheableObject)
|
||||
export class Itemfilter extends CacheableObject {
|
||||
static type = LDN_SERVICE_CONSTRAINT_FILTER;
|
||||
|
||||
@excludeFromEquals
|
||||
@autoserialize
|
||||
type: ResourceType;
|
||||
|
||||
@autoserialize
|
||||
id: string;
|
||||
|
||||
@deserialize
|
||||
_links: {
|
||||
self: {
|
||||
href: string;
|
||||
};
|
||||
};
|
||||
|
||||
get self(): string {
|
||||
return this._links.self.href;
|
||||
}
|
||||
}
|
@@ -0,0 +1,13 @@
|
||||
import { autoserialize } from 'cerialize';
|
||||
|
||||
/**
|
||||
* A single notify service pattern and his properties
|
||||
*/
|
||||
export class NotifyServicePattern {
|
||||
@autoserialize
|
||||
pattern: string;
|
||||
@autoserialize
|
||||
constraint: string;
|
||||
@autoserialize
|
||||
automatic: string;
|
||||
}
|
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* List of services statuses
|
||||
*/
|
||||
export enum LdnServiceStatus {
|
||||
UNKOWN,
|
||||
DISABLED,
|
||||
ENABLED,
|
||||
}
|
@@ -0,0 +1,3 @@
|
||||
export class LdnServiceConstrain {
|
||||
void: any;
|
||||
}
|
@@ -0,0 +1,12 @@
|
||||
/**
|
||||
* The resource type for Ldn-Services
|
||||
*
|
||||
* Needs to be in a separate file to prevent circular
|
||||
* dependencies in webpack.
|
||||
*/
|
||||
import { ResourceType } from '../../../core/shared/resource-type';
|
||||
|
||||
export const LDN_SERVICE = new ResourceType('ldnservice');
|
||||
export const LDN_SERVICE_CONSTRAINT_FILTERS = new ResourceType('itemfilters');
|
||||
|
||||
export const LDN_SERVICE_CONSTRAINT_FILTER = new ResourceType('itemfilter');
|
@@ -0,0 +1,71 @@
|
||||
import { ResourceType } from '../../../core/shared/resource-type';
|
||||
import { CacheableObject } from '../../../core/cache/cacheable-object.model';
|
||||
import { autoserialize, deserialize, deserializeAs, inheritSerialization } from 'cerialize';
|
||||
import { LDN_SERVICE } from './ldn-service.resource-type';
|
||||
import { excludeFromEquals } from '../../../core/utilities/equals.decorators';
|
||||
import { typedObject } from '../../../core/cache/builders/build-decorators';
|
||||
import { NotifyServicePattern } from './ldn-service-patterns.model';
|
||||
|
||||
/**
|
||||
* LDN Services bounded to each selected pattern, relation set in service creation
|
||||
*/
|
||||
|
||||
export interface LdnServiceByPattern {
|
||||
allowsMultipleRequests: boolean;
|
||||
services: LdnService[];
|
||||
}
|
||||
|
||||
/** An LdnService and its properties. */
|
||||
@typedObject
|
||||
@inheritSerialization(CacheableObject)
|
||||
export class LdnService extends CacheableObject {
|
||||
static type = LDN_SERVICE;
|
||||
|
||||
@excludeFromEquals
|
||||
@autoserialize
|
||||
type: ResourceType;
|
||||
|
||||
@autoserialize
|
||||
id: number;
|
||||
|
||||
@deserializeAs('id')
|
||||
uuid: string;
|
||||
|
||||
@autoserialize
|
||||
name: string;
|
||||
|
||||
@autoserialize
|
||||
description: string;
|
||||
|
||||
@autoserialize
|
||||
url: string;
|
||||
|
||||
@autoserialize
|
||||
score: number;
|
||||
|
||||
@autoserialize
|
||||
enabled: boolean;
|
||||
|
||||
@autoserialize
|
||||
ldnUrl: string;
|
||||
|
||||
@autoserialize
|
||||
lowerIp: string;
|
||||
|
||||
@autoserialize
|
||||
upperIp: string;
|
||||
|
||||
@autoserialize
|
||||
notifyServiceInboundPatterns?: NotifyServicePattern[];
|
||||
|
||||
@deserialize
|
||||
_links: {
|
||||
self: {
|
||||
href: string;
|
||||
};
|
||||
};
|
||||
|
||||
get self(): string {
|
||||
return this._links.self.href;
|
||||
}
|
||||
}
|
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* List of parameter types used for scripts
|
||||
*/
|
||||
export enum LdnServiceConstrainType {
|
||||
STRING = 'String',
|
||||
DATE = 'date',
|
||||
BOOLEAN = 'boolean',
|
||||
FILE = 'InputStream',
|
||||
OUTPUT = 'OutputStream'
|
||||
}
|
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* All available patterns for LDN service creation.
|
||||
* They are used to populate a dropdown in the LDN service form creation
|
||||
*/
|
||||
|
||||
export const notifyPatterns = [
|
||||
|
||||
'request-endorsement',
|
||||
|
||||
'request-ingest',
|
||||
|
||||
'request-review',
|
||||
|
||||
];
|
||||
|
||||
|
@@ -0,0 +1,32 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
|
||||
|
||||
/**
|
||||
* Interface for the route parameters.
|
||||
*/
|
||||
export interface NotificationsSuggestionTargetsPageParams {
|
||||
pageId?: string;
|
||||
pageSize?: number;
|
||||
currentPage?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* This class represents a resolver that retrieve the route data before the route is activated.
|
||||
*/
|
||||
@Injectable()
|
||||
export class NotificationsSuggestionTargetsPageResolver implements Resolve<NotificationsSuggestionTargetsPageParams> {
|
||||
|
||||
/**
|
||||
* Method for resolving the parameters in the current route.
|
||||
* @param {ActivatedRouteSnapshot} route The current ActivatedRouteSnapshot
|
||||
* @param {RouterStateSnapshot} state The current RouterStateSnapshot
|
||||
* @returns AdminNotificationsSuggestionTargetsPageParams Emits the route parameters
|
||||
*/
|
||||
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): NotificationsSuggestionTargetsPageParams {
|
||||
return {
|
||||
pageId: route.queryParams.pageId,
|
||||
pageSize: parseInt(route.queryParams.pageSize, 10),
|
||||
currentPage: parseInt(route.queryParams.page, 10)
|
||||
};
|
||||
}
|
||||
}
|
@@ -0,0 +1 @@
|
||||
<ds-publication-claim [source]="'openaire'"></ds-publication-claim>
|
@@ -0,0 +1,38 @@
|
||||
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
import { NotificationsSuggestionTargetsPageComponent } from '../../../quality-assurance-notifications-pages/notifications-suggestion-targets-page/notifications-suggestion-targets-page.component';
|
||||
|
||||
describe('NotificationsSuggestionTargetsPageComponent', () => {
|
||||
let component: NotificationsSuggestionTargetsPageComponent;
|
||||
let fixture: ComponentFixture<NotificationsSuggestionTargetsPageComponent>;
|
||||
|
||||
beforeEach(async(() => {
|
||||
TestBed.configureTestingModule({
|
||||
imports: [
|
||||
CommonModule,
|
||||
TranslateModule.forRoot()
|
||||
],
|
||||
declarations: [
|
||||
NotificationsSuggestionTargetsPageComponent
|
||||
],
|
||||
providers: [
|
||||
NotificationsSuggestionTargetsPageComponent
|
||||
],
|
||||
schemas: [NO_ERRORS_SCHEMA]
|
||||
})
|
||||
.compileComponents();
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(NotificationsSuggestionTargetsPageComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
});
|
@@ -0,0 +1,10 @@
|
||||
import { Component } from '@angular/core';
|
||||
|
||||
@Component({
|
||||
selector: 'ds-admin-notifications-publication-claim-page',
|
||||
templateUrl: './admin-notifications-publication-claim-page.component.html',
|
||||
styleUrls: ['./admin-notifications-publication-claim-page.component.scss']
|
||||
})
|
||||
export class AdminNotificationsPublicationClaimPageComponent {
|
||||
|
||||
}
|
@@ -1,8 +1,7 @@
|
||||
import { URLCombiner } from '../../core/url-combiner/url-combiner';
|
||||
import { getNotificationsModuleRoute } from '../admin-routing-paths';
|
||||
|
||||
export const QUALITY_ASSURANCE_EDIT_PATH = 'quality-assurance';
|
||||
export const PUBLICATION_CLAIMS_PATH = 'publication-claim';
|
||||
|
||||
export function getQualityAssuranceRoute(id: string) {
|
||||
return new URLCombiner(getNotificationsModuleRoute(), QUALITY_ASSURANCE_EDIT_PATH, id).toString();
|
||||
export function getQualityAssuranceEditRoute() {
|
||||
return `/${QUALITY_ASSURANCE_EDIT_PATH}`;
|
||||
}
|
||||
|
@@ -4,28 +4,46 @@ import { RouterModule } from '@angular/router';
|
||||
import { AuthenticatedGuard } from '../../core/auth/authenticated.guard';
|
||||
import { I18nBreadcrumbResolver } from '../../core/breadcrumbs/i18n-breadcrumb.resolver';
|
||||
import { I18nBreadcrumbsService } from '../../core/breadcrumbs/i18n-breadcrumbs.service';
|
||||
import { PUBLICATION_CLAIMS_PATH, QUALITY_ASSURANCE_EDIT_PATH } from './admin-notifications-routing-paths';
|
||||
import { AdminNotificationsPublicationClaimPageComponent } from './admin-notifications-publication-claim-page/admin-notifications-publication-claim-page.component';
|
||||
import { SiteAdministratorGuard } from '../../core/data/feature-authorization/feature-authorization-guard/site-administrator.guard';
|
||||
import { QualityAssuranceBreadcrumbResolver } from '../../core/breadcrumbs/quality-assurance-breadcrumb.resolver';
|
||||
import { QualityAssuranceBreadcrumbService } from '../../core/breadcrumbs/quality-assurance-breadcrumb.service';
|
||||
import { QUALITY_ASSURANCE_EDIT_PATH } from './admin-notifications-routing-paths';
|
||||
import { AdminQualityAssuranceEventsPageComponent } from './admin-quality-assurance-events-page/admin-quality-assurance-events-page.component';
|
||||
import { AdminQualityAssuranceEventsPageResolver } from './admin-quality-assurance-events-page/admin-quality-assurance-events-page.resolver';
|
||||
import { SourceDataResolver } from './admin-quality-assurance-source-page-component/admin-quality-assurance-source-data.resolver';
|
||||
import { AdminQualityAssuranceSourcePageComponent } from './admin-quality-assurance-source-page-component/admin-quality-assurance-source-page.component';
|
||||
import { AdminQualityAssuranceSourcePageResolver } from './admin-quality-assurance-source-page-component/admin-quality-assurance-source-page-resolver.service';
|
||||
import { AdminQualityAssuranceTopicsPageComponent } from './admin-quality-assurance-topics-page/admin-quality-assurance-topics-page.component';
|
||||
import { AdminQualityAssuranceTopicsPageResolver } from './admin-quality-assurance-topics-page/admin-quality-assurance-topics-page-resolver.service';
|
||||
import { QualityAssuranceEventsPageResolver } from '../../quality-assurance-notifications-pages/quality-assurance-events-page/quality-assurance-events-page.resolver';
|
||||
import { AdminNotificationsPublicationClaimPageResolver } from '../../quality-assurance-notifications-pages/notifications-suggestion-targets-page/notifications-suggestion-targets-page-resolver.service';
|
||||
import { QualityAssuranceTopicsPageComponent } from '../../quality-assurance-notifications-pages/quality-assurance-topics-page/quality-assurance-topics-page.component';
|
||||
import { QualityAssuranceTopicsPageResolver } from '../../quality-assurance-notifications-pages/quality-assurance-topics-page/quality-assurance-topics-page-resolver.service';
|
||||
import { QualityAssuranceSourcePageComponent } from '../../quality-assurance-notifications-pages/quality-assurance-source-page-component/quality-assurance-source-page.component';
|
||||
import { QualityAssuranceSourcePageResolver } from '../../quality-assurance-notifications-pages/quality-assurance-source-page-component/quality-assurance-source-page-resolver.service';
|
||||
import { SourceDataResolver } from '../../quality-assurance-notifications-pages/quality-assurance-source-page-component/quality-assurance-source-data.resolver';
|
||||
import { QualityAssuranceEventsPageComponent } from '../../quality-assurance-notifications-pages/quality-assurance-events-page/quality-assurance-events-page.component';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
RouterModule.forChild([
|
||||
{
|
||||
canActivate: [ AuthenticatedGuard ],
|
||||
path: `${PUBLICATION_CLAIMS_PATH}`,
|
||||
component: AdminNotificationsPublicationClaimPageComponent,
|
||||
pathMatch: 'full',
|
||||
resolve: {
|
||||
breadcrumb: I18nBreadcrumbResolver,
|
||||
suggestionTargetParams: AdminNotificationsPublicationClaimPageResolver
|
||||
},
|
||||
data: {
|
||||
title: 'admin.notifications.publicationclaim.page.title',
|
||||
breadcrumbKey: 'admin.notifications.publicationclaim',
|
||||
showBreadcrumbsFluid: false
|
||||
}
|
||||
},
|
||||
{
|
||||
canActivate: [ AuthenticatedGuard ],
|
||||
path: `${QUALITY_ASSURANCE_EDIT_PATH}/:sourceId`,
|
||||
component: AdminQualityAssuranceTopicsPageComponent,
|
||||
component: QualityAssuranceTopicsPageComponent,
|
||||
pathMatch: 'full',
|
||||
resolve: {
|
||||
breadcrumb: QualityAssuranceBreadcrumbResolver,
|
||||
openaireQualityAssuranceTopicsParams: AdminQualityAssuranceTopicsPageResolver,
|
||||
openaireQualityAssuranceTopicsParams: QualityAssuranceTopicsPageResolver
|
||||
},
|
||||
data: {
|
||||
title: 'admin.quality-assurance.page.title',
|
||||
@@ -35,13 +53,28 @@ import { AdminQualityAssuranceTopicsPageResolver } from './admin-quality-assuran
|
||||
},
|
||||
{
|
||||
canActivate: [ AuthenticatedGuard ],
|
||||
path: `${QUALITY_ASSURANCE_EDIT_PATH}`,
|
||||
component: AdminQualityAssuranceSourcePageComponent,
|
||||
path: `${QUALITY_ASSURANCE_EDIT_PATH}/:sourceId/target/:targetId`,
|
||||
component: QualityAssuranceTopicsPageComponent,
|
||||
pathMatch: 'full',
|
||||
resolve: {
|
||||
breadcrumb: I18nBreadcrumbResolver,
|
||||
openaireQualityAssuranceSourceParams: AdminQualityAssuranceSourcePageResolver,
|
||||
sourceData: SourceDataResolver,
|
||||
openaireQualityAssuranceTopicsParams: QualityAssuranceTopicsPageResolver
|
||||
},
|
||||
data: {
|
||||
title: 'admin.quality-assurance.page.title',
|
||||
breadcrumbKey: 'admin.quality-assurance',
|
||||
showBreadcrumbsFluid: false
|
||||
}
|
||||
},
|
||||
{
|
||||
canActivate: [ SiteAdministratorGuard ],
|
||||
path: `${QUALITY_ASSURANCE_EDIT_PATH}`,
|
||||
component: QualityAssuranceSourcePageComponent,
|
||||
pathMatch: 'full',
|
||||
resolve: {
|
||||
breadcrumb: I18nBreadcrumbResolver,
|
||||
openaireQualityAssuranceSourceParams: QualityAssuranceSourcePageResolver,
|
||||
sourceData: SourceDataResolver
|
||||
},
|
||||
data: {
|
||||
title: 'admin.notifications.source.breadcrumbs',
|
||||
@@ -52,11 +85,11 @@ import { AdminQualityAssuranceTopicsPageResolver } from './admin-quality-assuran
|
||||
{
|
||||
canActivate: [ AuthenticatedGuard ],
|
||||
path: `${QUALITY_ASSURANCE_EDIT_PATH}/:sourceId/:topicId`,
|
||||
component: AdminQualityAssuranceEventsPageComponent,
|
||||
component: QualityAssuranceEventsPageComponent,
|
||||
pathMatch: 'full',
|
||||
resolve: {
|
||||
breadcrumb: QualityAssuranceBreadcrumbResolver,
|
||||
openaireQualityAssuranceEventsParams: AdminQualityAssuranceEventsPageResolver,
|
||||
openaireQualityAssuranceEventsParams: QualityAssuranceEventsPageResolver
|
||||
},
|
||||
data: {
|
||||
title: 'admin.notifications.event.page.title',
|
||||
@@ -69,10 +102,12 @@ import { AdminQualityAssuranceTopicsPageResolver } from './admin-quality-assuran
|
||||
providers: [
|
||||
I18nBreadcrumbResolver,
|
||||
I18nBreadcrumbsService,
|
||||
AdminNotificationsPublicationClaimPageResolver,
|
||||
SourceDataResolver,
|
||||
AdminQualityAssuranceTopicsPageResolver,
|
||||
AdminQualityAssuranceEventsPageResolver,
|
||||
AdminQualityAssuranceSourcePageResolver,
|
||||
QualityAssuranceSourcePageResolver,
|
||||
QualityAssuranceTopicsPageResolver,
|
||||
QualityAssuranceEventsPageResolver,
|
||||
QualityAssuranceSourcePageResolver,
|
||||
QualityAssuranceBreadcrumbResolver,
|
||||
QualityAssuranceBreadcrumbService,
|
||||
],
|
||||
|
@@ -1,13 +1,10 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { NgModule } from '@angular/core';
|
||||
|
||||
import { CoreModule } from '../../core/core.module';
|
||||
import { NotificationsModule } from '../../notifications/notifications.module';
|
||||
import { SharedModule } from '../../shared/shared.module';
|
||||
import { AdminNotificationsRoutingModule } from './admin-notifications-routing.module';
|
||||
import { AdminQualityAssuranceEventsPageComponent } from './admin-quality-assurance-events-page/admin-quality-assurance-events-page.component';
|
||||
import { AdminQualityAssuranceSourcePageComponent } from './admin-quality-assurance-source-page-component/admin-quality-assurance-source-page.component';
|
||||
import { AdminQualityAssuranceTopicsPageComponent } from './admin-quality-assurance-topics-page/admin-quality-assurance-topics-page.component';
|
||||
import { AdminNotificationsPublicationClaimPageComponent } from './admin-notifications-publication-claim-page/admin-notifications-publication-claim-page.component';
|
||||
import { NotificationsModule } from '../../notifications/notifications.module';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
@@ -18,9 +15,7 @@ import { AdminQualityAssuranceTopicsPageComponent } from './admin-quality-assura
|
||||
NotificationsModule,
|
||||
],
|
||||
declarations: [
|
||||
AdminQualityAssuranceTopicsPageComponent,
|
||||
AdminQualityAssuranceEventsPageComponent,
|
||||
AdminQualityAssuranceSourcePageComponent,
|
||||
AdminNotificationsPublicationClaimPageComponent,
|
||||
],
|
||||
entryComponents: [],
|
||||
})
|
||||
|
@@ -1,31 +0,0 @@
|
||||
import { NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
import {
|
||||
async,
|
||||
ComponentFixture,
|
||||
TestBed,
|
||||
} from '@angular/core/testing';
|
||||
|
||||
import { AdminQualityAssuranceEventsPageComponent } from './admin-quality-assurance-events-page.component';
|
||||
|
||||
describe('AdminQualityAssuranceEventsPageComponent', () => {
|
||||
let component: AdminQualityAssuranceEventsPageComponent;
|
||||
let fixture: ComponentFixture<AdminQualityAssuranceEventsPageComponent>;
|
||||
|
||||
beforeEach(async(() => {
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [ AdminQualityAssuranceEventsPageComponent ],
|
||||
schemas: [NO_ERRORS_SCHEMA],
|
||||
})
|
||||
.compileComponents();
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(AdminQualityAssuranceEventsPageComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create AdminQualityAssuranceEventsPageComponent', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
});
|
@@ -1,30 +0,0 @@
|
||||
import { NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
import {
|
||||
ComponentFixture,
|
||||
TestBed,
|
||||
} from '@angular/core/testing';
|
||||
|
||||
import { AdminQualityAssuranceSourcePageComponent } from './admin-quality-assurance-source-page.component';
|
||||
|
||||
describe('AdminQualityAssuranceSourcePageComponent', () => {
|
||||
let component: AdminQualityAssuranceSourcePageComponent;
|
||||
let fixture: ComponentFixture<AdminQualityAssuranceSourcePageComponent>;
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
declarations: [ AdminQualityAssuranceSourcePageComponent ],
|
||||
schemas: [NO_ERRORS_SCHEMA],
|
||||
})
|
||||
.compileComponents();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(AdminQualityAssuranceSourcePageComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create AdminQualityAssuranceSourcePageComponent', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
});
|
@@ -1,10 +0,0 @@
|
||||
import { Component } from '@angular/core';
|
||||
|
||||
/**
|
||||
* Component for the page that show the QA sources.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'ds-admin-quality-assurance-source-page-component',
|
||||
templateUrl: './admin-quality-assurance-source-page.component.html',
|
||||
})
|
||||
export class AdminQualityAssuranceSourcePageComponent {}
|
@@ -1,31 +0,0 @@
|
||||
import { NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
import {
|
||||
async,
|
||||
ComponentFixture,
|
||||
TestBed,
|
||||
} from '@angular/core/testing';
|
||||
|
||||
import { AdminQualityAssuranceTopicsPageComponent } from './admin-quality-assurance-topics-page.component';
|
||||
|
||||
describe('AdminQualityAssuranceTopicsPageComponent', () => {
|
||||
let component: AdminQualityAssuranceTopicsPageComponent;
|
||||
let fixture: ComponentFixture<AdminQualityAssuranceTopicsPageComponent>;
|
||||
|
||||
beforeEach(async(() => {
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [ AdminQualityAssuranceTopicsPageComponent ],
|
||||
schemas: [NO_ERRORS_SCHEMA],
|
||||
})
|
||||
.compileComponents();
|
||||
}));
|
||||
|
||||
beforeEach(() => {
|
||||
fixture = TestBed.createComponent(AdminQualityAssuranceTopicsPageComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create AdminQualityAssuranceTopicsPageComponent', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
});
|
@@ -0,0 +1,58 @@
|
||||
import { NgModule } from '@angular/core';
|
||||
import { RouterModule } from '@angular/router';
|
||||
import { I18nBreadcrumbResolver } from '../../core/breadcrumbs/i18n-breadcrumb.resolver';
|
||||
import { AdminNotifyDashboardComponent } from './admin-notify-dashboard.component';
|
||||
import { SiteAdministratorGuard } from '../../core/data/feature-authorization/feature-authorization-guard/site-administrator.guard';
|
||||
import { AdminNotifyIncomingComponent } from './admin-notify-logs/admin-notify-incoming/admin-notify-incoming.component';
|
||||
import { AdminNotifyOutgoingComponent } from './admin-notify-logs/admin-notify-outgoing/admin-notify-outgoing.component';
|
||||
import { NotifyInfoGuard } from '../../core/coar-notify/notify-info/notify-info.guard';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
RouterModule.forChild([
|
||||
{
|
||||
canActivate: [SiteAdministratorGuard, NotifyInfoGuard],
|
||||
path: '',
|
||||
resolve: {
|
||||
breadcrumb: I18nBreadcrumbResolver,
|
||||
},
|
||||
component: AdminNotifyDashboardComponent,
|
||||
pathMatch: 'full',
|
||||
data: {
|
||||
title: 'admin.notify.dashboard.page.title',
|
||||
breadcrumbKey: 'admin.notify.dashboard',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'inbound',
|
||||
resolve: {
|
||||
breadcrumb: I18nBreadcrumbResolver,
|
||||
},
|
||||
component: AdminNotifyIncomingComponent,
|
||||
canActivate: [SiteAdministratorGuard, NotifyInfoGuard],
|
||||
data: {
|
||||
title: 'admin.notify.dashboard.page.title',
|
||||
breadcrumbKey: 'admin.notify.dashboard',
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'outbound',
|
||||
resolve: {
|
||||
breadcrumb: I18nBreadcrumbResolver,
|
||||
},
|
||||
component: AdminNotifyOutgoingComponent,
|
||||
canActivate: [SiteAdministratorGuard, NotifyInfoGuard],
|
||||
data: {
|
||||
title: 'admin.notify.dashboard.page.title',
|
||||
breadcrumbKey: 'admin.notify.dashboard',
|
||||
},
|
||||
}
|
||||
])
|
||||
],
|
||||
})
|
||||
/**
|
||||
* Routing module for the Notifications section of the admin sidebar
|
||||
*/
|
||||
export class AdminNotifyDashboardRoutingModule {
|
||||
|
||||
}
|
@@ -0,0 +1,23 @@
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<h1 class="border-bottom pb-2">{{'admin-notify-dashboard.title'| translate}}</h1>
|
||||
<div class="my-4">{{'admin-notify-dashboard.description' | translate}}</div>
|
||||
<div>
|
||||
<ul class="nav nav-tabs">
|
||||
<li class="nav-item">
|
||||
<a class="nav-link active">{{'admin-notify-dashboard.metrics' | translate}}</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" [routerLink]="'inbound'" [queryParams]="{view: 'table'}">{{'admin.notify.dashboard.inbound-logs' | translate}}</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" [routerLink]="'outbound'" [queryParams]="{view: 'table'}">{{'admin.notify.dashboard.outbound-logs' | translate}}</a>
|
||||
</ul>
|
||||
<div class="mt-2">
|
||||
<ds-admin-notify-metrics *ngIf="(notifyMetricsRows$ | async)?.length" [boxesConfig]="notifyMetricsRows$ | async"></ds-admin-notify-metrics>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
@@ -0,0 +1,57 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { AdminNotifyDashboardComponent } from './admin-notify-dashboard.component';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { SearchService } from '../../core/shared/search/search.service';
|
||||
import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
|
||||
import { buildPaginatedList } from '../../core/data/paginated-list.model';
|
||||
import { AdminNotifySearchResult } from './models/admin-notify-message-search-result.model';
|
||||
import { AdminNotifyMessage } from './models/admin-notify-message.model';
|
||||
|
||||
describe('AdminNotifyDashboardComponent', () => {
|
||||
let component: AdminNotifyDashboardComponent;
|
||||
let fixture: ComponentFixture<AdminNotifyDashboardComponent>;
|
||||
|
||||
let item1;
|
||||
let item2;
|
||||
let item3;
|
||||
let searchResult1;
|
||||
let searchResult2;
|
||||
let searchResult3;
|
||||
let results;
|
||||
|
||||
const mockBoxes = [
|
||||
{ title: 'admin-notify-dashboard.received-ldn', boxes: [ undefined, undefined, undefined, undefined, undefined ] },
|
||||
{ title: 'admin-notify-dashboard.generated-ldn', boxes: [ undefined, undefined, undefined, undefined, undefined ] }
|
||||
];
|
||||
|
||||
beforeEach(async () => {
|
||||
item1 = Object.assign(new AdminNotifyMessage(), { uuid: 'e1c51c69-896d-42dc-8221-1d5f2ad5516e' });
|
||||
item2 = Object.assign(new AdminNotifyMessage(), { uuid: 'c8279647-1acc-41ae-b036-951d5f65649b' });
|
||||
item3 = Object.assign(new AdminNotifyMessage(), { uuid: 'c3bcbff5-ec0c-4831-8e4c-94b9c933ccac' });
|
||||
searchResult1 = Object.assign(new AdminNotifySearchResult(), { indexableObject: item1 });
|
||||
searchResult2 = Object.assign(new AdminNotifySearchResult(), { indexableObject: item2 });
|
||||
searchResult3 = Object.assign(new AdminNotifySearchResult(), { indexableObject: item3 });
|
||||
results = buildPaginatedList(undefined, [searchResult1, searchResult2, searchResult3]);
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [TranslateModule.forRoot(), NgbNavModule],
|
||||
declarations: [ AdminNotifyDashboardComponent ],
|
||||
providers: [{ provide: SearchService, useValue: { search: () => createSuccessfulRemoteDataObject$(results)}}]
|
||||
})
|
||||
.compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(AdminNotifyDashboardComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', (done) => {
|
||||
component.notifyMetricsRows$.subscribe(boxes => {
|
||||
expect(boxes).toEqual(mockBoxes);
|
||||
done();
|
||||
});
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
});
|
@@ -0,0 +1,94 @@
|
||||
import { Component, OnInit } from '@angular/core';
|
||||
import { SearchService } from '../../core/shared/search/search.service';
|
||||
import { environment } from '../../../environments/environment';
|
||||
import { PaginatedSearchOptions } from '../../shared/search/models/paginated-search-options.model';
|
||||
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
|
||||
import { forkJoin, Observable } from 'rxjs';
|
||||
import { getFirstCompletedRemoteData } from '../../core/shared/operators';
|
||||
import { map } from 'rxjs/operators';
|
||||
import { SearchObjects } from '../../shared/search/models/search-objects.model';
|
||||
import { AdminNotifyMetricsBox, AdminNotifyMetricsRow } from './admin-notify-metrics/admin-notify-metrics.model';
|
||||
import { DSpaceObject } from '../../core/shared/dspace-object.model';
|
||||
import { SEARCH_CONFIG_SERVICE } from '../../my-dspace-page/my-dspace-page.component';
|
||||
import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service';
|
||||
|
||||
@Component({
|
||||
selector: 'ds-admin-notify-dashboard',
|
||||
templateUrl: './admin-notify-dashboard.component.html',
|
||||
providers: [
|
||||
{
|
||||
provide: SEARCH_CONFIG_SERVICE,
|
||||
useClass: SearchConfigurationService
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
/**
|
||||
* Component used for visual representation and search of LDN messages for Admins
|
||||
*/
|
||||
export class AdminNotifyDashboardComponent implements OnInit{
|
||||
|
||||
public notifyMetricsRows$: Observable<AdminNotifyMetricsRow[]>;
|
||||
|
||||
private metricsConfig = environment.notifyMetrics;
|
||||
private singleResultOptions = Object.assign(new PaginationComponentOptions(), {
|
||||
id: 'single-result-options',
|
||||
pageSize: 1
|
||||
});
|
||||
|
||||
constructor(private searchService: SearchService) {
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
const mertricsRowsConfigurations = this.metricsConfig
|
||||
.map(row => row.boxes)
|
||||
.map(boxes => boxes.map(box => box.config).filter(config => !!config));
|
||||
const flatConfigurations = [].concat(...mertricsRowsConfigurations.map((config) => config));
|
||||
const searchConfigurations = flatConfigurations
|
||||
.map(config => Object.assign(new PaginatedSearchOptions({}),
|
||||
{ configuration: config, pagination: this.singleResultOptions }
|
||||
));
|
||||
|
||||
this.notifyMetricsRows$ = forkJoin(searchConfigurations.map(config => this.searchService.search(config)
|
||||
.pipe(
|
||||
getFirstCompletedRemoteData(),
|
||||
map(response => this.mapSearchObjectsToMetricsBox(response.payload)),
|
||||
)
|
||||
)
|
||||
).pipe(
|
||||
map(metricBoxes => this.mapUpdatedBoxesToMetricsRows(metricBoxes))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to map received SearchObjects to notify boxes config
|
||||
*
|
||||
* @param searchObject The object to map
|
||||
* @private
|
||||
*/
|
||||
private mapSearchObjectsToMetricsBox(searchObject: SearchObjects<DSpaceObject>): AdminNotifyMetricsBox {
|
||||
const count = searchObject.pageInfo.totalElements;
|
||||
const objectConfig = searchObject.configuration;
|
||||
const metricsBoxes = [].concat(...this.metricsConfig.map((config) => config.boxes));
|
||||
|
||||
return {
|
||||
...metricsBoxes.find(box => box.config === objectConfig),
|
||||
count
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Function to map updated boxes with count to each row of the configuration
|
||||
*
|
||||
* @param boxesWithCount The object to map
|
||||
* @private
|
||||
*/
|
||||
private mapUpdatedBoxesToMetricsRows(boxesWithCount: AdminNotifyMetricsBox[]): AdminNotifyMetricsRow[] {
|
||||
return this.metricsConfig.map(row => {
|
||||
return {
|
||||
...row,
|
||||
boxes: row.boxes.map(rowBox => boxesWithCount.find(boxWithCount => boxWithCount.config === rowBox.config))
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
@@ -0,0 +1,51 @@
|
||||
import { NgModule } from '@angular/core';
|
||||
import { CommonModule, DatePipe } from '@angular/common';
|
||||
import { RouterModule } from '@angular/router';
|
||||
import { AdminNotifyDashboardComponent } from './admin-notify-dashboard.component';
|
||||
import { AdminNotifyDashboardRoutingModule } from './admin-notify-dashboard-routing.module';
|
||||
import { AdminNotifyMetricsComponent } from './admin-notify-metrics/admin-notify-metrics.component';
|
||||
import { AdminNotifyIncomingComponent } from './admin-notify-logs/admin-notify-incoming/admin-notify-incoming.component';
|
||||
import { SharedModule } from '../../shared/shared.module';
|
||||
import { SearchModule } from '../../shared/search/search.module';
|
||||
import { SearchPageModule } from '../../search-page/search-page.module';
|
||||
import { AdminNotifyOutgoingComponent } from './admin-notify-logs/admin-notify-outgoing/admin-notify-outgoing.component';
|
||||
import { AdminNotifyDetailModalComponent } from './admin-notify-detail-modal/admin-notify-detail-modal.component';
|
||||
import { AdminNotifySearchResultComponent } from './admin-notify-search-result/admin-notify-search-result.component';
|
||||
import { AdminNotifyMessagesService } from './services/admin-notify-messages.service';
|
||||
import { AdminNotifyLogsResultComponent } from './admin-notify-logs/admin-notify-logs-result/admin-notify-logs-result.component';
|
||||
|
||||
const ENTRY_COMPONENTS = [
|
||||
AdminNotifySearchResultComponent
|
||||
];
|
||||
@NgModule({
|
||||
imports: [
|
||||
CommonModule,
|
||||
RouterModule,
|
||||
SharedModule,
|
||||
AdminNotifyDashboardRoutingModule,
|
||||
SearchModule,
|
||||
SearchPageModule
|
||||
],
|
||||
providers: [
|
||||
AdminNotifyMessagesService,
|
||||
DatePipe
|
||||
],
|
||||
declarations: [
|
||||
...ENTRY_COMPONENTS,
|
||||
AdminNotifyDashboardComponent,
|
||||
AdminNotifyMetricsComponent,
|
||||
AdminNotifyIncomingComponent,
|
||||
AdminNotifyOutgoingComponent,
|
||||
AdminNotifyDetailModalComponent,
|
||||
AdminNotifySearchResultComponent,
|
||||
AdminNotifyLogsResultComponent
|
||||
]
|
||||
})
|
||||
export class AdminNotifyDashboardModule {
|
||||
static withEntryComponents() {
|
||||
return {
|
||||
ngModule: AdminNotifyDashboardModule,
|
||||
providers: ENTRY_COMPONENTS.map((component) => ({provide: component}))
|
||||
};
|
||||
}
|
||||
}
|
@@ -0,0 +1,22 @@
|
||||
<div class="modal-header">
|
||||
<h4 class="modal-title">{{'notify-message-modal.title' | translate}}</h4>
|
||||
<button type="button" class="close" aria-label="Close" (click)="activeModal.dismiss('Cross click')">
|
||||
<span aria-hidden="true">×</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="modal-body p-4">
|
||||
<div *ngFor="let key of notifyMessageKeys">
|
||||
<div class="row mb-4">
|
||||
<div class="font-weight-bold col">{{ key + '.notify-detail-modal' | translate}}</div>
|
||||
<div class="col text-right">{{'notify-detail-modal.' + notifyMessage[key] | translate: {default: notifyMessage[key] ?? "n/a" } }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex justify-content-end">
|
||||
<button class="btn-primary" (click)="toggleCoarMessage()">
|
||||
{{'notify-message-modal.show-message' | translate}}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<pre @fadeIn [innerHTML]="notifyMessage.message" class="bg-secondary text-white mt-2 p-2" *ngIf="isCoarMessageVisible"></pre>
|
||||
</div>
|
@@ -0,0 +1,36 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { AdminNotifyDetailModalComponent } from './admin-notify-detail-modal.component';
|
||||
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
|
||||
describe('AdminNotifyDetailModalComponent', () => {
|
||||
let component: AdminNotifyDetailModalComponent;
|
||||
let fixture: ComponentFixture<AdminNotifyDetailModalComponent>;
|
||||
const modalStub = jasmine.createSpyObj('modalStub', ['close']);
|
||||
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [TranslateModule.forRoot()],
|
||||
declarations: [ AdminNotifyDetailModalComponent ],
|
||||
providers: [{ provide: NgbActiveModal, useValue: modalStub }]
|
||||
})
|
||||
.compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(AdminNotifyDetailModalComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should close', () => {
|
||||
spyOn(component.response, 'emit');
|
||||
component.closeModal();
|
||||
expect(modalStub.close).toHaveBeenCalled();
|
||||
expect(component.response.emit).toHaveBeenCalledWith(true);
|
||||
});
|
||||
});
|
@@ -0,0 +1,49 @@
|
||||
import { Component, EventEmitter, Input, Output } from '@angular/core';
|
||||
import { AdminNotifyMessage } from '../models/admin-notify-message.model';
|
||||
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
import { MissingTranslationHelper } from '../../../shared/translate/missing-translation.helper';
|
||||
import { fadeIn } from '../../../shared/animations/fade';
|
||||
|
||||
@Component({
|
||||
selector: 'ds-admin-notify-detail-modal',
|
||||
templateUrl: './admin-notify-detail-modal.component.html',
|
||||
animations: [
|
||||
fadeIn
|
||||
]
|
||||
})
|
||||
/**
|
||||
* Component for detailed view of LDN messages displayed in search result in AdminNotifyDashboardComponent
|
||||
*/
|
||||
|
||||
export class AdminNotifyDetailModalComponent {
|
||||
@Input() notifyMessage: AdminNotifyMessage;
|
||||
@Input() notifyMessageKeys: string[];
|
||||
|
||||
/**
|
||||
* An event fired when the modal is closed
|
||||
*/
|
||||
@Output()
|
||||
response = new EventEmitter<boolean>();
|
||||
|
||||
public isCoarMessageVisible = false;
|
||||
|
||||
|
||||
constructor(protected activeModal: NgbActiveModal,
|
||||
public translationsService: TranslateService) {
|
||||
this.translationsService.missingTranslationHandler = new MissingTranslationHelper();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Close the modal and set the response to true so RootComponent knows the modal was closed
|
||||
*/
|
||||
closeModal() {
|
||||
this.activeModal.close();
|
||||
this.response.emit(true);
|
||||
}
|
||||
|
||||
toggleCoarMessage() {
|
||||
this.isCoarMessageVisible = !this.isCoarMessageVisible;
|
||||
}
|
||||
}
|
@@ -0,0 +1,23 @@
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<h1 class="border-bottom pb-2">{{'admin-notify-dashboard.title'| translate}}</h1>
|
||||
<div>
|
||||
<div>
|
||||
<ul class="nav nav-tabs">
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" [routerLink]="'../'">{{'admin-notify-dashboard.metrics' | translate}}</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link active">{{'admin.notify.dashboard.inbound-logs' | translate}}</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" [routerLink]="'../outbound'" [queryParams]="{view: 'table', configuration: 'NOTIFY.outgoing'}">{{'admin.notify.dashboard.outbound-logs' | translate}}</a>
|
||||
</ul>
|
||||
|
||||
<ds-admin-notify-logs-result [defaultConfiguration]="'NOTIFY.incoming'" ></ds-admin-notify-logs-result>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
@@ -0,0 +1,58 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { AdminNotifyIncomingComponent } from './admin-notify-incoming.component';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
import { MockActivatedRoute } from '../../../../shared/mocks/active-router.mock';
|
||||
import { provideMockStore } from '@ngrx/store/testing';
|
||||
import { HALEndpointService } from '../../../../core/shared/hal-endpoint.service';
|
||||
import { SEARCH_CONFIG_SERVICE } from '../../../../my-dspace-page/my-dspace-page.component';
|
||||
import { RouteService } from '../../../../core/services/route.service';
|
||||
import { routeServiceStub } from '../../../../shared/testing/route-service.stub';
|
||||
import { RequestService } from '../../../../core/data/request.service';
|
||||
import { RemoteDataBuildService } from '../../../../core/cache/builders/remote-data-build.service';
|
||||
import { getMockRemoteDataBuildService } from '../../../../shared/mocks/remote-data-build.service.mock';
|
||||
import { SearchConfigurationService } from '../../../../core/shared/search/search-configuration.service';
|
||||
|
||||
describe('AdminNotifyIncomingComponent', () => {
|
||||
let component: AdminNotifyIncomingComponent;
|
||||
let fixture: ComponentFixture<AdminNotifyIncomingComponent>;
|
||||
let halService: HALEndpointService;
|
||||
let requestService: RequestService;
|
||||
let rdbService: RemoteDataBuildService;
|
||||
|
||||
|
||||
|
||||
beforeEach(async () => {
|
||||
rdbService = getMockRemoteDataBuildService();
|
||||
halService = jasmine.createSpyObj('halService', {
|
||||
'getRootHref': '/api'
|
||||
});
|
||||
requestService = jasmine.createSpyObj('requestService', {
|
||||
'generateRequestId': 'client/1234',
|
||||
'send': '',
|
||||
});
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [TranslateModule.forRoot()],
|
||||
declarations: [ AdminNotifyIncomingComponent ],
|
||||
providers: [
|
||||
{ provide: SEARCH_CONFIG_SERVICE, useValue: SearchConfigurationService },
|
||||
{ provide: RouteService, useValue: routeServiceStub },
|
||||
{ provide: ActivatedRoute, useValue: new MockActivatedRoute() },
|
||||
{ provide: HALEndpointService, useValue: halService },
|
||||
{ provide: RequestService, useValue: requestService },
|
||||
{ provide: RemoteDataBuildService, useValue: rdbService },
|
||||
provideMockStore({}),
|
||||
]
|
||||
})
|
||||
.compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(AdminNotifyIncomingComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
});
|
@@ -0,0 +1,18 @@
|
||||
import { Component, Inject } from '@angular/core';
|
||||
import { SEARCH_CONFIG_SERVICE } from '../../../../my-dspace-page/my-dspace-page.component';
|
||||
import { SearchConfigurationService } from '../../../../core/shared/search/search-configuration.service';
|
||||
|
||||
@Component({
|
||||
selector: 'ds-admin-notify-incoming',
|
||||
templateUrl: './admin-notify-incoming.component.html',
|
||||
providers: [
|
||||
{
|
||||
provide: SEARCH_CONFIG_SERVICE,
|
||||
useClass: SearchConfigurationService
|
||||
}
|
||||
]
|
||||
})
|
||||
export class AdminNotifyIncomingComponent {
|
||||
constructor(@Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService) {
|
||||
}
|
||||
}
|
@@ -0,0 +1,25 @@
|
||||
<div class="container my-4">
|
||||
<div class="row">
|
||||
<div class="col-12 col-md-3 text-left h4">{{((isInbound$ | async) ? 'admin.notify.dashboard.inbound' : 'admin.notify.dashboard.outbound') | translate}}</div>
|
||||
<div class="col-md-9">
|
||||
<div class="h4">
|
||||
<button (click)="resetDefaultConfiguration()" *ngIf="(selectedSearchConfig$ | async) !== defaultConfiguration" class="badge badge-primary mr-1 mb-1">
|
||||
{{ 'admin-notify-logs.' + (selectedSearchConfig$ | async) | translate}}
|
||||
<span> ×</span>
|
||||
</button>
|
||||
</div>
|
||||
<ds-search-labels [inPlaceSearch]="true"></ds-search-labels>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div>
|
||||
<ds-themed-search
|
||||
[configuration]="selectedSearchConfig$ | async"
|
||||
[showViewModes]="false"
|
||||
[searchEnabled]="false"
|
||||
[context]="context"
|
||||
></ds-themed-search>
|
||||
</div>
|
||||
|
@@ -0,0 +1,49 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { AdminNotifyLogsResultComponent } from './admin-notify-logs-result.component';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { MockActivatedRoute } from '../../../../shared/mocks/active-router.mock';
|
||||
import { provideMockStore } from '@ngrx/store/testing';
|
||||
import { HALEndpointService } from '../../../../core/shared/hal-endpoint.service';
|
||||
import { ObjectCacheService } from '../../../../core/cache/object-cache.service';
|
||||
import { RequestService } from '../../../../core/data/request.service';
|
||||
import { RemoteDataBuildService } from '../../../../core/cache/builders/remote-data-build.service';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
import { RouterStub } from '../../../../shared/testing/router.stub';
|
||||
import { RouteService } from '../../../../core/services/route.service';
|
||||
import { routeServiceStub } from '../../../../shared/testing/route-service.stub';
|
||||
|
||||
describe('AdminNotifyLogsResultComponent', () => {
|
||||
let component: AdminNotifyLogsResultComponent;
|
||||
let fixture: ComponentFixture<AdminNotifyLogsResultComponent>;
|
||||
let objectCache: ObjectCacheService;
|
||||
let requestService: RequestService;
|
||||
let halService: HALEndpointService;
|
||||
let rdbService: RemoteDataBuildService;
|
||||
|
||||
beforeEach(async () => {
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [TranslateModule.forRoot()],
|
||||
declarations: [ AdminNotifyLogsResultComponent ],
|
||||
providers: [
|
||||
{ provide: RouteService, useValue: routeServiceStub },
|
||||
{ provide: Router, useValue: new RouterStub() },
|
||||
{ provide: ActivatedRoute, useValue: new MockActivatedRoute() },
|
||||
{ provide: HALEndpointService, useValue: halService },
|
||||
{ provide: ObjectCacheService, useValue: objectCache },
|
||||
{ provide: RequestService, useValue: requestService },
|
||||
{ provide: RemoteDataBuildService, useValue: rdbService },
|
||||
provideMockStore({}),
|
||||
]
|
||||
})
|
||||
.compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(AdminNotifyLogsResultComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
});
|
@@ -0,0 +1,73 @@
|
||||
import { ChangeDetectorRef, Component, Inject, Input, OnInit } from '@angular/core';
|
||||
import { SEARCH_CONFIG_SERVICE } from '../../../../my-dspace-page/my-dspace-page.component';
|
||||
import { Context } from '../../../../core/shared/context.model';
|
||||
import { SearchConfigurationService } from '../../../../core/shared/search/search-configuration.service';
|
||||
import { Observable } from 'rxjs';
|
||||
import { ActivatedRoute, ActivatedRouteSnapshot, Router } from '@angular/router';
|
||||
import { ViewMode } from '../../../../core/shared/view-mode.model';
|
||||
import { map } from 'rxjs/operators';
|
||||
|
||||
@Component({
|
||||
selector: 'ds-admin-notify-logs-result',
|
||||
templateUrl: './admin-notify-logs-result.component.html',
|
||||
providers: [
|
||||
{
|
||||
provide: SEARCH_CONFIG_SERVICE,
|
||||
useClass: SearchConfigurationService
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
/**
|
||||
* Component for visualization of search page and related results for the logs of the Notify dashboard
|
||||
*/
|
||||
|
||||
export class AdminNotifyLogsResultComponent implements OnInit {
|
||||
|
||||
@Input()
|
||||
defaultConfiguration: string;
|
||||
|
||||
|
||||
public selectedSearchConfig$: Observable<string>;
|
||||
public isInbound$: Observable<boolean>;
|
||||
|
||||
protected readonly context = Context.CoarNotify;
|
||||
|
||||
constructor(@Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService,
|
||||
private router: Router,
|
||||
private route: ActivatedRoute,
|
||||
protected cdRef: ChangeDetectorRef) {
|
||||
}
|
||||
|
||||
ngOnInit() {
|
||||
this.selectedSearchConfig$ = this.searchConfigService.getCurrentConfiguration(this.defaultConfiguration);
|
||||
this.isInbound$ = this.selectedSearchConfig$.pipe(
|
||||
map(config => config.startsWith('NOTIFY.incoming'))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset route state to default configuration
|
||||
*/
|
||||
public resetDefaultConfiguration() {
|
||||
//Idle navigation to trigger rendering of result on same page
|
||||
this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
|
||||
this.router.navigate([this.getResolvedUrl(this.route.snapshot)], {
|
||||
queryParams: {
|
||||
configuration: this.defaultConfiguration,
|
||||
view: ViewMode.Table,
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get resolved url from route
|
||||
*
|
||||
* @param route url path
|
||||
* @returns url path
|
||||
*/
|
||||
private getResolvedUrl(route: ActivatedRouteSnapshot): string {
|
||||
return route.pathFromRoot.map(v => v.url.map(segment => segment.toString()).join('/')).join('/');
|
||||
}
|
||||
}
|
@@ -0,0 +1,24 @@
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<h1 class="border-bottom pb-2">{{'admin-notify-dashboard.title'| translate}}</h1>
|
||||
<div>
|
||||
<div>
|
||||
<ul class="nav nav-tabs">
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" [routerLink]="'../'">{{'admin-notify-dashboard.metrics' | translate}}</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" [routerLink]="'../inbound'" [queryParams]="{view: 'table', configuration: 'NOTIFY.incoming'}">{{'admin.notify.dashboard.inbound-logs' | translate}}</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link active">{{'admin.notify.dashboard.outbound-logs' | translate}}</a>
|
||||
</ul>
|
||||
|
||||
<ds-admin-notify-logs-result [defaultConfiguration]="'NOTIFY.outgoing'" ></ds-admin-notify-logs-result>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
@@ -0,0 +1,57 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { AdminNotifyOutgoingComponent } from './admin-notify-outgoing.component';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
import { MockActivatedRoute } from '../../../../shared/mocks/active-router.mock';
|
||||
import { provideMockStore } from '@ngrx/store/testing';
|
||||
import { HALEndpointService } from '../../../../core/shared/hal-endpoint.service';
|
||||
import { SEARCH_CONFIG_SERVICE } from '../../../../my-dspace-page/my-dspace-page.component';
|
||||
import { RouteService } from '../../../../core/services/route.service';
|
||||
import { routeServiceStub } from '../../../../shared/testing/route-service.stub';
|
||||
import { RequestService } from '../../../../core/data/request.service';
|
||||
import { getMockRemoteDataBuildService } from '../../../../shared/mocks/remote-data-build.service.mock';
|
||||
import { RemoteDataBuildService } from '../../../../core/cache/builders/remote-data-build.service';
|
||||
import { SearchConfigurationService } from '../../../../core/shared/search/search-configuration.service';
|
||||
|
||||
describe('AdminNotifyOutgoingComponent', () => {
|
||||
let component: AdminNotifyOutgoingComponent;
|
||||
let fixture: ComponentFixture<AdminNotifyOutgoingComponent>;
|
||||
let halService: HALEndpointService;
|
||||
let requestService: RequestService;
|
||||
let rdbService: RemoteDataBuildService;
|
||||
|
||||
|
||||
beforeEach(async () => {
|
||||
rdbService = getMockRemoteDataBuildService();
|
||||
requestService = jasmine.createSpyObj('requestService', {
|
||||
'generateRequestId': 'client/1234',
|
||||
'send': '',
|
||||
});
|
||||
halService = jasmine.createSpyObj('halService', {
|
||||
'getRootHref': '/api'
|
||||
});
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [TranslateModule.forRoot()],
|
||||
declarations: [ AdminNotifyOutgoingComponent ],
|
||||
providers: [
|
||||
{ provide: SEARCH_CONFIG_SERVICE, useValue: SearchConfigurationService },
|
||||
{ provide: RouteService, useValue: routeServiceStub },
|
||||
{ provide: ActivatedRoute, useValue: new MockActivatedRoute() },
|
||||
{ provide: HALEndpointService, useValue: halService },
|
||||
{ provide: RequestService, useValue: requestService },
|
||||
{ provide: RemoteDataBuildService, useValue: rdbService },
|
||||
provideMockStore({}),
|
||||
]
|
||||
})
|
||||
.compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(AdminNotifyOutgoingComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
});
|
@@ -0,0 +1,18 @@
|
||||
import { Component, Inject } from '@angular/core';
|
||||
import { SEARCH_CONFIG_SERVICE } from '../../../../my-dspace-page/my-dspace-page.component';
|
||||
import { SearchConfigurationService } from '../../../../core/shared/search/search-configuration.service';
|
||||
|
||||
@Component({
|
||||
selector: 'ds-admin-notify-outgoing',
|
||||
templateUrl: './admin-notify-outgoing.component.html',
|
||||
providers: [
|
||||
{
|
||||
provide: SEARCH_CONFIG_SERVICE,
|
||||
useClass: SearchConfigurationService
|
||||
}
|
||||
]
|
||||
})
|
||||
export class AdminNotifyOutgoingComponent {
|
||||
constructor(@Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService) {
|
||||
}
|
||||
}
|
@@ -0,0 +1,9 @@
|
||||
<div class="mb-5" *ngFor="let row of boxesConfig">
|
||||
<div class="mb-2">{{ row.title | translate }}</div>
|
||||
<div class="row justify-content-between">
|
||||
<div class="col-sm" *ngFor="let box of row.boxes">
|
||||
<ds-notification-box (selectedBoxConfig)="navigateToSelectedSearchConfig($event)" [boxConfig]="box"></ds-notification-box>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
@@ -0,0 +1,71 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
|
||||
import { AdminNotifyMetricsComponent } from './admin-notify-metrics.component';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { ViewMode } from '../../../core/shared/view-mode.model';
|
||||
import { RouterStub } from '../../../shared/testing/router.stub';
|
||||
|
||||
describe('AdminNotifyMetricsComponent', () => {
|
||||
let component: AdminNotifyMetricsComponent;
|
||||
let fixture: ComponentFixture<AdminNotifyMetricsComponent>;
|
||||
let router: RouterStub;
|
||||
|
||||
beforeEach(async () => {
|
||||
router = Object.assign(new RouterStub(),
|
||||
{url : '/notify-dashboard'}
|
||||
);
|
||||
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [TranslateModule.forRoot()],
|
||||
declarations: [ AdminNotifyMetricsComponent ],
|
||||
providers: [{provide: Router, useValue: router}]
|
||||
})
|
||||
.compileComponents();
|
||||
|
||||
|
||||
|
||||
fixture = TestBed.createComponent(AdminNotifyMetricsComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
it('should navigate to correct url based on config', () => {
|
||||
const searchConfig = 'test.involvedItems';
|
||||
const incomingConfig = 'NOTIFY.incoming.test';
|
||||
const outgoingConfig = 'NOTIFY.outgoing.test';
|
||||
const adminPath = '/admin/search';
|
||||
const routeExtras = {
|
||||
queryParams: {
|
||||
configuration: searchConfig,
|
||||
view: ViewMode.ListElement
|
||||
},
|
||||
};
|
||||
|
||||
const routeExtrasTable = {
|
||||
queryParams: {
|
||||
configuration: incomingConfig,
|
||||
view: ViewMode.Table
|
||||
},
|
||||
};
|
||||
|
||||
const routeExtrasTableOutgoing = {
|
||||
queryParams: {
|
||||
configuration: outgoingConfig,
|
||||
view: ViewMode.Table
|
||||
},
|
||||
};
|
||||
component.navigateToSelectedSearchConfig(searchConfig);
|
||||
expect(router.navigate).toHaveBeenCalledWith([adminPath], routeExtras);
|
||||
|
||||
component.navigateToSelectedSearchConfig(incomingConfig);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/notify-dashboard/inbound'], routeExtrasTable);
|
||||
|
||||
component.navigateToSelectedSearchConfig(outgoingConfig);
|
||||
expect(router.navigate).toHaveBeenCalledWith(['/notify-dashboard/outbound'], routeExtrasTableOutgoing);
|
||||
});
|
||||
});
|
@@ -0,0 +1,53 @@
|
||||
import { Component, Input } from '@angular/core';
|
||||
import { AdminNotifyMetricsRow } from './admin-notify-metrics.model';
|
||||
import { Router } from '@angular/router';
|
||||
import { ViewMode } from '../../../core/shared/view-mode.model';
|
||||
|
||||
@Component({
|
||||
selector: 'ds-admin-notify-metrics',
|
||||
templateUrl: './admin-notify-metrics.component.html',
|
||||
})
|
||||
/**
|
||||
* Component used to display the number of notification for each configured box in the notifyMetrics section
|
||||
*/
|
||||
|
||||
export class AdminNotifyMetricsComponent {
|
||||
|
||||
@Input()
|
||||
boxesConfig: AdminNotifyMetricsRow[];
|
||||
|
||||
private incomingConfiguration = 'NOTIFY.incoming';
|
||||
private involvedItemsSuffix = 'involvedItems';
|
||||
private inboundPath = '/inbound';
|
||||
private outboundPath = '/outbound';
|
||||
private adminSearchPath = '/admin/search';
|
||||
|
||||
constructor(private router: Router) {
|
||||
}
|
||||
|
||||
|
||||
public navigateToSelectedSearchConfig(searchConfig: string) {
|
||||
const isRelatedItemsConfig = searchConfig.endsWith(this.involvedItemsSuffix);
|
||||
|
||||
if (isRelatedItemsConfig) {
|
||||
this.router.navigate([this.adminSearchPath], {
|
||||
queryParams: {
|
||||
configuration: searchConfig,
|
||||
view: ViewMode.ListElement
|
||||
},
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const isIncomingConfig = searchConfig.startsWith(this.incomingConfiguration);
|
||||
const selectedPath = isIncomingConfig ? this.inboundPath : this.outboundPath;
|
||||
|
||||
this.router.navigate([`${this.router.url}${selectedPath}`], {
|
||||
queryParams: {
|
||||
configuration: searchConfig,
|
||||
view: ViewMode.Table
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
@@ -0,0 +1,19 @@
|
||||
/**
|
||||
* The properties for each Box to be displayed in rows in the AdminNotifyMetricsComponent
|
||||
*/
|
||||
|
||||
export interface AdminNotifyMetricsBox {
|
||||
color: string;
|
||||
textColor?: string;
|
||||
title: string;
|
||||
description: string;
|
||||
config: string;
|
||||
count?: number;
|
||||
}
|
||||
/**
|
||||
* The properties for each Row containing a list of AdminNotifyMetricsBox to be displayed in the AdminNotifyMetricsComponent
|
||||
*/
|
||||
export interface AdminNotifyMetricsRow {
|
||||
title: string;
|
||||
boxes: AdminNotifyMetricsBox[]
|
||||
}
|
@@ -0,0 +1,51 @@
|
||||
<div class="table-responsive mt-2">
|
||||
<table class="table table-striped table-hover">
|
||||
<thead>
|
||||
<tr class="text-nowrap">
|
||||
<th scope="col">{{ 'notify-message-result.timestamp' | translate}}</th>
|
||||
<th scope="col">{{'notify-message-result.repositoryItem' | translate}}</th>
|
||||
<th scope="col">{{ 'notify-message-result.ldnService' | translate}}</th>
|
||||
<th scope="col">{{ 'notify-message-result.type' | translate }}</th>
|
||||
<th scope="col">{{ 'notify-message-result.status' | translate }}</th>
|
||||
<th scope="col">{{ 'notify-message-result.action' | translate }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr *ngFor="let message of (messagesSubject$ | async)">
|
||||
<td class="text-nowrap">
|
||||
<div *ngIf="message.queueLastStartTime">{{ message.queueLastStartTime | date:"YYYY/MM/d hh:mm:ss" }}</div>
|
||||
<div *ngIf="!message.queueLastStartTime">n/a</div>
|
||||
</td>
|
||||
<td>
|
||||
<ds-truncatable [id]="message.id">
|
||||
<ds-truncatable-part [id]="message.id" [minLines]="2">
|
||||
<a *ngIf="message.relatedItem" [routerLink]="'/items/' + (message.context || message.object)">{{ message.relatedItem }}</a>
|
||||
</ds-truncatable-part>
|
||||
</ds-truncatable>
|
||||
<div *ngIf="!message.relatedItem">n/a</div>
|
||||
</td>
|
||||
<td>
|
||||
<div *ngIf="message.ldnService">{{ message.ldnService }}</div>
|
||||
<div *ngIf="!message.ldnService">n/a</div>
|
||||
</td>
|
||||
<td>
|
||||
<div>{{ message.activityStreamType }}</div>
|
||||
</td>
|
||||
<td>
|
||||
<div class="text-nowrap">{{ 'notify-detail-modal.' + message.queueStatusLabel | translate }}</div>
|
||||
</td>
|
||||
<td>
|
||||
<div class="d-flex flex-column">
|
||||
<button class="btn mb-2 btn-dark" (click)="openDetailModal(message)">{{ 'notify-message-result.detail' | translate }}</button>
|
||||
<button *ngIf="message.queueStatusLabel !== reprocessStatus && validStatusesForReprocess.includes(message.queueStatusLabel)"
|
||||
(click)="reprocessMessage(message)"
|
||||
class="btn btn-warning"
|
||||
>
|
||||
{{ 'notify-message-result.reprocess' | translate }}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
@@ -0,0 +1,181 @@
|
||||
import { ComponentFixture, TestBed } from '@angular/core/testing';
|
||||
import { AdminNotifySearchResultComponent } from './admin-notify-search-result.component';
|
||||
import { AdminNotifyMessagesService } from '../services/admin-notify-messages.service';
|
||||
import { ObjectCacheService } from '../../../core/cache/object-cache.service';
|
||||
import { RequestService } from '../../../core/data/request.service';
|
||||
import { HALEndpointService } from '../../../core/shared/hal-endpoint.service';
|
||||
import { RemoteDataBuildService } from '../../../core/cache/builders/remote-data-build.service';
|
||||
import { cold } from 'jasmine-marbles';
|
||||
import { ConfigurationProperty } from '../../../core/shared/configuration-property.model';
|
||||
import { RouteService } from '../../../core/services/route.service';
|
||||
import { routeServiceStub } from '../../../shared/testing/route-service.stub';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
import { RouterStub } from '../../../shared/testing/router.stub';
|
||||
import { TranslateModule } from '@ngx-translate/core';
|
||||
import { of as observableOf, of } from 'rxjs';
|
||||
import { AdminNotifyMessage } from '../models/admin-notify-message.model';
|
||||
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { AdminNotifyDetailModalComponent } from '../admin-notify-detail-modal/admin-notify-detail-modal.component';
|
||||
import { SearchConfigurationService } from '../../../core/shared/search/search-configuration.service';
|
||||
import { SEARCH_CONFIG_SERVICE } from '../../../my-dspace-page/my-dspace-page.component';
|
||||
import { DatePipe } from '@angular/common';
|
||||
import { NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
|
||||
export const mockAdminNotifyMessages = [
|
||||
{
|
||||
'type': 'message',
|
||||
'id': 'urn:uuid:5fb3af44-d4f8-4226-9475-2d09c2d8d9e0',
|
||||
'coarNotifyType': 'coar-notify:ReviewAction',
|
||||
'activityStreamType': 'TentativeReject',
|
||||
'inReplyTo': 'urn:uuid:f7289ad5-0955-4c86-834c-fb54a736778b',
|
||||
'object': null,
|
||||
'context': '24d50450-9ff0-485f-82d4-fba1be42f3f9',
|
||||
'queueAttempts': 1,
|
||||
'queueLastStartTime': '2023-11-24T14:44:00.064+00:00',
|
||||
'origin': 12,
|
||||
'target': null,
|
||||
'queueStatusLabel': 'notify-queue-status.processed',
|
||||
'queueTimeout': '2023-11-24T15:44:00.064+00:00',
|
||||
'queueStatus': 3,
|
||||
'_links': {
|
||||
'self': {
|
||||
'href': 'http://localhost:8080/server/api/ldn/messages/urn:uuid:5fb3af44-d4f8-4226-9475-2d09c2d8d9e0'
|
||||
}
|
||||
},
|
||||
'thumbnail': 'test',
|
||||
'item': {},
|
||||
'accessStatus': {},
|
||||
'ldnService': 'NOTIFY inbox - Automatic service',
|
||||
'relatedItem': 'test coar 2 demo',
|
||||
'message': '{"@context":["https://www.w3.org/ns/activitystreams","https://purl.org/coar/notify"],"id":"urn:uuid:668f26e0-2e8d-4118-b0d2-ee713523bc45","type":["Reject","coar-notify:IngestAction"],"actor":{"id":"https://generic-service.com","type":["Service"],"name":"Generic Service"},"context":{"id":"https://dspace-coar.4science.cloud/handle/123456789/28","type":["Document"],"ietf:cite-as":"https://doi.org/10.4598/12123488"},"object":{"id":"https://dspace-coar.4science.cloud/handle/123456789/28","type":["Offer"]},"origin":{"id":"https://generic-service.com/system","type":["Service"],"inbox":"https://notify-inbox.info/inbox7"},"target":{"id":"https://some-organisation.org","type":["Organization"],"inbox":"https://dspace-coar.4science.cloud/server/ldn/inbox"},"inReplyTo":"urn:uuid:d9b4010a-f128-4815-abb2-83707a2ee9cf"}'
|
||||
},
|
||||
{
|
||||
'type': 'message',
|
||||
'id': 'urn:uuid:544c8777-e826-4810-a625-3e394cc3660d',
|
||||
'coarNotifyType': 'coar-notify:IngestAction',
|
||||
'activityStreamType': 'Announce',
|
||||
'inReplyTo': 'urn:uuid:b2ad72d6-6ea9-464f-b385-29a78417f6b8',
|
||||
'object': null,
|
||||
'context': 'e657437a-0ee2-437d-916a-bba8c57bf40b',
|
||||
'queueAttempts': 1,
|
||||
'queueLastStartTime': null,
|
||||
'origin': 12,
|
||||
'target': null,
|
||||
'queueStatusLabel': 'notify-queue-status.unmapped_action',
|
||||
'queueTimeout': '2023-11-24T14:15:34.945+00:00',
|
||||
'queueStatus': 6,
|
||||
'_links': {
|
||||
'self': {
|
||||
'href': 'http://localhost:8080/server/api/ldn/messages/urn:uuid:544c8777-e826-4810-a625-3e394cc3660d'
|
||||
}
|
||||
},
|
||||
'thumbnail': {},
|
||||
'item': {},
|
||||
'accessStatus': {},
|
||||
'ldnService': 'NOTIFY inbox - Automatic service',
|
||||
'relatedItem': 'test coar demo',
|
||||
'message': '{"@context":["https://www.w3.org/ns/activitystreams","https://purl.org/coar/notify"],"id":"urn:uuid:668f26e0-2e8d-4118-b0d2-ee713523bc45","type":["Reject","coar-notify:IngestAction"],"actor":{"id":"https://generic-service.com","type":["Service"],"name":"Generic Service"},"context":{"id":"https://dspace-coar.4science.cloud/handle/123456789/28","type":["Document"],"ietf:cite-as":"https://doi.org/10.4598/12123488"},"object":{"id":"https://dspace-coar.4science.cloud/handle/123456789/28","type":["Offer"]},"origin":{"id":"https://generic-service.com/system","type":["Service"],"inbox":"https://notify-inbox.info/inbox7"},"target":{"id":"https://some-organisation.org","type":["Organization"],"inbox":"https://dspace-coar.4science.cloud/server/ldn/inbox"},"inReplyTo":"urn:uuid:d9b4010a-f128-4815-abb2-83707a2ee9cf"}'
|
||||
}
|
||||
] as unknown as AdminNotifyMessage[];
|
||||
describe('AdminNotifySearchResultComponent', () => {
|
||||
let component: AdminNotifySearchResultComponent;
|
||||
let fixture: ComponentFixture<AdminNotifySearchResultComponent>;
|
||||
let objectCache: ObjectCacheService;
|
||||
let requestService: RequestService;
|
||||
let halService: HALEndpointService;
|
||||
let rdbService: RemoteDataBuildService;
|
||||
let adminNotifyMessageService: AdminNotifyMessagesService;
|
||||
let searchConfigService: SearchConfigurationService;
|
||||
let modalService: NgbModal;
|
||||
const requestUUID = '34cfed7c-f597-49ef-9cbe-ea351f0023c2';
|
||||
const testObject = {
|
||||
uuid: 'test-property',
|
||||
name: 'test-property',
|
||||
values: ['value-1', 'value-2']
|
||||
} as ConfigurationProperty;
|
||||
|
||||
beforeEach(async () => {
|
||||
halService = jasmine.createSpyObj('halService', {
|
||||
getEndpoint: cold('a', { a: '' })
|
||||
});
|
||||
adminNotifyMessageService = jasmine.createSpyObj('adminNotifyMessageService', {
|
||||
getDetailedMessages: of(mockAdminNotifyMessages),
|
||||
reprocessMessage: of(mockAdminNotifyMessages),
|
||||
});
|
||||
requestService = jasmine.createSpyObj('requestService', {
|
||||
generateRequestId: requestUUID,
|
||||
send: true
|
||||
});
|
||||
rdbService = jasmine.createSpyObj('rdbService', {
|
||||
buildSingle: cold('a', {
|
||||
a: {
|
||||
payload: testObject
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
searchConfigService = jasmine.createSpyObj('searchConfigService', {
|
||||
getCurrentConfiguration: of('NOTIFY.outgoing')
|
||||
});
|
||||
objectCache = {} as ObjectCacheService;
|
||||
|
||||
|
||||
await TestBed.configureTestingModule({
|
||||
imports: [TranslateModule.forRoot()],
|
||||
declarations: [ AdminNotifySearchResultComponent, AdminNotifyDetailModalComponent ],
|
||||
providers: [
|
||||
{ provide: AdminNotifyMessagesService, useValue: adminNotifyMessageService },
|
||||
{ provide: RouteService, useValue: routeServiceStub },
|
||||
{ provide: ActivatedRoute, useValue: new RouterStub() },
|
||||
{ provide: HALEndpointService, useValue: halService },
|
||||
{ provide: ObjectCacheService, useValue: objectCache },
|
||||
{ provide: RequestService, useValue: requestService },
|
||||
{ provide: RemoteDataBuildService, useValue: rdbService },
|
||||
{ provide: SEARCH_CONFIG_SERVICE, useValue: searchConfigService },
|
||||
DatePipe
|
||||
],
|
||||
schemas: [NO_ERRORS_SCHEMA]
|
||||
})
|
||||
.compileComponents();
|
||||
|
||||
fixture = TestBed.createComponent(AdminNotifySearchResultComponent);
|
||||
component = fixture.componentInstance;
|
||||
component.searchConfigService = searchConfigService;
|
||||
modalService = (component as any).modalService;
|
||||
spyOn(modalService, 'open').and.returnValue(Object.assign({ componentInstance: Object.assign({ response: observableOf(true) }) }));
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should create', () => {
|
||||
expect(component).toBeTruthy();
|
||||
expect(component.isInbound).toBeFalsy();
|
||||
});
|
||||
|
||||
it('should open modal', () => {
|
||||
component.openDetailModal(mockAdminNotifyMessages[0]);
|
||||
expect(modalService.open).toHaveBeenCalledWith(AdminNotifyDetailModalComponent);
|
||||
});
|
||||
|
||||
it('should map messages', (done) => {
|
||||
component.messagesSubject$.subscribe((messages) => {
|
||||
expect(messages).toEqual(mockAdminNotifyMessages);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should reprocess message', (done) => {
|
||||
component.reprocessMessage(mockAdminNotifyMessages[0]);
|
||||
component.messagesSubject$.subscribe((messages) => {
|
||||
expect(messages).toEqual(mockAdminNotifyMessages);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should unsubscribe on destroy', () => {
|
||||
(component as any).subs = [of(null).subscribe()];
|
||||
|
||||
spyOn((component as any).subs[0], 'unsubscribe');
|
||||
component.ngOnDestroy();
|
||||
expect((component as any).subs[0].unsubscribe).toHaveBeenCalled();
|
||||
});
|
||||
});
|
@@ -0,0 +1,153 @@
|
||||
import { Component, Inject, OnDestroy, OnInit } from '@angular/core';
|
||||
import { AdminNotifySearchResult } from '../models/admin-notify-message-search-result.model';
|
||||
import { ViewMode } from '../../../core/shared/view-mode.model';
|
||||
import { Context } from '../../../core/shared/context.model';
|
||||
import { AdminNotifyMessage } from '../models/admin-notify-message.model';
|
||||
import { tabulatableObjectsComponent } from '../../../shared/object-collection/shared/tabulatable-objects/tabulatable-objects.decorator';
|
||||
import { TabulatableResultListElementsComponent } from '../../../shared/object-list/search-result-list-element/tabulatable-search-result/tabulatable-result-list-elements.component';
|
||||
import { PaginatedList } from '../../../core/data/paginated-list.model';
|
||||
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { AdminNotifyDetailModalComponent } from '../admin-notify-detail-modal/admin-notify-detail-modal.component';
|
||||
import { BehaviorSubject, Subscription } from 'rxjs';
|
||||
import { AdminNotifyMessagesService } from '../services/admin-notify-messages.service';
|
||||
import { SearchConfigurationService } from '../../../core/shared/search/search-configuration.service';
|
||||
import { SEARCH_CONFIG_SERVICE } from '../../../my-dspace-page/my-dspace-page.component';
|
||||
import { DatePipe } from '@angular/common';
|
||||
|
||||
@tabulatableObjectsComponent(PaginatedList<AdminNotifySearchResult>, ViewMode.Table, Context.CoarNotify)
|
||||
@Component({
|
||||
selector: 'ds-admin-notify-search-result',
|
||||
templateUrl: './admin-notify-search-result.component.html',
|
||||
providers: [
|
||||
{
|
||||
provide: SEARCH_CONFIG_SERVICE,
|
||||
useClass: SearchConfigurationService
|
||||
}
|
||||
]
|
||||
})
|
||||
/**
|
||||
* Component for visualization in table format of the search results related to the AdminNotifyDashboardComponent
|
||||
*/
|
||||
|
||||
|
||||
export class AdminNotifySearchResultComponent extends TabulatableResultListElementsComponent<PaginatedList<AdminNotifySearchResult>, AdminNotifySearchResult> implements OnInit, OnDestroy{
|
||||
public messagesSubject$: BehaviorSubject<AdminNotifyMessage[]> = new BehaviorSubject([]);
|
||||
public reprocessStatus = 'QUEUE_STATUS_QUEUED_FOR_RETRY';
|
||||
//we check on one type of config to render specific table headers
|
||||
public isInbound: boolean;
|
||||
|
||||
/**
|
||||
* Statuses for which we display the reprocess button
|
||||
*/
|
||||
public validStatusesForReprocess = [
|
||||
'QUEUE_STATUS_UNTRUSTED',
|
||||
'QUEUE_STATUS_UNTRUSTED_IP',
|
||||
'QUEUE_STATUS_FAILED',
|
||||
'QUEUE_STATUS_UNMAPPED_ACTION'
|
||||
];
|
||||
|
||||
|
||||
/**
|
||||
* Array to track all subscriptions and unsubscribe them onDestroy
|
||||
* @type {Array}
|
||||
*/
|
||||
private subs: Subscription[] = [];
|
||||
|
||||
/**
|
||||
* Keys to be formatted as date
|
||||
* @private
|
||||
*/
|
||||
|
||||
private dateTypeKeys: string[] = ['queueLastStartTime', 'queueTimeout'];
|
||||
|
||||
/**
|
||||
* Keys to be not shown in detail
|
||||
* @private
|
||||
*/
|
||||
private messageKeys: string[] = [
|
||||
'type',
|
||||
'id',
|
||||
'coarNotifyType',
|
||||
'activityStreamType',
|
||||
'inReplyTo',
|
||||
'queueAttempts',
|
||||
'queueLastStartTime',
|
||||
'queueStatusLabel',
|
||||
'queueTimeout'
|
||||
];
|
||||
|
||||
/**
|
||||
* The format for the date values
|
||||
* @private
|
||||
*/
|
||||
private dateFormat = 'YYYY/MM/d hh:mm:ss';
|
||||
|
||||
constructor(private modalService: NgbModal,
|
||||
private adminNotifyMessagesService: AdminNotifyMessagesService,
|
||||
private datePipe: DatePipe,
|
||||
@Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService) {
|
||||
super();
|
||||
}
|
||||
|
||||
/**
|
||||
* Map messages on init for readable representation
|
||||
*/
|
||||
ngOnInit() {
|
||||
this.mapDetailsToMessages();
|
||||
this.subs.push(this.searchConfigService.getCurrentConfiguration('')
|
||||
.subscribe(configuration => {
|
||||
this.isInbound = configuration.startsWith('NOTIFY.incoming');
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
ngOnDestroy() {
|
||||
this.subs.forEach(sub => sub.unsubscribe());
|
||||
}
|
||||
|
||||
/**
|
||||
* Open modal for details visualization
|
||||
* @param notifyMessage the message to be displayed
|
||||
*/
|
||||
openDetailModal(notifyMessage: AdminNotifyMessage) {
|
||||
const modalRef = this.modalService.open(AdminNotifyDetailModalComponent);
|
||||
const messageToOpen = {...notifyMessage};
|
||||
|
||||
this.messageKeys.forEach(key => {
|
||||
if (this.dateTypeKeys.includes(key)) {
|
||||
messageToOpen[key] = this.datePipe.transform(messageToOpen[key], this.dateFormat);
|
||||
}
|
||||
});
|
||||
// format COAR message for technical visualization
|
||||
messageToOpen.message = JSON.stringify(JSON.parse(notifyMessage.message), null, 2);
|
||||
|
||||
modalRef.componentInstance.notifyMessage = messageToOpen;
|
||||
modalRef.componentInstance.notifyMessageKeys = this.messageKeys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reprocess message in status QUEUE_STATUS_QUEUED_FOR_RETRY and update results
|
||||
* @param message the message to be reprocessed
|
||||
*/
|
||||
reprocessMessage(message: AdminNotifyMessage) {
|
||||
this.subs.push(
|
||||
this.adminNotifyMessagesService.reprocessMessage(message, this.messagesSubject$)
|
||||
.subscribe(response => {
|
||||
this.messagesSubject$.next(response);
|
||||
}
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Map readable results to messages
|
||||
* @private
|
||||
*/
|
||||
private mapDetailsToMessages() {
|
||||
this.subs.push(this.adminNotifyMessagesService.getDetailedMessages(this.objects?.page.map(pageResult => pageResult.indexableObject))
|
||||
.subscribe(response => {
|
||||
this.messagesSubject$.next(response);
|
||||
}));
|
||||
}
|
||||
}
|
@@ -0,0 +1,7 @@
|
||||
import { AdminNotifyMessage } from './admin-notify-message.model';
|
||||
import { searchResultFor } from '../../../shared/search/search-result-element-decorator';
|
||||
import { SearchResult } from '../../../shared/search/models/search-result.model';
|
||||
|
||||
@searchResultFor(AdminNotifyMessage)
|
||||
export class AdminNotifySearchResult extends SearchResult<AdminNotifyMessage> {
|
||||
}
|
@@ -0,0 +1,166 @@
|
||||
import { autoserialize, deserialize, inheritSerialization } from 'cerialize';
|
||||
import { typedObject } from '../../../core/cache/builders/build-decorators';
|
||||
import { ADMIN_NOTIFY_MESSAGE } from './admin-notify-message.resource-type';
|
||||
import { excludeFromEquals } from '../../../core/utilities/equals.decorators';
|
||||
import { DSpaceObject } from '../../../core/shared/dspace-object.model';
|
||||
import { GenericConstructor } from '../../../core/shared/generic-constructor';
|
||||
import { ListableObject } from '../../../shared/object-collection/shared/listable-object.model';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
/**
|
||||
* A message that includes admin notify info
|
||||
*/
|
||||
@typedObject
|
||||
@inheritSerialization(DSpaceObject)
|
||||
export class AdminNotifyMessage extends DSpaceObject {
|
||||
static type = ADMIN_NOTIFY_MESSAGE;
|
||||
|
||||
/**
|
||||
* The type of the resource
|
||||
*/
|
||||
@excludeFromEquals
|
||||
type = ADMIN_NOTIFY_MESSAGE;
|
||||
|
||||
/**
|
||||
* The id of the message
|
||||
*/
|
||||
@autoserialize
|
||||
id: string;
|
||||
|
||||
/**
|
||||
* The id of the notification
|
||||
*/
|
||||
@autoserialize
|
||||
notificationId: string;
|
||||
|
||||
/**
|
||||
* The type of the notification
|
||||
*/
|
||||
@autoserialize
|
||||
notificationType: string;
|
||||
|
||||
/**
|
||||
* The type of the notification
|
||||
*/
|
||||
@autoserialize
|
||||
coarNotifyType: string;
|
||||
|
||||
/**
|
||||
* The type of the activity
|
||||
*/
|
||||
@autoserialize
|
||||
activityStreamType: string;
|
||||
|
||||
/**
|
||||
* The object the message reply to
|
||||
*/
|
||||
@autoserialize
|
||||
inReplyTo: string;
|
||||
|
||||
/**
|
||||
* The object the message relates to
|
||||
*/
|
||||
@autoserialize
|
||||
object: string;
|
||||
|
||||
/**
|
||||
* The name of the related item
|
||||
*/
|
||||
@autoserialize
|
||||
relatedItem: string;
|
||||
|
||||
/**
|
||||
* The name of the related ldn service
|
||||
*/
|
||||
@autoserialize
|
||||
ldnService: string;
|
||||
|
||||
/**
|
||||
* The context of the message
|
||||
*/
|
||||
@autoserialize
|
||||
context: string;
|
||||
|
||||
/**
|
||||
* The related COAR message
|
||||
*/
|
||||
@autoserialize
|
||||
message: string;
|
||||
|
||||
/**
|
||||
* The attempts of the queue
|
||||
*/
|
||||
@autoserialize
|
||||
queueAttempts: number;
|
||||
|
||||
/**
|
||||
* Timestamp of the last queue attempt
|
||||
*/
|
||||
@autoserialize
|
||||
queueLastStartTime: string;
|
||||
|
||||
/**
|
||||
* The type of the activity stream
|
||||
*/
|
||||
@autoserialize
|
||||
origin: number | string;
|
||||
|
||||
/**
|
||||
* The type of the activity stream
|
||||
*/
|
||||
@autoserialize
|
||||
target: number | string;
|
||||
|
||||
/**
|
||||
* The label for the status of the queue
|
||||
*/
|
||||
@autoserialize
|
||||
queueStatusLabel: string;
|
||||
|
||||
/**
|
||||
* The timeout of the queue
|
||||
*/
|
||||
@autoserialize
|
||||
queueTimeout: string;
|
||||
|
||||
/**
|
||||
* The status of the queue
|
||||
*/
|
||||
@autoserialize
|
||||
queueStatus: number;
|
||||
|
||||
/**
|
||||
* Thumbnail link used when browsing items with showThumbs config enabled.
|
||||
*/
|
||||
@autoserialize
|
||||
thumbnail: string;
|
||||
|
||||
/**
|
||||
* The observable pointing to the item itself
|
||||
*/
|
||||
@autoserialize
|
||||
item: Observable<AdminNotifyMessage>;
|
||||
|
||||
/**
|
||||
* The observable pointing to the access status of the item
|
||||
*/
|
||||
@autoserialize
|
||||
accessStatus: Observable<AdminNotifyMessage>;
|
||||
|
||||
|
||||
|
||||
@deserialize
|
||||
_links: {
|
||||
self: {
|
||||
href: string;
|
||||
};
|
||||
};
|
||||
|
||||
get self(): string {
|
||||
return this._links.self.href;
|
||||
}
|
||||
|
||||
getRenderTypes(): (string | GenericConstructor<ListableObject>)[] {
|
||||
return [this.constructor as GenericConstructor<ListableObject>];
|
||||
}
|
||||
}
|
@@ -0,0 +1,9 @@
|
||||
import { ResourceType } from '../../../core/shared/resource-type';
|
||||
|
||||
/**
|
||||
* The resource type for AdminNotifyMessage
|
||||
*
|
||||
* Needs to be in a separate file to prevent circular
|
||||
* dependencies in webpack.
|
||||
*/
|
||||
export const ADMIN_NOTIFY_MESSAGE = new ResourceType('message');
|
@@ -0,0 +1,113 @@
|
||||
import { cold } from 'jasmine-marbles';
|
||||
import { AdminNotifyMessagesService } from './admin-notify-messages.service';
|
||||
import { RequestService } from '../../../core/data/request.service';
|
||||
import { RemoteDataBuildService } from '../../../core/cache/builders/remote-data-build.service';
|
||||
import { ObjectCacheService } from '../../../core/cache/object-cache.service';
|
||||
import { HALEndpointService } from '../../../core/shared/hal-endpoint.service';
|
||||
import { NotificationsService } from '../../../shared/notifications/notifications.service';
|
||||
import { LdnServicesService } from '../../admin-ldn-services/ldn-services-data/ldn-services-data.service';
|
||||
import { ItemDataService } from '../../../core/data/item-data.service';
|
||||
import { RequestEntry } from '../../../core/data/request-entry.model';
|
||||
import { RestResponse } from '../../../core/cache/response.models';
|
||||
import { BehaviorSubject, of } from 'rxjs';
|
||||
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
|
||||
import { RemoteData } from '../../../core/data/remote-data';
|
||||
import { RequestEntryState } from '../../../core/data/request-entry-state.model';
|
||||
import { mockAdminNotifyMessages } from '../admin-notify-search-result/admin-notify-search-result.component.spec';
|
||||
import { take } from 'rxjs/operators';
|
||||
import { deepClone } from 'fast-json-patch';
|
||||
import { AdminNotifyMessage } from '../models/admin-notify-message.model';
|
||||
|
||||
describe('AdminNotifyMessagesService test', () => {
|
||||
let service: AdminNotifyMessagesService;
|
||||
let requestService: RequestService;
|
||||
let rdbService: RemoteDataBuildService;
|
||||
let objectCache: ObjectCacheService;
|
||||
let halService: HALEndpointService;
|
||||
let notificationsService: NotificationsService;
|
||||
let ldnServicesService: LdnServicesService;
|
||||
let itemDataService: ItemDataService;
|
||||
let responseCacheEntry: RequestEntry;
|
||||
let mockMessages: AdminNotifyMessage[];
|
||||
|
||||
const endpointURL = `https://rest.api/rest/api/ldn/messages`;
|
||||
const requestUUID = '8b3c613a-5a4b-438b-9686-be1d5b4a1c5a';
|
||||
const remoteDataMocks = {
|
||||
Success: new RemoteData(null, null, null, RequestEntryState.Success, null, null, 200),
|
||||
};
|
||||
const testLdnServiceName = 'testLdnService';
|
||||
const testRelatedItemName = 'testRelatedItem';
|
||||
|
||||
function initTestService() {
|
||||
return new AdminNotifyMessagesService(
|
||||
requestService,
|
||||
rdbService,
|
||||
objectCache,
|
||||
halService,
|
||||
notificationsService,
|
||||
ldnServicesService,
|
||||
itemDataService
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mockMessages = deepClone(mockAdminNotifyMessages);
|
||||
objectCache = {} as ObjectCacheService;
|
||||
notificationsService = {} as NotificationsService;
|
||||
responseCacheEntry = new RequestEntry();
|
||||
responseCacheEntry.request = { href: endpointURL } as any;
|
||||
responseCacheEntry.response = new RestResponse(true, 200, 'Success');
|
||||
|
||||
|
||||
requestService = jasmine.createSpyObj('requestService', {
|
||||
generateRequestId: requestUUID,
|
||||
send: true,
|
||||
removeByHrefSubstring: {},
|
||||
getByHref: of(responseCacheEntry),
|
||||
getByUUID: of(responseCacheEntry),
|
||||
});
|
||||
|
||||
halService = jasmine.createSpyObj('halService', {
|
||||
getEndpoint: of(endpointURL)
|
||||
});
|
||||
|
||||
rdbService = jasmine.createSpyObj('rdbService', {
|
||||
buildSingle: createSuccessfulRemoteDataObject$({}, 500),
|
||||
buildList: cold('a', { a: remoteDataMocks.Success }),
|
||||
buildFromRequestUUID: createSuccessfulRemoteDataObject$(mockMessages)
|
||||
});
|
||||
|
||||
ldnServicesService = jasmine.createSpyObj('ldnServicesService', {
|
||||
findById: createSuccessfulRemoteDataObject$({name: testLdnServiceName}),
|
||||
});
|
||||
|
||||
itemDataService = jasmine.createSpyObj('itemDataService', {
|
||||
findById: createSuccessfulRemoteDataObject$({name: testRelatedItemName}),
|
||||
});
|
||||
|
||||
service = initTestService();
|
||||
});
|
||||
|
||||
describe('Admin Notify service', () => {
|
||||
it('should be defined', () => {
|
||||
expect(service).toBeDefined();
|
||||
});
|
||||
|
||||
it('should get details for messages', (done) => {
|
||||
service.getDetailedMessages(mockMessages).pipe(take(1)).subscribe((detailedMessages) => {
|
||||
expect(detailedMessages[0].ldnService).toEqual(testLdnServiceName);
|
||||
expect(detailedMessages[0].relatedItem).toEqual(testRelatedItemName);
|
||||
done();
|
||||
});
|
||||
});
|
||||
|
||||
it('should reprocess message', (done) => {
|
||||
const behaviorSubject = new BehaviorSubject(mockMessages);
|
||||
service.reprocessMessage(mockMessages[0], behaviorSubject).pipe(take(1)).subscribe((reprocessedMessages) => {
|
||||
expect(reprocessedMessages.length).toEqual(2);
|
||||
expect(reprocessedMessages).toEqual(mockMessages);
|
||||
done();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
@@ -0,0 +1,100 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { dataService } from '../../../core/data/base/data-service.decorator';
|
||||
import { IdentifiableDataService } from '../../../core/data/base/identifiable-data.service';
|
||||
import { RequestService } from '../../../core/data/request.service';
|
||||
import { RemoteDataBuildService } from '../../../core/cache/builders/remote-data-build.service';
|
||||
import { ObjectCacheService } from '../../../core/cache/object-cache.service';
|
||||
import { HALEndpointService } from '../../../core/shared/hal-endpoint.service';
|
||||
import { NotificationsService } from '../../../shared/notifications/notifications.service';
|
||||
import { BehaviorSubject, from, Observable, of, scan } from 'rxjs';
|
||||
import { ADMIN_NOTIFY_MESSAGE } from '../models/admin-notify-message.resource-type';
|
||||
import { AdminNotifyMessage } from '../models/admin-notify-message.model';
|
||||
import { map, mergeMap, switchMap, tap } from 'rxjs/operators';
|
||||
import { getAllSucceededRemoteDataPayload, getFirstCompletedRemoteData } from '../../../core/shared/operators';
|
||||
import { LdnServicesService } from '../../admin-ldn-services/ldn-services-data/ldn-services-data.service';
|
||||
import { ItemDataService } from '../../../core/data/item-data.service';
|
||||
import { PostRequest } from '../../../core/data/request.models';
|
||||
import { RestRequest } from '../../../core/data/rest-request.model';
|
||||
|
||||
/**
|
||||
* Injectable service responsible for fetching/sending data from/to the REST API on the messages endpoint.
|
||||
*
|
||||
* @export
|
||||
* @class AdminNotifyMessagesService
|
||||
* @extends {IdentifiableDataService<AdminNotifyMessage>}
|
||||
*/
|
||||
@Injectable()
|
||||
@dataService(ADMIN_NOTIFY_MESSAGE)
|
||||
export class AdminNotifyMessagesService extends IdentifiableDataService<AdminNotifyMessage> {
|
||||
|
||||
protected reprocessEndpoint = 'enqueueretry';
|
||||
|
||||
constructor(
|
||||
protected requestService: RequestService,
|
||||
protected rdbService: RemoteDataBuildService,
|
||||
protected objectCache: ObjectCacheService,
|
||||
protected halService: HALEndpointService,
|
||||
protected notificationsService: NotificationsService,
|
||||
private ldnServicesService: LdnServicesService,
|
||||
private itemDataService: ItemDataService,
|
||||
) {
|
||||
super('messages', requestService, rdbService, objectCache, halService);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Add detailed information to each message
|
||||
* @param messages the messages to which add detailded info
|
||||
*/
|
||||
public getDetailedMessages(messages: AdminNotifyMessage[]): Observable<AdminNotifyMessage[]> {
|
||||
return from(messages).pipe(
|
||||
mergeMap(message =>
|
||||
message.target || message.origin ? this.ldnServicesService.findById((message.target || message.origin).toString()).pipe(
|
||||
getAllSucceededRemoteDataPayload(),
|
||||
map(detail => ({...message, ldnService: detail.name}))
|
||||
) : of(message),
|
||||
),
|
||||
mergeMap(message =>
|
||||
message.object || message.context ? this.itemDataService.findById(message.object || message.context).pipe(
|
||||
getAllSucceededRemoteDataPayload(),
|
||||
map(detail => ({...message, relatedItem: detail.name}))
|
||||
) : of(message),
|
||||
),
|
||||
scan((acc: any, value: any) => [...acc, value], []),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reprocess message in status QUEUE_STATUS_QUEUED_FOR_RETRY and update results
|
||||
* @param message the message to reprocess
|
||||
* @param messageSubject the current visualised messages source
|
||||
*/
|
||||
public reprocessMessage(message: AdminNotifyMessage, messageSubject: BehaviorSubject<AdminNotifyMessage[]>): Observable<AdminNotifyMessage[]> {
|
||||
const requestId = this.requestService.generateRequestId();
|
||||
|
||||
return this.halService.getEndpoint(this.reprocessEndpoint).pipe(
|
||||
map(endpoint => endpoint.replace('{id}', message.id)),
|
||||
map((endpointURL: string) => new PostRequest(requestId, endpointURL)),
|
||||
tap(request => this.requestService.send(request)),
|
||||
switchMap((request: RestRequest) => this.rdbService.buildFromRequestUUID<AdminNotifyMessage>(request.uuid)),
|
||||
getFirstCompletedRemoteData(),
|
||||
getAllSucceededRemoteDataPayload(),
|
||||
mergeMap(reprocessedMessage => this.getDetailedMessages([reprocessedMessage])),
|
||||
).pipe(
|
||||
mergeMap((newMessages) => messageSubject.pipe(
|
||||
map(messages => {
|
||||
const detailedReprocessedMessage = newMessages[0];
|
||||
const messageToUpdate = messages.find(currentMessage => currentMessage.id === message.id);
|
||||
const indexOfMessageToUpdate = messages.indexOf(messageToUpdate);
|
||||
detailedReprocessedMessage.target = message.target;
|
||||
detailedReprocessedMessage.object = message.object;
|
||||
detailedReprocessedMessage.origin = message.origin;
|
||||
detailedReprocessedMessage.context = message.context;
|
||||
messages[indexOfMessageToUpdate] = detailedReprocessedMessage;
|
||||
|
||||
return messages;
|
||||
})
|
||||
)),
|
||||
);
|
||||
}
|
||||
}
|
@@ -19,7 +19,7 @@
|
||||
<table id="formats" class="table table-striped table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col" [attr.aria-label]="'admin.registries.bitstream-formats.select' | translate"></th>
|
||||
<th scope="col"><span class="sr-only">{{'admin.registries.bitstream-formats.table.selected' | translate}}</span></th>
|
||||
<th scope="col">{{'admin.registries.bitstream-formats.table.id' | translate}}</th>
|
||||
<th scope="col">{{'admin.registries.bitstream-formats.table.name' | translate}}</th>
|
||||
<th scope="col">{{'admin.registries.bitstream-formats.table.mimetype' | translate}}</th>
|
||||
@@ -35,6 +35,7 @@
|
||||
[checked]="isSelected(bitstreamFormat) | async"
|
||||
(change)="selectBitStreamFormat(bitstreamFormat, $event)"
|
||||
>
|
||||
<span class="sr-only">{{'admin.registries.bitstream-formats.select' | translate}}}</span>
|
||||
</label>
|
||||
</td>
|
||||
<td><a [routerLink]="['/admin/registries/bitstream-formats', bitstreamFormat.id, 'edit']">{{bitstreamFormat.id}}</a></td>
|
||||
|
@@ -2,7 +2,7 @@
|
||||
<div class="metadata-registry row">
|
||||
<div class="col-12">
|
||||
|
||||
<h2 id="header" class="border-bottom pb-2">{{'admin.registries.metadata.head' | translate}}</h2>
|
||||
<h1 id="header" class="border-bottom pb-2">{{'admin.registries.metadata.head' | translate}}</h1>
|
||||
|
||||
<p id="description" class="pb-2">{{'admin.registries.metadata.description' | translate}}</p>
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
<table id="metadata-schemas" class="table table-striped table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col"></th>
|
||||
<th scope="col"><span class="sr-only">{{'admin.registries.metadata.schemas.table.selected' | translate}}</span></th>
|
||||
<th scope="col">{{'admin.registries.metadata.schemas.table.id' | translate}}</th>
|
||||
<th scope="col">{{'admin.registries.metadata.schemas.table.namespace' | translate}}</th>
|
||||
<th scope="col">{{'admin.registries.metadata.schemas.table.name' | translate}}</th>
|
||||
@@ -34,6 +34,7 @@
|
||||
[checked]="isSelected(schema) | async"
|
||||
(change)="selectMetadataSchema(schema, $event)"
|
||||
>
|
||||
<span class="sr-only">{{((isSelected(schema) | async) ? 'admin.registries.metadata.schemas.deselect' : 'admin.registries.metadata.schemas.select') | translate}}</span>
|
||||
</label>
|
||||
</td>
|
||||
<td class="selectable-row" (click)="editSchema(schema)"><a [routerLink]="[schema.prefix]">{{schema.id}}</a></td>
|
||||
|
@@ -1,11 +1,11 @@
|
||||
<div *ngIf="registryService.getActiveMetadataSchema() | async; then editheader; else createHeader"></div>
|
||||
|
||||
<ng-template #createHeader>
|
||||
<h4>{{messagePrefix + '.create' | translate}}</h4>
|
||||
<h2>{{messagePrefix + '.create' | translate}}</h2>
|
||||
</ng-template>
|
||||
|
||||
<ng-template #editheader>
|
||||
<h4>{{messagePrefix + '.edit' | translate}}</h4>
|
||||
<h2>{{messagePrefix + '.edit' | translate}}</h2>
|
||||
</ng-template>
|
||||
|
||||
<ds-form [formId]="formId"
|
||||
|
@@ -1,11 +1,11 @@
|
||||
<div *ngIf="registryService.getActiveMetadataField() | async; then editheader; else createHeader"></div>
|
||||
|
||||
<ng-template #createHeader>
|
||||
<h4>{{messagePrefix + '.create' | translate}}</h4>
|
||||
<h2>{{messagePrefix + '.create' | translate}}</h2>
|
||||
</ng-template>
|
||||
|
||||
<ng-template #editheader>
|
||||
<h4>{{messagePrefix + '.edit' | translate}}</h4>
|
||||
<h2>{{messagePrefix + '.edit' | translate}}</h2>
|
||||
</ng-template>
|
||||
|
||||
<ds-form [formId]="formId"
|
||||
|
@@ -2,7 +2,7 @@
|
||||
<div class="metadata-schema row">
|
||||
<div class="col-12" *ngVar="(metadataSchema$ | async) as schema">
|
||||
|
||||
<h2 id="header" class="border-bottom pb-2">{{'admin.registries.schema.head' | translate}}: "{{schema?.prefix}}"</h2>
|
||||
<h1 id="header" class="border-bottom pb-2">{{'admin.registries.schema.head' | translate}}: "{{schema?.prefix}}"</h1>
|
||||
|
||||
<p id="description" class="pb-2">{{'admin.registries.schema.description' | translate:{ namespace: schema?.namespace } }}</p>
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
[metadataSchema]="schema"
|
||||
(submitForm)="forceUpdateFields()"></ds-metadata-field-form>
|
||||
|
||||
<h3>{{'admin.registries.schema.fields.head' | translate}}</h3>
|
||||
<h2>{{'admin.registries.schema.fields.head' | translate}}</h2>
|
||||
|
||||
<ng-container *ngVar="(metadataFields$ | async)?.payload as fields">
|
||||
<ds-pagination
|
||||
@@ -24,7 +24,7 @@
|
||||
<table id="metadata-fields" class="table table-striped table-hover">
|
||||
<thead>
|
||||
<tr>
|
||||
<th></th>
|
||||
<th><span class="sr-only">{{'admin.registries.schema.fields.table.selected' | translate}}</span></th>
|
||||
<th scope="col">{{'admin.registries.schema.fields.table.id' | translate}}</th>
|
||||
<th scope="col">{{'admin.registries.schema.fields.table.field' | translate}}</th>
|
||||
<th scope="col">{{'admin.registries.schema.fields.table.scopenote' | translate}}</th>
|
||||
@@ -33,12 +33,11 @@
|
||||
<tbody>
|
||||
<tr *ngFor="let field of fields?.page"
|
||||
[ngClass]="{'table-primary' : isActive(field) | async}">
|
||||
<td>
|
||||
<label class="mb-0">
|
||||
<input type="checkbox"
|
||||
[checked]="isSelected(field) | async"
|
||||
(change)="selectMetadataField(field, $event)">
|
||||
</label>
|
||||
<td *ngVar="(isSelected(field) | async) as selected">
|
||||
<input type="checkbox"
|
||||
[attr.aria-label]="(selected ? 'admin.registries.schema.fields.deselect' : 'admin.registries.schema.fields.select') | translate"
|
||||
[checked]="selected"
|
||||
(change)="selectMetadataField(field, $event)">
|
||||
</td>
|
||||
<td class="selectable-row" (click)="editField(field)">{{field.id}}</td>
|
||||
<td class="selectable-row" (click)="editField(field)">{{schema?.prefix}}.{{field.element}}{{field.qualifier ? '.' + field.qualifier : ''}}</td>
|
||||
|
37
src/app/admin/admin-reports/admin-reports-routing.module.ts
Normal file
37
src/app/admin/admin-reports/admin-reports-routing.module.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { FilteredCollectionsComponent } from './filtered-collections/filtered-collections.component';
|
||||
import { FilteredItemsComponent } from './filtered-items/filtered-items.component';
|
||||
import { RouterModule } from '@angular/router';
|
||||
import { NgModule } from '@angular/core';
|
||||
import { I18nBreadcrumbResolver } from '../../core/breadcrumbs/i18n-breadcrumb.resolver';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
RouterModule.forChild([
|
||||
{
|
||||
path: 'collections',
|
||||
resolve: { breadcrumb: I18nBreadcrumbResolver },
|
||||
data: {title: 'admin.reports.collections.title', breadcrumbKey: 'admin.reports.collections'},
|
||||
children: [
|
||||
{
|
||||
path: '',
|
||||
component: FilteredCollectionsComponent
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
path: 'queries',
|
||||
resolve: { breadcrumb: I18nBreadcrumbResolver },
|
||||
data: {title: 'admin.reports.items.title', breadcrumbKey: 'admin.reports.items'},
|
||||
children: [
|
||||
{
|
||||
path: '',
|
||||
component: FilteredItemsComponent
|
||||
}
|
||||
]
|
||||
}
|
||||
])
|
||||
]
|
||||
})
|
||||
export class AdminReportsRoutingModule {
|
||||
|
||||
}
|
28
src/app/admin/admin-reports/admin-reports.module.ts
Normal file
28
src/app/admin/admin-reports/admin-reports.module.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { NgModule } from '@angular/core';
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { FilteredCollectionsComponent } from './filtered-collections/filtered-collections.component';
|
||||
import { RouterModule } from '@angular/router';
|
||||
import { SharedModule } from '../../shared/shared.module';
|
||||
import { FormModule } from '../../shared/form/form.module';
|
||||
import { FilteredItemsComponent } from './filtered-items/filtered-items.component';
|
||||
import { AdminReportsRoutingModule } from './admin-reports-routing.module';
|
||||
import { NgbAccordionModule } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { FiltersComponent } from './filters-section/filters-section.component';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
CommonModule,
|
||||
SharedModule,
|
||||
RouterModule,
|
||||
FormModule,
|
||||
AdminReportsRoutingModule,
|
||||
NgbAccordionModule
|
||||
],
|
||||
declarations: [
|
||||
FilteredCollectionsComponent,
|
||||
FilteredItemsComponent,
|
||||
FiltersComponent
|
||||
]
|
||||
})
|
||||
export class AdminReportsModule {
|
||||
}
|
@@ -0,0 +1,36 @@
|
||||
export class FilteredCollection {
|
||||
|
||||
public label: string;
|
||||
public handle: string;
|
||||
public communityLabel: string;
|
||||
public communityHandle: string;
|
||||
public nbTotalItems: number;
|
||||
public values = {};
|
||||
public allFiltersValue: number;
|
||||
|
||||
public clear() {
|
||||
this.label = '';
|
||||
this.handle = '';
|
||||
this.communityLabel = '';
|
||||
this.communityHandle = '';
|
||||
this.nbTotalItems = 0;
|
||||
this.values = {};
|
||||
this.allFiltersValue = 0;
|
||||
}
|
||||
|
||||
public deserialize(object: any) {
|
||||
this.clear();
|
||||
this.label = object.label;
|
||||
this.handle = object.handle;
|
||||
this.communityLabel = object.community_label;
|
||||
this.communityHandle = object.community_handle;
|
||||
this.nbTotalItems = object.nb_total_items;
|
||||
let valuesPerFilter = object.values;
|
||||
for (let filter in valuesPerFilter) {
|
||||
if (valuesPerFilter.hasOwnProperty(filter)) {
|
||||
this.values[filter] = valuesPerFilter[filter];
|
||||
}
|
||||
}
|
||||
this.allFiltersValue = object.all_filters_value;
|
||||
}
|
||||
}
|
@@ -0,0 +1,64 @@
|
||||
<div class="container">
|
||||
<div class="metadata-registry row">
|
||||
<div class="col-12">
|
||||
|
||||
<h1 id="header" class="border-bottom pb-2">{{ "admin.reports.collections.head" | translate }}</h1>
|
||||
|
||||
<div id="metadatadiv">
|
||||
<ngb-accordion [closeOthers]="true" activeIds="filters" #acc="ngbAccordion">
|
||||
<ngb-panel id="filters">
|
||||
<ng-template ngbPanelTitle>
|
||||
{{ "admin.reports.commons.filters" | translate }}
|
||||
</ng-template>
|
||||
<ng-template ngbPanelContent>
|
||||
<div class="container">
|
||||
<div class="row">
|
||||
<span class="col-3"></span>
|
||||
<button class="btn btn-primary mt-1 col-6" (click)="submit()">{{ "admin.reports.button.show-collections" | translate }}</button>
|
||||
</div>
|
||||
<ds-filters [filtersForm]="filtersFormGroup()"></ds-filters>
|
||||
<div class="row">
|
||||
<span class="col-3"></span>
|
||||
<button class="btn btn-primary mt-1 col-6" (click)="submit()">{{ "admin.reports.button.show-collections" | translate }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</ng-template>
|
||||
</ngb-panel>
|
||||
<ngb-panel id="collections">
|
||||
<ng-template ngbPanelTitle>
|
||||
{{ "admin.reports.collections.collections-report" | translate }}
|
||||
</ng-template>
|
||||
<ng-template ngbPanelContent>
|
||||
<table id="table" class="table table-striped">
|
||||
<thead>
|
||||
<tr class="header">
|
||||
<th rowspan="2">{{ "admin.reports.collections.community" | translate }}</th>
|
||||
<th rowspan="2">{{ "admin.reports.collections.collection" | translate }}</th>
|
||||
<th>{{ "admin.reports.collections.nb_items" | translate }}</th>
|
||||
<th>{{ "admin.reports.collections.match_all_selected_filters" | translate }}</th>
|
||||
<th *ngFor="let filter of results.summary.values | keyvalue">{{ ("admin.reports.commons.filters." + getGroup(filter.key) + "." + filter.key) | translate }}</th>
|
||||
</tr>
|
||||
<tr class="header">
|
||||
<th class="num">{{ results.summary.nbTotalItems }}</th>
|
||||
<th class="num">{{ results.summary.allFiltersValue }}</th>
|
||||
<th class="num" *ngFor="let filter of results.summary.values | keyvalue">{{ filter.value }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr *ngFor="let coll of results.collections">
|
||||
<td><a href="/handle/{{ coll.communityHandle }}" rel="noopener noreferrer" target="_blank">{{ coll.communityLabel }}</a></td>
|
||||
<td><a href="/handle/{{ coll.handle }}" rel="noopener noreferrer" target="_blank">{{ coll.label }}</a></td>
|
||||
<td class="num">{{ coll.nbTotalItems }}</td>
|
||||
<td class="num">{{ coll.allFiltersValue }}</td>
|
||||
<td class="num" *ngFor="let filter of results.summary.values | keyvalue">{{ coll.values[filter.key] || 0 }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</ng-template>
|
||||
</ngb-panel>
|
||||
</ngb-accordion>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
@@ -0,0 +1,3 @@
|
||||
.num {
|
||||
text-align: center;
|
||||
}
|
@@ -0,0 +1,83 @@
|
||||
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
|
||||
import { NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
|
||||
import { TranslateLoaderMock } from 'src/app/shared/mocks/translate-loader.mock';
|
||||
import { FormBuilder } from '@angular/forms';
|
||||
import { FilteredCollectionsComponent } from './filtered-collections.component';
|
||||
import { DspaceRestService } from 'src/app/core/dspace-rest/dspace-rest.service';
|
||||
import { NgbAccordion, NgbAccordionModule } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { HttpClientTestingModule } from '@angular/common/http/testing';
|
||||
import { of as observableOf } from 'rxjs';
|
||||
import { RawRestResponse } from 'src/app/core/dspace-rest/raw-rest-response.model';
|
||||
|
||||
describe('FiltersComponent', () => {
|
||||
let component: FilteredCollectionsComponent;
|
||||
let fixture: ComponentFixture<FilteredCollectionsComponent>;
|
||||
let formBuilder: FormBuilder;
|
||||
|
||||
const expected = {
|
||||
payload: {
|
||||
collections: [],
|
||||
summary: {
|
||||
label: 'Test'
|
||||
}
|
||||
},
|
||||
statusCode: 200,
|
||||
statusText: 'OK'
|
||||
} as RawRestResponse;
|
||||
|
||||
beforeEach(waitForAsync(() => {
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [FilteredCollectionsComponent],
|
||||
imports: [
|
||||
NgbAccordionModule,
|
||||
TranslateModule.forRoot({
|
||||
loader: {
|
||||
provide: TranslateLoader,
|
||||
useClass: TranslateLoaderMock
|
||||
}
|
||||
}),
|
||||
HttpClientTestingModule
|
||||
],
|
||||
providers: [
|
||||
FormBuilder,
|
||||
DspaceRestService
|
||||
],
|
||||
schemas: [NO_ERRORS_SCHEMA]
|
||||
});
|
||||
}));
|
||||
|
||||
beforeEach(waitForAsync(() => {
|
||||
formBuilder = TestBed.inject(FormBuilder);
|
||||
|
||||
fixture = TestBed.createComponent(FilteredCollectionsComponent);
|
||||
component = fixture.componentInstance;
|
||||
fixture.detectChanges();
|
||||
}));
|
||||
|
||||
it('should create the component', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should be displaying the filters panel initially', () => {
|
||||
let accordion: NgbAccordion = component.accordionComponent;
|
||||
expect(accordion.isExpanded('filters')).toBeTrue();
|
||||
});
|
||||
|
||||
describe('toggle', () => {
|
||||
beforeEach(() => {
|
||||
spyOn(component, 'getFilteredCollections').and.returnValue(observableOf(expected));
|
||||
spyOn(component.results, 'deserialize');
|
||||
spyOn(component.accordionComponent, 'expand').and.callThrough();
|
||||
component.submit();
|
||||
fixture.detectChanges();
|
||||
});
|
||||
|
||||
it('should be displaying the collections panel after submitting', waitForAsync(() => {
|
||||
fixture.whenStable().then(() => {
|
||||
expect(component.accordionComponent.expand).toHaveBeenCalledWith('collections');
|
||||
expect(component.accordionComponent.isExpanded('collections')).toBeTrue();
|
||||
});
|
||||
}));
|
||||
});
|
||||
});
|
@@ -0,0 +1,70 @@
|
||||
import { Component, ViewChild } from '@angular/core';
|
||||
import { FormBuilder, FormGroup } from '@angular/forms';
|
||||
import { NgbAccordion } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { Observable } from 'rxjs';
|
||||
import { RestRequestMethod } from 'src/app/core/data/rest-request-method';
|
||||
import { DspaceRestService } from 'src/app/core/dspace-rest/dspace-rest.service';
|
||||
import { RawRestResponse } from 'src/app/core/dspace-rest/raw-rest-response.model';
|
||||
import { environment } from 'src/environments/environment';
|
||||
import { FiltersComponent } from '../filters-section/filters-section.component';
|
||||
import { FilteredCollections } from './filtered-collections.model';
|
||||
|
||||
/**
|
||||
* Component representing the Filtered Collections content report
|
||||
*/
|
||||
@Component({
|
||||
selector: 'ds-report-filtered-collections',
|
||||
templateUrl: './filtered-collections.component.html',
|
||||
styleUrls: ['./filtered-collections.component.scss']
|
||||
})
|
||||
export class FilteredCollectionsComponent {
|
||||
|
||||
queryForm: FormGroup;
|
||||
results: FilteredCollections = new FilteredCollections();
|
||||
@ViewChild('acc') accordionComponent: NgbAccordion;
|
||||
|
||||
constructor(
|
||||
private formBuilder: FormBuilder,
|
||||
private restService: DspaceRestService) {}
|
||||
|
||||
ngOnInit() {
|
||||
this.queryForm = this.formBuilder.group({
|
||||
filters: FiltersComponent.formGroup(this.formBuilder)
|
||||
});
|
||||
}
|
||||
|
||||
filtersFormGroup(): FormGroup {
|
||||
return this.queryForm.get('filters') as FormGroup;
|
||||
}
|
||||
|
||||
getGroup(filterId: string): string {
|
||||
return FiltersComponent.getGroup(filterId).id;
|
||||
}
|
||||
|
||||
submit() {
|
||||
this
|
||||
.getFilteredCollections()
|
||||
.subscribe(
|
||||
response => {
|
||||
this.results.deserialize(response.payload);
|
||||
this.accordionComponent.expand('collections');
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
getFilteredCollections(): Observable<RawRestResponse> {
|
||||
let params = this.toQueryString();
|
||||
if (params.length > 0) {
|
||||
params = `?${params}`;
|
||||
}
|
||||
let scheme = environment.rest.ssl ? 'https' : 'http';
|
||||
let urlRestApp = `${scheme}://${environment.rest.host}:${environment.rest.port}${environment.rest.nameSpace}`;
|
||||
return this.restService.request(RestRequestMethod.GET, `${urlRestApp}/api/contentreport/filteredcollections${params}`);
|
||||
}
|
||||
|
||||
private toQueryString(): string {
|
||||
let params = FiltersComponent.toQueryString(this.queryForm.value.filters);
|
||||
return params;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,26 @@
|
||||
import { FilteredCollection } from './filtered-collection.model';
|
||||
|
||||
export class FilteredCollections {
|
||||
|
||||
public collections: Array<FilteredCollection> = [];
|
||||
public summary: FilteredCollection = new FilteredCollection();
|
||||
|
||||
public clear() {
|
||||
this.collections.splice(0, this.collections.length);
|
||||
this.summary.clear();
|
||||
}
|
||||
|
||||
public deserialize(object: any) {
|
||||
this.clear();
|
||||
let summary = object.summary;
|
||||
this.summary.deserialize(summary);
|
||||
let collections = object.collections;
|
||||
for (let i = 0; i < collections.length; i++) {
|
||||
let collection = collections[i];
|
||||
let coll = new FilteredCollection();
|
||||
coll.deserialize(collection);
|
||||
this.collections.push(coll);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,23 @@
|
||||
import { Item } from 'src/app/core/shared/item.model';
|
||||
|
||||
export class FilteredItems {
|
||||
|
||||
public items: Item[] = [];
|
||||
public itemCount: number;
|
||||
|
||||
public clear() {
|
||||
this.items.splice(0, this.items.length);
|
||||
}
|
||||
|
||||
public deserialize(object: any, offset: number = 0) {
|
||||
this.clear();
|
||||
this.itemCount = object.itemCount;
|
||||
let items = object.items;
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
let item = items[i];
|
||||
item.index = this.items.length + offset + 1;
|
||||
this.items.push(item);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,175 @@
|
||||
<div class="container">
|
||||
<div class="metadata-registry row">
|
||||
<div class="col-12">
|
||||
|
||||
<h1 id="header" class="border-bottom pb-2">{{'admin.reports.items.head' | translate}}</h1>
|
||||
|
||||
<div id="querydiv" [formGroup]="queryForm">
|
||||
<ngb-accordion [closeOthers]="true" activeIds="collectionSelector" #acc="ngbAccordion">
|
||||
<ngb-panel id="collectionSelector">
|
||||
<ng-template ngbPanelTitle>
|
||||
{{'admin.reports.items.section.collectionSelector' | translate}}
|
||||
</ng-template>
|
||||
<ng-template ngbPanelContent>
|
||||
<select id="collSel" name="collSel" class="form-control" multiple="multiple" size="10" formControlName="collections">
|
||||
<option *ngFor="let item of collections" [value]="item.id" [disabled]="item.disabled">{{item.name$ | async}}</option>
|
||||
</select>
|
||||
<div class="row">
|
||||
<span class="col-3"></span>
|
||||
<button class="btn btn-primary mt-1 col-6" (click)="submit()">{{'admin.reports.items.run' | translate}}</button>
|
||||
</div>
|
||||
</ng-template>
|
||||
</ngb-panel>
|
||||
<ngb-panel id="metadataFieldQueries">
|
||||
<ng-template ngbPanelTitle>
|
||||
{{'admin.reports.items.section.metadataFieldQueries' | translate}}
|
||||
</ng-template>
|
||||
<ng-template ngbPanelContent>
|
||||
<fieldset id="predefqueries" class="form-group">
|
||||
<label>
|
||||
{{'admin.reports.items.predefinedQueries' | translate}}
|
||||
</label>
|
||||
<select id="predefselect" formControlName="presetQuery" class="form-control" (change)="setPresetQuery()">
|
||||
<option *ngFor="let item of presetQueries" [value]="item.id" [selected]="item.isDefault">{{item.label | translate}}</option>
|
||||
</select>
|
||||
</fieldset>
|
||||
<div class="row"> </div>
|
||||
<div id="queries">
|
||||
<div class="metadata" *ngFor="let pred of queryPredicatesArray().controls; let i = index">
|
||||
<div [formGroup]="pred" class="form-group">
|
||||
<div class="form-row">
|
||||
<div class="col-4">
|
||||
<select class="query-tool" formControlName="field" class="form-control">
|
||||
<option *ngFor="let item of metadataFieldsWithAny" [value]="item.id">{{item.name$ | async}}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-auto">
|
||||
<select class="query-tool" formControlName="operator" class="form-control">
|
||||
<option *ngFor="let item of predicates" [value]="item.id">{{item.name$ | async | translate}}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col">
|
||||
<input class="form-control" formControlName="value"/>
|
||||
</div>
|
||||
<div class="col-auto">
|
||||
<button class="btn btn-light" (click)="addQueryPredicate()">+</button>
|
||||
|
||||
<button class="btn btn-light" [disabled]="deleteQueryPredicateDisabled()" (click)="deleteQueryPredicate(i)">–</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<span class="col-3"></span>
|
||||
<button class="btn btn-primary mt-1 col-6" (click)="submit()">{{'admin.reports.items.run' | translate}}</button>
|
||||
</div>
|
||||
</ng-template>
|
||||
</ngb-panel>
|
||||
<ngb-panel id="limitPaginateQueries">
|
||||
<ng-template ngbPanelTitle>
|
||||
{{'admin.reports.items.section.limitPaginateQueries' | translate}}
|
||||
</ng-template>
|
||||
<ng-template ngbPanelContent>
|
||||
<div class="row align-items-center">
|
||||
<label for="limit" class="col-sm-2 col-form-label">{{'admin.reports.items.limit' | translate}}:</label>
|
||||
<div class="col-6">
|
||||
<select id="limit" name="limit" formControlName="pageLimit" class="form-control col-6">
|
||||
<option *ngFor="let item of pageLimits" value="{{item.id}}" [selected]="item.isDefault">{{item.name$ | async}}</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row align-items-center">
|
||||
<label for="offset" class="col-sm-2 col-form-label">{{'admin.reports.items.offset' | translate}}:</label>
|
||||
<div class="col-6">
|
||||
<input id="offset" name="offset" value="0" class="form-control col-6">
|
||||
</div>
|
||||
</div>
|
||||
<div class="row">
|
||||
<span class="col-3"></span>
|
||||
<button class="btn btn-primary mt-1 col-6" (click)="submit()">{{'admin.reports.items.run' | translate}}</button>
|
||||
</div>
|
||||
</ng-template>
|
||||
</ngb-panel>
|
||||
<ngb-panel id="filters">
|
||||
<ng-template ngbPanelTitle>
|
||||
{{'admin.reports.commons.filters' | translate}}
|
||||
</ng-template>
|
||||
<ng-template ngbPanelContent>
|
||||
<div class="row">
|
||||
<span class="col-3"></span>
|
||||
<button class="btn btn-primary mt-1 col-6" (click)="submit()">{{'admin.reports.items.run' | translate}}</button>
|
||||
</div>
|
||||
<ds-filters [filtersForm]="filtersFormGroup()"></ds-filters>
|
||||
<div class="row">
|
||||
<span class="col-3"></span>
|
||||
<button class="btn btn-primary mt-1 col-6" (click)="submit()">{{'admin.reports.items.run' | translate}}</button>
|
||||
</div>
|
||||
</ng-template>
|
||||
</ngb-panel>
|
||||
<ngb-panel id="additionalData">
|
||||
<ng-template ngbPanelTitle>
|
||||
{{'admin.reports.commons.additional-data' | translate}}
|
||||
</ng-template>
|
||||
<ng-template ngbPanelContent>
|
||||
<div id="show-fields">
|
||||
<select class="query-tool" name="show_fields" multiple="multiple" size="8" class="form-control" formControlName="additionalFields">
|
||||
<option *ngFor="let item of metadataFields" [value]="item.id">{{item.name$ | async}}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="row">
|
||||
<span class="col-3"></span>
|
||||
<button class="btn btn-primary mt-1 col-6" (click)="submit()">{{'admin.reports.items.run' | translate}}</button>
|
||||
</div>
|
||||
</ng-template>
|
||||
</ngb-panel>
|
||||
<ngb-panel id="itemResults">
|
||||
<ng-template ngbPanelTitle>
|
||||
{{'admin.reports.collections.item-results' | translate}}
|
||||
</ng-template>
|
||||
<ng-template ngbPanelContent>
|
||||
<table id="table" class="table table-striped">
|
||||
<thead>
|
||||
<tr class="header">
|
||||
<th>{{ "admin.reports.items.number" | translate }}</th>
|
||||
<th>{{ "admin.reports.items.id" | translate }}</th>
|
||||
<th>{{ "admin.reports.items.collection" | translate }}</th>
|
||||
<th>{{ "admin.reports.items.handle" | translate }}</th>
|
||||
<th>{{ "admin.reports.items.title" | translate }}</th>
|
||||
<th *ngFor="let field of queryForm.value['additionalFields']">{{ field }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr *ngFor="let item of results$ | async">
|
||||
<td class="num">{{ item.index }}</td>
|
||||
<td>{{ item.uuid }}</td>
|
||||
<td><a *ngIf="item.owningCollection" href="/handle/{{ item.owningCollection.handle }}" rel="noopener noreferrer" target="_blank">{{ item.owningCollection.name }}</a></td>
|
||||
<td><a *ngIf="item.handle" href="/handle/{{ item.handle }}" rel="noopener noreferrer" target="_blank">{{ item.handle }}</a></td>
|
||||
<td>{{ item.name }}</td>
|
||||
<td class="num" *ngFor="let field of queryForm.value['additionalFields']">
|
||||
<span *ngFor="let mdvalue of item.metadata[field]">
|
||||
{{ mdvalue.value || "" }}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div>
|
||||
{{'admin.reports.commons.page' | translate}} {{ currentPage + 1 }} {{'admin.reports.commons.of' | translate}} {{ pageCount() }}
|
||||
</div>
|
||||
<div>
|
||||
<button id="prev" class="btn btn-light" (click)="prevPage()" [disabled]="!canNavigatePrevious()">{{'admin.reports.commons.previous-page' | translate}}</button>
|
||||
<button id="next" class="btn btn-light" (click)="nextPage()" [disabled]="!canNavigateNext()">{{'admin.reports.commons.next-page' | translate}}</button>
|
||||
<!--
|
||||
<button id="export">{{'admin.reports.commons.export' | translate}}</button>
|
||||
-->
|
||||
</div>
|
||||
<table id="itemtable" class="sortable"></table>
|
||||
</ng-template>
|
||||
</ngb-panel>
|
||||
</ngb-accordion>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
@@ -0,0 +1,3 @@
|
||||
.num {
|
||||
text-align: center;
|
||||
}
|
@@ -0,0 +1,336 @@
|
||||
import { Component, ViewChild } from '@angular/core';
|
||||
import { FormArray, FormBuilder, FormControl, FormGroup } from '@angular/forms';
|
||||
import { NgbAccordion } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { TranslateService } from '@ngx-translate/core';
|
||||
import { map, Observable } from 'rxjs';
|
||||
import { CollectionDataService } from 'src/app/core/data/collection-data.service';
|
||||
import { CommunityDataService } from 'src/app/core/data/community-data.service';
|
||||
import { MetadataFieldDataService } from 'src/app/core/data/metadata-field-data.service';
|
||||
import { MetadataSchemaDataService } from 'src/app/core/data/metadata-schema-data.service';
|
||||
import { RestRequestMethod } from 'src/app/core/data/rest-request-method';
|
||||
import { DspaceRestService } from 'src/app/core/dspace-rest/dspace-rest.service';
|
||||
import { RawRestResponse } from 'src/app/core/dspace-rest/raw-rest-response.model';
|
||||
import { MetadataField } from 'src/app/core/metadata/metadata-field.model';
|
||||
import { MetadataSchema } from 'src/app/core/metadata/metadata-schema.model';
|
||||
import { Collection } from 'src/app/core/shared/collection.model';
|
||||
import { Community } from 'src/app/core/shared/community.model';
|
||||
import { Item } from 'src/app/core/shared/item.model';
|
||||
import { getFirstSucceededRemoteListPayload } from 'src/app/core/shared/operators';
|
||||
import { isEmpty } from 'src/app/shared/empty.util';
|
||||
import { environment } from 'src/environments/environment';
|
||||
import { FiltersComponent } from '../filters-section/filters-section.component';
|
||||
import { FilteredItems } from './filtered-items-model';
|
||||
import { OptionVO } from './option-vo.model';
|
||||
import { PresetQuery } from './preset-query.model';
|
||||
import { QueryPredicate } from './query-predicate.model';
|
||||
|
||||
/**
|
||||
* Component representing the Filtered Items content report.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'ds-report-filtered-items',
|
||||
templateUrl: './filtered-items.component.html',
|
||||
styleUrls: ['./filtered-items.component.scss']
|
||||
})
|
||||
export class FilteredItemsComponent {
|
||||
|
||||
collections: OptionVO[];
|
||||
presetQueries: PresetQuery[];
|
||||
metadataFields: OptionVO[];
|
||||
metadataFieldsWithAny: OptionVO[];
|
||||
predicates: OptionVO[];
|
||||
pageLimits: OptionVO[];
|
||||
|
||||
queryForm: FormGroup;
|
||||
currentPage = 0;
|
||||
results: FilteredItems = new FilteredItems();
|
||||
results$: Observable<Item[]>;
|
||||
@ViewChild('acc') accordionComponent: NgbAccordion;
|
||||
|
||||
constructor(
|
||||
private communityService: CommunityDataService,
|
||||
private collectionService: CollectionDataService,
|
||||
private metadataSchemaService: MetadataSchemaDataService,
|
||||
private metadataFieldService: MetadataFieldDataService,
|
||||
private translateService: TranslateService,
|
||||
private formBuilder: FormBuilder,
|
||||
private restService: DspaceRestService) {}
|
||||
|
||||
ngOnInit() {
|
||||
this.loadCollections();
|
||||
this.loadPresetQueries();
|
||||
this.loadMetadataFields();
|
||||
this.loadPredicates();
|
||||
this.loadPageLimits();
|
||||
|
||||
let formQueryPredicates: FormGroup[] = [
|
||||
new QueryPredicate().toFormGroup(this.formBuilder)
|
||||
];
|
||||
|
||||
this.queryForm = this.formBuilder.group({
|
||||
collections: this.formBuilder.control([''], []),
|
||||
presetQuery: this.formBuilder.control('new', []),
|
||||
queryPredicates: this.formBuilder.array(formQueryPredicates),
|
||||
pageLimit: this.formBuilder.control('10', []),
|
||||
filters: FiltersComponent.formGroup(this.formBuilder),
|
||||
additionalFields: this.formBuilder.control([], [])
|
||||
});
|
||||
}
|
||||
|
||||
loadCollections(): void {
|
||||
this.collections = [];
|
||||
let wholeRepo$ = this.translateService.stream('admin.reports.items.wholeRepo');
|
||||
this.collections.push(OptionVO.collectionLoc('', wholeRepo$));
|
||||
|
||||
this.communityService.findAll({ elementsPerPage: 10000, currentPage: 1 }).pipe(
|
||||
getFirstSucceededRemoteListPayload()
|
||||
).subscribe(
|
||||
(communitiesRest: Community[]) => {
|
||||
communitiesRest.forEach(community => {
|
||||
let commVO = OptionVO.collection(community.uuid, community.name, true);
|
||||
this.collections.push(commVO);
|
||||
|
||||
this.collectionService.findByParent(community.uuid, { elementsPerPage: 10000, currentPage: 1 }).pipe(
|
||||
getFirstSucceededRemoteListPayload()
|
||||
).subscribe(
|
||||
(collectionsRest: Collection[]) => {
|
||||
collectionsRest.filter(collection => collection.firstMetadataValue('dspace.entity.type') === 'Publication')
|
||||
.forEach(collection => {
|
||||
let collVO = OptionVO.collection(collection.uuid, '–' + collection.name);
|
||||
this.collections.push(collVO);
|
||||
});
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
loadPresetQueries(): void {
|
||||
this.presetQueries = [
|
||||
PresetQuery.of('new', 'admin.reports.items.preset.new', []),
|
||||
PresetQuery.of('q1', 'admin.reports.items.preset.hasNoTitle', [
|
||||
QueryPredicate.of('dc.title', QueryPredicate.DOES_NOT_EXIST)
|
||||
]),
|
||||
PresetQuery.of('q2', 'admin.reports.items.preset.hasNoIdentifierUri', [
|
||||
QueryPredicate.of('dc.identifier.uri', QueryPredicate.DOES_NOT_EXIST)
|
||||
]),
|
||||
PresetQuery.of('q3', 'admin.reports.items.preset.hasCompoundSubject', [
|
||||
QueryPredicate.of('dc.subject.*', QueryPredicate.LIKE, '%;%')
|
||||
]),
|
||||
PresetQuery.of('q4', 'admin.reports.items.preset.hasCompoundAuthor', [
|
||||
QueryPredicate.of('dc.contributor.author', QueryPredicate.LIKE, '% and %')
|
||||
]),
|
||||
PresetQuery.of('q5', 'admin.reports.items.preset.hasCompoundCreator', [
|
||||
QueryPredicate.of('dc.creator', QueryPredicate.LIKE, '% and %')
|
||||
]),
|
||||
PresetQuery.of('q6', 'admin.reports.items.preset.hasUrlInDescription', [
|
||||
QueryPredicate.of('dc.description', QueryPredicate.MATCHES, '^.*(http://|https://|mailto:).*$')
|
||||
]),
|
||||
PresetQuery.of('q7', 'admin.reports.items.preset.hasFullTextInProvenance', [
|
||||
QueryPredicate.of('dc.description.provenance', QueryPredicate.MATCHES, '^.*No\. of bitstreams(.|\r|\n|\r\n)*\.(PDF|pdf|DOC|doc|PPT|ppt|DOCX|docx|PPTX|pptx).*$')
|
||||
]),
|
||||
PresetQuery.of('q8', 'admin.reports.items.preset.hasNonFullTextInProvenance', [
|
||||
QueryPredicate.of('dc.description.provenance', QueryPredicate.DOES_NOT_MATCH, '^.*No\. of bitstreams(.|\r|\n|\r\n)*\.(PDF|pdf|DOC|doc|PPT|ppt|DOCX|docx|PPTX|pptx).*$')
|
||||
]),
|
||||
PresetQuery.of('q9', 'admin.reports.items.preset.hasEmptyMetadata', [
|
||||
QueryPredicate.of('*', QueryPredicate.MATCHES, '^\s*$')
|
||||
]),
|
||||
PresetQuery.of('q10', 'admin.reports.items.preset.hasUnbreakingDataInDescription', [
|
||||
QueryPredicate.of('dc.description.*', QueryPredicate.MATCHES, '^.*[^\s]{50,}.*$')
|
||||
]),
|
||||
PresetQuery.of('q12', 'admin.reports.items.preset.hasXmlEntityInMetadata', [
|
||||
QueryPredicate.of('*', QueryPredicate.MATCHES, '^.*&#.*$')
|
||||
]),
|
||||
PresetQuery.of('q13', 'admin.reports.items.preset.hasNonAsciiCharInMetadata', [
|
||||
QueryPredicate.of('*', QueryPredicate.MATCHES, '^.*[^[:ascii:]].*$')
|
||||
])
|
||||
];
|
||||
}
|
||||
|
||||
loadMetadataFields(): void {
|
||||
this.metadataFields = [];
|
||||
this.metadataFieldsWithAny = [];
|
||||
let anyField$ = this.translateService.stream('admin.reports.items.anyField');
|
||||
this.metadataFieldsWithAny.push(OptionVO.itemLoc('*', anyField$));
|
||||
this.metadataSchemaService.findAll({ elementsPerPage: 10000, currentPage: 1 }).pipe(
|
||||
getFirstSucceededRemoteListPayload()
|
||||
).subscribe(
|
||||
(schemasRest: MetadataSchema[]) => {
|
||||
schemasRest.forEach(schema => {
|
||||
this.metadataFieldService.findBySchema(schema, { elementsPerPage: 10000, currentPage: 1 }).pipe(
|
||||
getFirstSucceededRemoteListPayload()
|
||||
).subscribe(
|
||||
(fieldsRest: MetadataField[]) => {
|
||||
fieldsRest.forEach(field => {
|
||||
let fieldName = schema.prefix + '.' + field.toString();
|
||||
let fieldVO = OptionVO.item(fieldName, fieldName);
|
||||
this.metadataFields.push(fieldVO);
|
||||
this.metadataFieldsWithAny.push(fieldVO);
|
||||
if (isEmpty(field.qualifier)) {
|
||||
fieldName = schema.prefix + '.' + field.element + '.*';
|
||||
fieldVO = OptionVO.item(fieldName, fieldName);
|
||||
this.metadataFieldsWithAny.push(fieldVO);
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
loadPredicates(): void {
|
||||
this.predicates = [
|
||||
OptionVO.item(QueryPredicate.EXISTS, 'admin.reports.items.predicate.exists'),
|
||||
OptionVO.item(QueryPredicate.DOES_NOT_EXIST, 'admin.reports.items.predicate.doesNotExist'),
|
||||
OptionVO.item(QueryPredicate.EQUALS, 'admin.reports.items.predicate.equals'),
|
||||
OptionVO.item(QueryPredicate.DOES_NOT_EQUAL, 'admin.reports.items.predicate.doesNotEqual'),
|
||||
OptionVO.item(QueryPredicate.LIKE, 'admin.reports.items.predicate.like'),
|
||||
OptionVO.item(QueryPredicate.NOT_LIKE, 'admin.reports.items.predicate.notLike'),
|
||||
OptionVO.item(QueryPredicate.CONTAINS, 'admin.reports.items.predicate.contains'),
|
||||
OptionVO.item(QueryPredicate.DOES_NOT_CONTAIN, 'admin.reports.items.predicate.doesNotContain'),
|
||||
OptionVO.item(QueryPredicate.MATCHES, 'admin.reports.items.predicate.matches'),
|
||||
OptionVO.item(QueryPredicate.DOES_NOT_MATCH, 'admin.reports.items.predicate.doesNotMatch')
|
||||
];
|
||||
}
|
||||
|
||||
loadPageLimits(): void {
|
||||
this.pageLimits = [
|
||||
OptionVO.item('10', '10'),
|
||||
OptionVO.item('25', '25'),
|
||||
OptionVO.item('50', '50'),
|
||||
OptionVO.item('100', '100')
|
||||
];
|
||||
}
|
||||
|
||||
queryPredicatesArray(): FormArray {
|
||||
return (this.queryForm.get('queryPredicates') as FormArray);
|
||||
}
|
||||
|
||||
addQueryPredicate(newItem: FormGroup = new QueryPredicate().toFormGroup(this.formBuilder)) {
|
||||
this.queryPredicatesArray().push(newItem);
|
||||
}
|
||||
|
||||
deleteQueryPredicateDisabled(): boolean {
|
||||
return this.queryPredicatesArray().length < 2;
|
||||
}
|
||||
|
||||
deleteQueryPredicate(index: number, nbToDelete: number = 1) {
|
||||
if (index > -1) {
|
||||
this.queryPredicatesArray().removeAt(index);
|
||||
}
|
||||
}
|
||||
|
||||
setPresetQuery() {
|
||||
let queryField = this.queryForm.controls.presetQuery as FormControl;
|
||||
let value = queryField.value;
|
||||
let query = this.presetQueries.find(q => q.id === value);
|
||||
if (query !== undefined) {
|
||||
this.queryPredicatesArray().clear();
|
||||
query.predicates
|
||||
.map(qp => qp.toFormGroup(this.formBuilder))
|
||||
.forEach(qp => this.addQueryPredicate(qp));
|
||||
if (query.predicates.length === 0) {
|
||||
this.addQueryPredicate(new QueryPredicate().toFormGroup(this.formBuilder));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
filtersFormGroup(): FormGroup {
|
||||
return this.queryForm.get('filters') as FormGroup;
|
||||
}
|
||||
|
||||
private pageSize() {
|
||||
let form = this.queryForm.value;
|
||||
return form.pageLimit;
|
||||
}
|
||||
|
||||
canNavigatePrevious(): boolean {
|
||||
return this.currentPage > 0;
|
||||
}
|
||||
|
||||
prevPage() {
|
||||
if (this.canNavigatePrevious()) {
|
||||
this.currentPage--;
|
||||
this.resubmit();
|
||||
}
|
||||
}
|
||||
|
||||
pageCount(): number {
|
||||
let total = this.results.itemCount || 0;
|
||||
return Math.ceil(total / this.pageSize());
|
||||
}
|
||||
|
||||
canNavigateNext(): boolean {
|
||||
return this.currentPage + 1 < this.pageCount();
|
||||
}
|
||||
|
||||
nextPage() {
|
||||
if (this.canNavigateNext()) {
|
||||
this.currentPage++;
|
||||
this.resubmit();
|
||||
}
|
||||
}
|
||||
|
||||
submit() {
|
||||
this.accordionComponent.expand('itemResults');
|
||||
this.currentPage = 0;
|
||||
this.resubmit();
|
||||
}
|
||||
|
||||
resubmit() {
|
||||
this.results$ = this
|
||||
.getFilteredItems()
|
||||
.pipe(
|
||||
map(response => {
|
||||
let offset = this.currentPage * this.pageSize();
|
||||
this.results.deserialize(response.payload, offset);
|
||||
return this.results.items;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
getFilteredItems(): Observable<RawRestResponse> {
|
||||
let params = this.toQueryString();
|
||||
if (params.length > 0) {
|
||||
params = `?${params}`;
|
||||
}
|
||||
let scheme = environment.rest.ssl ? 'https' : 'http';
|
||||
let urlRestApp = `${scheme}://${environment.rest.host}:${environment.rest.port}${environment.rest.nameSpace}`;
|
||||
return this.restService.request(RestRequestMethod.GET, `${urlRestApp}/api/contentreport/filtereditems${params}`);
|
||||
}
|
||||
|
||||
private toQueryString(): string {
|
||||
let params = `pageNumber=${this.currentPage}&pageLimit=${this.pageSize()}`;
|
||||
|
||||
let colls = this.queryForm.value.collections;
|
||||
for (let i = 0; i < colls.length; i++) {
|
||||
params += `&collections=${colls[i]}`;
|
||||
}
|
||||
|
||||
let preds = this.queryForm.value.queryPredicates;
|
||||
for (let i = 0; i < preds.length; i++) {
|
||||
const field = preds[i].field;
|
||||
const op = preds[i].operator;
|
||||
const value = preds[i].value;
|
||||
params += `&queryPredicates=${field}:${op}`;
|
||||
if (value) {
|
||||
params += `:${value}`;
|
||||
}
|
||||
}
|
||||
|
||||
let filters = FiltersComponent.toQueryString(this.queryForm.value.filters);
|
||||
if (filters.length > 0) {
|
||||
params += `&${filters}`;
|
||||
}
|
||||
|
||||
let addFlds = this.queryForm.value.additionalFields;
|
||||
for (let i = 0; i < addFlds.length; i++) {
|
||||
params += `&additionalFields=${addFlds[i]}`;
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,50 @@
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
/**
|
||||
* Component representing an option in each selectable list of values
|
||||
* used in the Filtered Items report query interface
|
||||
*/
|
||||
export class OptionVO {
|
||||
|
||||
id: string;
|
||||
name$: Observable<string>;
|
||||
disabled = false;
|
||||
|
||||
static collection(id: string, name: string, disabled: boolean = false): OptionVO {
|
||||
let opt = new OptionVO();
|
||||
opt.id = id;
|
||||
opt.name$ = OptionVO.toObservable(name);
|
||||
opt.disabled = disabled;
|
||||
return opt;
|
||||
}
|
||||
|
||||
static collectionLoc(id: string, name$: Observable<string>, disabled: boolean = false): OptionVO {
|
||||
let opt = new OptionVO();
|
||||
opt.id = id;
|
||||
opt.name$ = name$;
|
||||
opt.disabled = disabled;
|
||||
return opt;
|
||||
}
|
||||
|
||||
static item(id: string, name: string): OptionVO {
|
||||
let opt = new OptionVO();
|
||||
opt.id = id;
|
||||
opt.name$ = OptionVO.toObservable(name);
|
||||
return opt;
|
||||
}
|
||||
|
||||
static itemLoc(id: string, name$: Observable<string>): OptionVO {
|
||||
let opt = new OptionVO();
|
||||
opt.id = id;
|
||||
opt.name$ = name$;
|
||||
return opt;
|
||||
}
|
||||
|
||||
private static toObservable<T>(value: T): Observable<T> {
|
||||
return new Observable<T>(subscriber => {
|
||||
subscriber.next(value);
|
||||
subscriber.complete();
|
||||
});
|
||||
|
||||
}
|
||||
}
|
@@ -0,0 +1,17 @@
|
||||
import { QueryPredicate } from './query-predicate.model';
|
||||
|
||||
export class PresetQuery {
|
||||
|
||||
id: string;
|
||||
label: string;
|
||||
predicates: QueryPredicate[];
|
||||
|
||||
static of(id: string, label: string, predicates: QueryPredicate[]) {
|
||||
let query = new PresetQuery();
|
||||
query.id = id;
|
||||
query.label = label;
|
||||
query.predicates = predicates;
|
||||
return query;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,36 @@
|
||||
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
|
||||
|
||||
export class QueryPredicate {
|
||||
|
||||
static EXISTS = 'exists';
|
||||
static DOES_NOT_EXIST = 'doesnt_exist';
|
||||
static EQUALS = 'equals';
|
||||
static DOES_NOT_EQUAL = 'not_equals';
|
||||
static LIKE = 'like';
|
||||
static NOT_LIKE = 'not_like';
|
||||
static CONTAINS = 'contains';
|
||||
static DOES_NOT_CONTAIN = 'doesnt_contain';
|
||||
static MATCHES = 'matches';
|
||||
static DOES_NOT_MATCH = 'doesnt_match';
|
||||
|
||||
field = '*';
|
||||
operator: string;
|
||||
value: string;
|
||||
|
||||
static of(field: string, operator: string, value: string = '') {
|
||||
let pred = new QueryPredicate();
|
||||
pred.field = field;
|
||||
pred.operator = operator;
|
||||
pred.value = value;
|
||||
return pred;
|
||||
}
|
||||
|
||||
toFormGroup(formBuilder: FormBuilder): FormGroup {
|
||||
return formBuilder.group({
|
||||
field: new FormControl(this.field),
|
||||
operator: new FormControl(this.operator),
|
||||
value: new FormControl(this.value)
|
||||
});
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,19 @@
|
||||
import { Filter } from './filter.model';
|
||||
|
||||
export class FilterGroup {
|
||||
|
||||
id: string;
|
||||
key: string;
|
||||
|
||||
constructor(id: string, public filters: Filter[]) {
|
||||
this.id = id;
|
||||
this.key = 'admin.reports.commons.filters.' + id;
|
||||
filters.forEach(filter => {
|
||||
filter.key = this.key + '.' + filter.id;
|
||||
if (filter.hasTooltip) {
|
||||
filter.tooltipKey = filter.key + '.tooltip';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,8 @@
|
||||
export class Filter {
|
||||
|
||||
key: string;
|
||||
tooltipKey: string;
|
||||
|
||||
constructor(public id: string, public hasTooltip: boolean = false) {}
|
||||
|
||||
}
|
@@ -0,0 +1,19 @@
|
||||
<fieldset class="row row-cols-2">
|
||||
<ng-container>
|
||||
<span class="col-12"> </span>
|
||||
<span class="col-1"> </span>
|
||||
<button id="btnSelectAllFilters" class="btn btn-light mt-1 col-4" (click)="selectAll()">{{"admin.reports.commons.filters.select_all" | translate}}</button>
|
||||
<span class="col-2"> </span>
|
||||
<button id="btnDeselectAllFilters" class="btn btn-light mt-1 col-4" (click)="deselectAll()">{{"admin.reports.commons.filters.deselect_all" | translate}}</button>
|
||||
<span class="col-1"> </span>
|
||||
<span class="col-12"> </span>
|
||||
</ng-container>
|
||||
</fieldset>
|
||||
<fieldset class="row row-cols-2" *ngFor="let group of allFilters()">
|
||||
<legend>{{group.key | translate}}</legend>
|
||||
<ng-container [formGroup]="filtersForm">
|
||||
<div *ngFor="let filter of group.filters" class="col-6">
|
||||
<input type="checkbox" id="flt-{{filter.id}}" value="{{filter.id}}" class="form-check-input col-1 align-baseline" formControlName="{{filter.id}}"><label for="flt-{{filter.id}}" class="col-11 align-middle" title="{{filter.tooltipKey | translate}}">{{filter.key | translate}}</label>
|
||||
</div>
|
||||
</ng-container>
|
||||
</fieldset>
|
@@ -0,0 +1,101 @@
|
||||
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
|
||||
import { NO_ERRORS_SCHEMA } from '@angular/core';
|
||||
import { FiltersComponent } from './filters-section.component';
|
||||
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
|
||||
import { TranslateLoaderMock } from 'src/app/shared/mocks/translate-loader.mock';
|
||||
import { FormBuilder } from '@angular/forms';
|
||||
|
||||
describe('FiltersComponent', () => {
|
||||
let component: FiltersComponent;
|
||||
let fixture: ComponentFixture<FiltersComponent>;
|
||||
let formBuilder: FormBuilder;
|
||||
|
||||
beforeEach(waitForAsync(() => {
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [FiltersComponent],
|
||||
imports: [
|
||||
TranslateModule.forRoot({
|
||||
loader: {
|
||||
provide: TranslateLoader,
|
||||
useClass: TranslateLoaderMock
|
||||
}
|
||||
})
|
||||
],
|
||||
providers: [
|
||||
FormBuilder
|
||||
],
|
||||
schemas: [NO_ERRORS_SCHEMA]
|
||||
});
|
||||
}));
|
||||
|
||||
beforeEach(waitForAsync(() => {
|
||||
formBuilder = TestBed.inject(FormBuilder);
|
||||
|
||||
fixture = TestBed.createComponent(FiltersComponent);
|
||||
component = fixture.componentInstance;
|
||||
component.filtersForm = FiltersComponent.formGroup(formBuilder);
|
||||
fixture.detectChanges();
|
||||
}));
|
||||
|
||||
const isOneSelected = (values: {}): boolean => {
|
||||
let oneSelected = false;
|
||||
let allFilters = FiltersComponent.FILTERS;
|
||||
for (let i = 0; !oneSelected && i < allFilters.length; i++) {
|
||||
let group = allFilters[i];
|
||||
for (let j = 0; j < group.filters.length; j++) {
|
||||
let filter = group.filters[j];
|
||||
oneSelected = oneSelected || values[filter.id];
|
||||
}
|
||||
}
|
||||
return oneSelected;
|
||||
};
|
||||
|
||||
const isAllSelected = (values: {}): boolean => {
|
||||
let allSelected = true;
|
||||
let allFilters = FiltersComponent.FILTERS;
|
||||
for (let i = 0; allSelected && i < allFilters.length; i++) {
|
||||
let group = allFilters[i];
|
||||
for (let j = 0; j < group.filters.length; j++) {
|
||||
let filter = group.filters[j];
|
||||
allSelected = allSelected && values[filter.id];
|
||||
}
|
||||
}
|
||||
return allSelected;
|
||||
};
|
||||
|
||||
it('should create the component', () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
|
||||
it('should select all checkboxes', () => {
|
||||
// By default, nothing is selected, so at least one item is not selected.
|
||||
let values = component.filtersForm.value;
|
||||
let allSelected: boolean = isAllSelected(values);
|
||||
expect(allSelected).toBeFalse();
|
||||
|
||||
// Now we select everything...
|
||||
component.selectAll();
|
||||
|
||||
// We must retrieve the form values again since selectAll() injects a new dictionary.
|
||||
values = component.filtersForm.value;
|
||||
allSelected = isAllSelected(values);
|
||||
expect(allSelected).toBeTrue();
|
||||
});
|
||||
|
||||
it('should deselect all checkboxes', () => {
|
||||
// Since nothing is selected by default, we select at least an item
|
||||
// so that deselectAll() actually deselects something.
|
||||
let values = component.filtersForm.value;
|
||||
values.is_item = true;
|
||||
let oneSelected: boolean = isOneSelected(values);
|
||||
expect(oneSelected).toBeTrue();
|
||||
|
||||
// Now we deselect everything...
|
||||
component.deselectAll();
|
||||
|
||||
// We must retrieve the form values again since deselectAll() injects a new dictionary.
|
||||
values = component.filtersForm.value;
|
||||
oneSelected = isOneSelected(values);
|
||||
expect(oneSelected).toBeFalse();
|
||||
});
|
||||
});
|
@@ -0,0 +1,149 @@
|
||||
import { Component, Input } from '@angular/core';
|
||||
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
|
||||
import { FilterGroup } from './filter-group.model';
|
||||
import { Filter } from './filter.model';
|
||||
|
||||
/**
|
||||
* Component representing the Query Filters section used in both
|
||||
* Filtered Collections and Filtered Items content reports
|
||||
*/
|
||||
@Component({
|
||||
selector: 'ds-filters',
|
||||
templateUrl: './filters-section.component.html',
|
||||
styleUrls: ['./filters-section.component.scss']
|
||||
})
|
||||
export class FiltersComponent {
|
||||
|
||||
static FILTERS = [
|
||||
new FilterGroup('property', [
|
||||
new Filter('is_item'),
|
||||
new Filter('is_withdrawn'),
|
||||
new Filter('is_not_withdrawn'),
|
||||
new Filter('is_discoverable'),
|
||||
new Filter('is_not_discoverable')
|
||||
]),
|
||||
new FilterGroup('bitstream', [
|
||||
new Filter('has_multiple_originals'),
|
||||
new Filter('has_no_originals'),
|
||||
new Filter('has_one_original')
|
||||
]),
|
||||
new FilterGroup('bitstream_mime', [
|
||||
new Filter('has_doc_original'),
|
||||
new Filter('has_image_original'),
|
||||
new Filter('has_unsupp_type'),
|
||||
new Filter('has_mixed_original'),
|
||||
new Filter('has_pdf_original'),
|
||||
new Filter('has_jpg_original'),
|
||||
new Filter('has_small_pdf'),
|
||||
new Filter('has_large_pdf'),
|
||||
new Filter('has_doc_without_text')
|
||||
]),
|
||||
new FilterGroup('mime', [
|
||||
new Filter('has_only_supp_image_type'),
|
||||
new Filter('has_unsupp_image_type'),
|
||||
new Filter('has_only_supp_doc_type'),
|
||||
new Filter('has_unsupp_doc_type')
|
||||
]),
|
||||
new FilterGroup('bundle', [
|
||||
new Filter('has_unsupported_bundle'),
|
||||
new Filter('has_small_thumbnail'),
|
||||
new Filter('has_original_without_thumbnail'),
|
||||
new Filter('has_invalid_thumbnail_name'),
|
||||
new Filter('has_non_generated_thumb'),
|
||||
new Filter('no_license'),
|
||||
new Filter('has_license_documentation')
|
||||
]),
|
||||
new FilterGroup('permission', [
|
||||
new Filter('has_restricted_original', true),
|
||||
new Filter('has_restricted_thumbnail', true),
|
||||
new Filter('has_restricted_metadata', true)
|
||||
])
|
||||
];
|
||||
|
||||
@Input() filtersForm: FormGroup;
|
||||
|
||||
static formGroup(formBuilder: FormBuilder): FormGroup {
|
||||
let fields = {};
|
||||
let allFilters = FiltersComponent.FILTERS;
|
||||
for (let i = 0; i < allFilters.length; i++) {
|
||||
let group = allFilters[i];
|
||||
for (let j = 0; j < group.filters.length; j++) {
|
||||
let filter = group.filters[j];
|
||||
fields[filter.id] = new FormControl(false);
|
||||
}
|
||||
}
|
||||
return formBuilder.group(fields);
|
||||
}
|
||||
|
||||
static getFilter(filterId: string): Filter {
|
||||
let allFilters = FiltersComponent.FILTERS;
|
||||
for (let i = 0; i < allFilters.length; i++) {
|
||||
let group = allFilters[i];
|
||||
for (let j = 0; j < group.filters.length; j++) {
|
||||
let filter = group.filters[j];
|
||||
if (filter.id === filterId) {
|
||||
return filter;
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
static getGroup(filterId: string): FilterGroup {
|
||||
let allFilters = FiltersComponent.FILTERS;
|
||||
for (let i = 0; i < allFilters.length; i++) {
|
||||
let group = allFilters[i];
|
||||
for (let j = 0; j < group.filters.length; j++) {
|
||||
let filter = group.filters[j];
|
||||
if (filter.id === filterId) {
|
||||
return group;
|
||||
}
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
static toQueryString(filters: Object): string {
|
||||
let params = '';
|
||||
let first = true;
|
||||
for (const key in filters) {
|
||||
if (filters[key]) {
|
||||
if (first) {
|
||||
first = false;
|
||||
} else {
|
||||
params += '&';
|
||||
}
|
||||
params += `filters=${key}`;
|
||||
}
|
||||
}
|
||||
return params;
|
||||
}
|
||||
|
||||
allFilters(): FilterGroup[] {
|
||||
return FiltersComponent.FILTERS;
|
||||
}
|
||||
|
||||
private setAllFilters(value: boolean) {
|
||||
// I don't know why, but patchValue() with individual controls doesn't work.
|
||||
// I therefore use setValue() with the whole set, which mercifully works...
|
||||
let fields = {};
|
||||
let allFilters = FiltersComponent.FILTERS;
|
||||
for (let i = 0; i < allFilters.length; i++) {
|
||||
let group = allFilters[i];
|
||||
for (let j = 0; j < group.filters.length; j++) {
|
||||
let filter = group.filters[j];
|
||||
fields[filter.id] = value;
|
||||
}
|
||||
}
|
||||
this.filtersForm.setValue(fields);
|
||||
}
|
||||
|
||||
selectAll(): void {
|
||||
this.setAllFilters(true);
|
||||
}
|
||||
|
||||
deselectAll(): void {
|
||||
this.setAllFilters(false);
|
||||
}
|
||||
|
||||
}
|
@@ -1,13 +1,30 @@
|
||||
import { getAdminModuleRoute } from '../app-routing-paths';
|
||||
import { URLCombiner } from '../core/url-combiner/url-combiner';
|
||||
import { getAdminModuleRoute } from '../app-routing-paths';
|
||||
import { getQualityAssuranceEditRoute } from './admin-notifications/admin-notifications-routing-paths';
|
||||
|
||||
export const REGISTRIES_MODULE_PATH = 'registries';
|
||||
export const NOTIFICATIONS_MODULE_PATH = 'notifications';
|
||||
export const LDN_PATH = 'ldn';
|
||||
export const REPORTS_MODULE_PATH = 'reports';
|
||||
export const NOTIFY_DASHBOARD_MODULE_PATH = 'notify-dashboard';
|
||||
|
||||
|
||||
export function getRegistriesModuleRoute() {
|
||||
return new URLCombiner(getAdminModuleRoute(), REGISTRIES_MODULE_PATH).toString();
|
||||
}
|
||||
|
||||
export function getLdnServicesModuleRoute() {
|
||||
return new URLCombiner(getAdminModuleRoute(), LDN_PATH).toString();
|
||||
}
|
||||
|
||||
export function getNotificationsModuleRoute() {
|
||||
return new URLCombiner(getAdminModuleRoute(), NOTIFICATIONS_MODULE_PATH).toString();
|
||||
}
|
||||
|
||||
export function getNotificatioQualityAssuranceRoute() {
|
||||
return new URLCombiner(`/${NOTIFICATIONS_MODULE_PATH}`, getQualityAssuranceEditRoute()).toString();
|
||||
}
|
||||
|
||||
export function getReportsModuleRoute() {
|
||||
return new URLCombiner(getAdminModuleRoute(), REPORTS_MODULE_PATH).toString();
|
||||
}
|
||||
|
@@ -6,12 +6,10 @@ import { I18nBreadcrumbsService } from '../core/breadcrumbs/i18n-breadcrumbs.ser
|
||||
import { AdminCurationTasksComponent } from './admin-curation-tasks/admin-curation-tasks.component';
|
||||
import { BatchImportPageComponent } from './admin-import-batch-page/batch-import-page.component';
|
||||
import { MetadataImportPageComponent } from './admin-import-metadata-page/metadata-import-page.component';
|
||||
import {
|
||||
NOTIFICATIONS_MODULE_PATH,
|
||||
REGISTRIES_MODULE_PATH,
|
||||
} from './admin-routing-paths';
|
||||
import { LDN_PATH, NOTIFICATIONS_MODULE_PATH, NOTIFY_DASHBOARD_MODULE_PATH, REGISTRIES_MODULE_PATH, REPORTS_MODULE_PATH } from './admin-routing-paths';
|
||||
import { AdminSearchPageComponent } from './admin-search-page/admin-search-page.component';
|
||||
import { AdminWorkflowPageComponent } from './admin-workflow-page/admin-workflow-page.component';
|
||||
import { SiteAdministratorGuard } from '../core/data/feature-authorization/feature-authorization-guard/site-administrator.guard';
|
||||
|
||||
@NgModule({
|
||||
imports: [
|
||||
@@ -25,42 +23,70 @@ import { AdminWorkflowPageComponent } from './admin-workflow-page/admin-workflow
|
||||
path: REGISTRIES_MODULE_PATH,
|
||||
loadChildren: () => import('./admin-registries/admin-registries.module')
|
||||
.then((m) => m.AdminRegistriesModule),
|
||||
canActivate: [SiteAdministratorGuard]
|
||||
},
|
||||
{
|
||||
path: 'search',
|
||||
resolve: { breadcrumb: I18nBreadcrumbResolver },
|
||||
component: AdminSearchPageComponent,
|
||||
data: { title: 'admin.search.title', breadcrumbKey: 'admin.search' },
|
||||
canActivate: [SiteAdministratorGuard]
|
||||
},
|
||||
{
|
||||
path: 'workflow',
|
||||
resolve: { breadcrumb: I18nBreadcrumbResolver },
|
||||
component: AdminWorkflowPageComponent,
|
||||
data: { title: 'admin.workflow.title', breadcrumbKey: 'admin.workflow' },
|
||||
canActivate: [SiteAdministratorGuard]
|
||||
},
|
||||
{
|
||||
path: 'curation-tasks',
|
||||
resolve: { breadcrumb: I18nBreadcrumbResolver },
|
||||
component: AdminCurationTasksComponent,
|
||||
data: { title: 'admin.curation-tasks.title', breadcrumbKey: 'admin.curation-tasks' },
|
||||
canActivate: [SiteAdministratorGuard]
|
||||
},
|
||||
{
|
||||
path: 'metadata-import',
|
||||
resolve: { breadcrumb: I18nBreadcrumbResolver },
|
||||
component: MetadataImportPageComponent,
|
||||
data: { title: 'admin.metadata-import.title', breadcrumbKey: 'admin.metadata-import' },
|
||||
canActivate: [SiteAdministratorGuard]
|
||||
},
|
||||
{
|
||||
path: 'batch-import',
|
||||
resolve: { breadcrumb: I18nBreadcrumbResolver },
|
||||
component: BatchImportPageComponent,
|
||||
data: { title: 'admin.batch-import.title', breadcrumbKey: 'admin.batch-import' },
|
||||
canActivate: [SiteAdministratorGuard]
|
||||
},
|
||||
{
|
||||
path: 'system-wide-alert',
|
||||
resolve: { breadcrumb: I18nBreadcrumbResolver },
|
||||
loadChildren: () => import('../system-wide-alert/system-wide-alert.module').then((m) => m.SystemWideAlertModule),
|
||||
data: { title: 'admin.system-wide-alert.title', breadcrumbKey: 'admin.system-wide-alert' },
|
||||
data: {title: 'admin.system-wide-alert.title', breadcrumbKey: 'admin.system-wide-alert'},
|
||||
canActivate: [SiteAdministratorGuard]
|
||||
},
|
||||
{
|
||||
path: LDN_PATH,
|
||||
children: [
|
||||
{ path: '', pathMatch: 'full', redirectTo: 'services' },
|
||||
{
|
||||
path: 'services',
|
||||
loadChildren: () => import('./admin-ldn-services/admin-ldn-services.module')
|
||||
.then((m) => m.AdminLdnServicesModule),
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
path: REPORTS_MODULE_PATH,
|
||||
loadChildren: () => import('./admin-reports/admin-reports.module')
|
||||
.then((m) => m.AdminReportsModule),
|
||||
},
|
||||
{
|
||||
path: NOTIFY_DASHBOARD_MODULE_PATH,
|
||||
loadChildren: () => import('./admin-notify-dashboard/admin-notify-dashboard.module')
|
||||
.then((m) => m.AdminNotifyDashboardModule),
|
||||
},
|
||||
]),
|
||||
],
|
||||
|
@@ -1,4 +1,4 @@
|
||||
<ng-template dsListableObject>
|
||||
<ng-template dsDynamicComponentLoader>
|
||||
</ng-template>
|
||||
<div #badges>
|
||||
<ng-content></ng-content>
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user