Merge branch 'use-applied-filter-to-display-label-on-search_contribute-main' into advanced-search_contribute-main

# Conflicts:
#	src/app/core/shared/search/search-configuration.service.spec.ts
#	src/app/core/shared/search/search-filter.service.spec.ts
#	src/app/core/shared/search/search-filter.service.ts
#	src/app/core/shared/search/search.service.ts
#	src/app/shared/search/advanced-search/advanced-search.component.html
#	src/app/shared/search/advanced-search/advanced-search.component.scss
#	src/app/shared/search/advanced-search/advanced-search.component.spec.ts
#	src/app/shared/search/advanced-search/advanced-search.component.ts
#	src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.spec.ts
#	src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.spec.ts
#	src/app/shared/search/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.ts
#	src/app/shared/search/search-filters/search-filter/search-facet-filter-wrapper/search-facet-filter-wrapper.component.ts
#	src/app/shared/search/search-filters/search-filter/search-facet-filter/search-facet-filter.component.spec.ts
#	src/app/shared/search/search-filters/search-filter/search-facet-filter/search-facet-filter.component.ts
#	src/app/shared/search/search-filters/search-filter/search-filter.actions.ts
#	src/app/shared/search/search-filters/search-filter/search-filter.component.ts
#	src/app/shared/search/search-filters/search-filter/search-filter.reducer.ts
#	src/app/shared/search/search-filters/search-filter/search-hierarchy-filter/search-hierarchy-filter.component.spec.ts
#	src/app/shared/search/search-filters/search-filter/search-hierarchy-filter/search-hierarchy-filter.component.ts
#	src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.html
#	src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.spec.ts
#	src/app/shared/search/search-filters/search-filter/search-range-filter/search-range-filter.component.ts
#	src/app/shared/search/search-filters/search-filters.component.html
#	src/app/shared/search/search-filters/search-filters.component.ts
#	src/app/shared/search/search-filters/themed-search-filters.component.ts
#	src/app/shared/search/search-labels/search-label-loader/search-label-loader.component.ts
#	src/app/shared/search/search-labels/search-label-loader/search-label-loader.decorator.ts
#	src/app/shared/search/search-labels/search-label-range/search-label-range.component.html
#	src/app/shared/search/search-labels/search-label-range/search-label-range.component.spec.ts
#	src/app/shared/search/search-labels/search-label-range/search-label-range.component.ts
#	src/app/shared/search/search-labels/search-label/search-label.component.html
#	src/app/shared/search/search-labels/search-label/search-label.component.spec.ts
#	src/app/shared/search/search-labels/search-label/search-label.component.ts
#	src/app/shared/search/search-labels/search-labels.component.ts
#	src/app/shared/search/search-sidebar/search-sidebar.component.html
#	src/app/shared/search/search-sidebar/search-sidebar.component.ts
#	src/app/shared/search/search-sidebar/themed-search-sidebar.component.ts
#	src/app/shared/search/search.component.html
#	src/app/shared/search/search.component.ts
#	src/app/shared/search/search.module.ts
#	src/app/shared/testing/search-configuration-service.stub.ts
#	src/assets/i18n/en.json5
This commit is contained in:
Alexandre Vryghem
2024-04-30 16:41:45 +02:00
3278 changed files with 132835 additions and 56507 deletions

View File

@@ -0,0 +1,117 @@
import { AbstractControl } from '@angular/forms';
import {
mapToCanActivate,
Route,
} from '@angular/router';
import {
DYNAMIC_ERROR_MESSAGES_MATCHER,
DynamicErrorMessagesMatcher,
} from '@ng-dynamic-forms/core';
import { i18nBreadcrumbResolver } from '../core/breadcrumbs/i18n-breadcrumb.resolver';
import { GroupAdministratorGuard } from '../core/data/feature-authorization/feature-authorization-guard/group-administrator.guard';
import { SiteAdministratorGuard } from '../core/data/feature-authorization/feature-authorization-guard/site-administrator.guard';
import {
EPERSON_PATH,
GROUP_PATH,
} from './access-control-routing-paths';
import { BulkAccessComponent } from './bulk-access/bulk-access.component';
import { EPeopleRegistryComponent } from './epeople-registry/epeople-registry.component';
import { EPersonFormComponent } from './epeople-registry/eperson-form/eperson-form.component';
import { EPersonResolver } from './epeople-registry/eperson-resolver.service';
import { GroupFormComponent } from './group-registry/group-form/group-form.component';
import { GroupPageGuard } from './group-registry/group-page.guard';
import { GroupsRegistryComponent } from './group-registry/groups-registry.component';
/**
* Condition for displaying error messages on email form field
*/
export const ValidateEmailErrorStateMatcher: DynamicErrorMessagesMatcher =
(control: AbstractControl, model: any, hasFocus: boolean) => {
return (control.touched && !hasFocus) || (control.errors?.emailTaken && hasFocus);
};
const providers = [
{
provide: DYNAMIC_ERROR_MESSAGES_MATCHER,
useValue: ValidateEmailErrorStateMatcher,
},
];
export const ROUTES: Route[] = [
{
path: EPERSON_PATH,
component: EPeopleRegistryComponent,
resolve: {
breadcrumb: i18nBreadcrumbResolver,
},
providers,
data: { title: 'admin.access-control.epeople.title', breadcrumbKey: 'admin.access-control.epeople' },
canActivate: mapToCanActivate([SiteAdministratorGuard]),
},
{
path: `${EPERSON_PATH}/create`,
component: EPersonFormComponent,
resolve: {
breadcrumb: i18nBreadcrumbResolver,
},
providers,
data: { title: 'admin.access-control.epeople.add.title', breadcrumbKey: 'admin.access-control.epeople.add' },
canActivate: mapToCanActivate([SiteAdministratorGuard]),
},
{
path: `${EPERSON_PATH}/:id/edit`,
component: EPersonFormComponent,
resolve: {
breadcrumb: i18nBreadcrumbResolver,
ePerson: EPersonResolver,
},
providers,
data: { title: 'admin.access-control.epeople.edit.title', breadcrumbKey: 'admin.access-control.epeople.edit' },
canActivate: mapToCanActivate([SiteAdministratorGuard]),
},
{
path: GROUP_PATH,
component: GroupsRegistryComponent,
resolve: {
breadcrumb: i18nBreadcrumbResolver,
},
providers,
data: { title: 'admin.access-control.groups.title', breadcrumbKey: 'admin.access-control.groups' },
canActivate: mapToCanActivate([GroupAdministratorGuard]),
},
{
path: `${GROUP_PATH}/create`,
component: GroupFormComponent,
resolve: {
breadcrumb: i18nBreadcrumbResolver,
},
providers,
data: {
title: 'admin.access-control.groups.title.addGroup',
breadcrumbKey: 'admin.access-control.groups.addGroup',
},
canActivate: mapToCanActivate([GroupAdministratorGuard]),
},
{
path: `${GROUP_PATH}/:groupId/edit`,
component: GroupFormComponent,
resolve: {
breadcrumb: i18nBreadcrumbResolver,
},
providers,
data: {
title: 'admin.access-control.groups.title.singleGroup',
breadcrumbKey: 'admin.access-control.groups.singleGroup',
},
canActivate: mapToCanActivate([GroupPageGuard]),
},
{
path: 'bulk-access',
component: BulkAccessComponent,
resolve: {
breadcrumb: i18nBreadcrumbResolver,
},
data: { title: 'admin.access-control.bulk-access.title', breadcrumbKey: 'admin.access-control.bulk-access' },
canActivate: mapToCanActivate([SiteAdministratorGuard]),
},
];

View File

@@ -1,12 +1,22 @@
import { URLCombiner } from '../core/url-combiner/url-combiner';
import { getAccessControlModuleRoute } from '../app-routing-paths';
import { URLCombiner } from '../core/url-combiner/url-combiner';
export const GROUP_EDIT_PATH = 'groups';
export const EPERSON_PATH = 'epeople';
export function getEPersonsRoute(): string {
return new URLCombiner(getAccessControlModuleRoute(), EPERSON_PATH).toString();
}
export function getEPersonEditRoute(id: string): string {
return new URLCombiner(getEPersonsRoute(), id, 'edit').toString();
}
export const GROUP_PATH = 'groups';
export function getGroupsRoute() {
return new URLCombiner(getAccessControlModuleRoute(), GROUP_EDIT_PATH).toString();
return new URLCombiner(getAccessControlModuleRoute(), GROUP_PATH).toString();
}
export function getGroupEditRoute(id: string) {
return new URLCombiner(getAccessControlModuleRoute(), GROUP_EDIT_PATH, id).toString();
return new URLCombiner(getGroupsRoute(), id, 'edit').toString();
}

View File

@@ -1,73 +0,0 @@
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { EPeopleRegistryComponent } from './epeople-registry/epeople-registry.component';
import { GroupFormComponent } from './group-registry/group-form/group-form.component';
import { GroupsRegistryComponent } from './group-registry/groups-registry.component';
import { GROUP_EDIT_PATH } from './access-control-routing-paths';
import { I18nBreadcrumbResolver } from '../core/breadcrumbs/i18n-breadcrumb.resolver';
import { GroupPageGuard } from './group-registry/group-page.guard';
import {
GroupAdministratorGuard
} from '../core/data/feature-authorization/feature-authorization-guard/group-administrator.guard';
import {
SiteAdministratorGuard
} from '../core/data/feature-authorization/feature-authorization-guard/site-administrator.guard';
import { BulkAccessComponent } from './bulk-access/bulk-access.component';
@NgModule({
imports: [
RouterModule.forChild([
{
path: 'epeople',
component: EPeopleRegistryComponent,
resolve: {
breadcrumb: I18nBreadcrumbResolver
},
data: { title: 'admin.access-control.epeople.title', breadcrumbKey: 'admin.access-control.epeople' },
canActivate: [SiteAdministratorGuard]
},
{
path: GROUP_EDIT_PATH,
component: GroupsRegistryComponent,
resolve: {
breadcrumb: I18nBreadcrumbResolver
},
data: { title: 'admin.access-control.groups.title', breadcrumbKey: 'admin.access-control.groups' },
canActivate: [GroupAdministratorGuard]
},
{
path: `${GROUP_EDIT_PATH}/newGroup`,
component: GroupFormComponent,
resolve: {
breadcrumb: I18nBreadcrumbResolver
},
data: { title: 'admin.access-control.groups.title.addGroup', breadcrumbKey: 'admin.access-control.groups.addGroup' },
canActivate: [GroupAdministratorGuard]
},
{
path: `${GROUP_EDIT_PATH}/:groupId`,
component: GroupFormComponent,
resolve: {
breadcrumb: I18nBreadcrumbResolver
},
data: { title: 'admin.access-control.groups.title.singleGroup', breadcrumbKey: 'admin.access-control.groups.singleGroup' },
canActivate: [GroupPageGuard]
},
{
path: 'bulk-access',
component: BulkAccessComponent,
resolve: {
breadcrumb: I18nBreadcrumbResolver
},
data: { title: 'admin.access-control.bulk-access.title', breadcrumbKey: 'admin.access-control.bulk-access' },
canActivate: [SiteAdministratorGuard]
},
])
]
})
/**
* Routing module for the AccessControl section of the admin sidebar
*/
export class AccessControlRoutingModule {
}

View File

@@ -1,67 +0,0 @@
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { SharedModule } from '../shared/shared.module';
import { AccessControlRoutingModule } from './access-control-routing.module';
import { EPeopleRegistryComponent } from './epeople-registry/epeople-registry.component';
import { EPersonFormComponent } from './epeople-registry/eperson-form/eperson-form.component';
import { GroupFormComponent } from './group-registry/group-form/group-form.component';
import { MembersListComponent } from './group-registry/group-form/members-list/members-list.component';
import { SubgroupsListComponent } from './group-registry/group-form/subgroup-list/subgroups-list.component';
import { GroupsRegistryComponent } from './group-registry/groups-registry.component';
import { FormModule } from '../shared/form/form.module';
import { DYNAMIC_ERROR_MESSAGES_MATCHER, DynamicErrorMessagesMatcher } from '@ng-dynamic-forms/core';
import { AbstractControl } from '@angular/forms';
import { BulkAccessComponent } from './bulk-access/bulk-access.component';
import { NgbAccordionModule } from '@ng-bootstrap/ng-bootstrap';
import { BulkAccessBrowseComponent } from './bulk-access/browse/bulk-access-browse.component';
import { BulkAccessSettingsComponent } from './bulk-access/settings/bulk-access-settings.component';
import { SearchModule } from '../shared/search/search.module';
import { AccessControlFormModule } from '../shared/access-control-form-container/access-control-form.module';
/**
* Condition for displaying error messages on email form field
*/
export const ValidateEmailErrorStateMatcher: DynamicErrorMessagesMatcher =
(control: AbstractControl, model: any, hasFocus: boolean) => {
return (control.touched && !hasFocus) || (control.errors?.emailTaken && hasFocus);
};
@NgModule({
imports: [
CommonModule,
SharedModule,
RouterModule,
AccessControlRoutingModule,
FormModule,
NgbAccordionModule,
SearchModule,
AccessControlFormModule,
],
exports: [
MembersListComponent,
],
declarations: [
EPeopleRegistryComponent,
EPersonFormComponent,
GroupsRegistryComponent,
GroupFormComponent,
SubgroupsListComponent,
MembersListComponent,
BulkAccessComponent,
BulkAccessBrowseComponent,
BulkAccessSettingsComponent,
],
providers: [
{
provide: DYNAMIC_ERROR_MESSAGES_MATCHER,
useValue: ValidateEmailErrorStateMatcher
},
]
})
/**
* This module handles all components related to the access control pages
*/
export class AccessControlModule {
}

View File

@@ -1,15 +1,15 @@
<ngb-accordion #acc="ngbAccordion" [activeIds]="'browse'">
<ngb-panel [id]="'browse'">
<ng-template ngbPanelHeader>
<div class="w-100 d-flex justify-content-between collapse-toggle" ngbPanelToggle (click)="acc.toggle('browse')"
<div class="w-100 d-flex gap-3 justify-content-between collapse-toggle" ngbPanelToggle (click)="acc.toggle('browse')"
data-test="browse">
<button type="button" class="btn btn-link p-0" (click)="$event.preventDefault()"
[attr.aria-expanded]="!acc.isExpanded('browse')"
aria-controls="collapsePanels">
[attr.aria-expanded]="acc.isExpanded('browse')"
aria-controls="bulk-access-browse-panel-content">
{{ 'admin.access-control.bulk-access-browse.header' | translate }}
</button>
<div class="text-right d-flex">
<div class="ml-3 d-inline-block">
<div class="text-right d-flex gap-2">
<div class="d-flex my-auto">
<span *ngIf="acc.isExpanded('browse')" class="fas fa-chevron-up fa-fw"></span>
<span *ngIf="!acc.isExpanded('browse')" class="fas fa-chevron-down fa-fw"></span>
</div>
@@ -17,51 +17,52 @@
</div>
</ng-template>
<ng-template ngbPanelContent>
<ul ngbNav #nav="ngbNav" [(activeId)]="activateId" class="nav-pills">
<li [ngbNavItem]="'search'">
<a ngbNavLink>{{'admin.access-control.bulk-access-browse.search.header' | translate}}</a>
<ng-template ngbNavContent>
<div class="mx-n3">
<ds-themed-search [configuration]="'administrativeBulkAccess'"
[selectable]="true"
[selectionConfig]="{ repeatable: true, listId: listId }"
[showThumbnails]="false"></ds-themed-search>
</div>
</ng-template>
</li>
<li [ngbNavItem]="'selected'">
<a ngbNavLink>
{{'admin.access-control.bulk-access-browse.selected.header' | translate: {number: ((objectsSelected$ | async)?.payload?.totalElements) ? (objectsSelected$ | async)?.payload?.totalElements : '0'} }}
</a>
<ng-template ngbNavContent>
<ds-pagination
[paginationOptions]="(paginationOptions$ | async)"
[pageInfoState]="(objectsSelected$|async)?.payload.pageInfo"
[collectionSize]="(objectsSelected$|async)?.payload?.totalElements"
[objects]="(objectsSelected$|async)"
[showPaginator]="false"
(prev)="pagePrev()"
(next)="pageNext()">
<ul *ngIf="(objectsSelected$|async)?.hasSucceeded" class="list-unstyled ml-4">
<li *ngFor='let object of (objectsSelected$|async)?.payload?.page | paginate: { itemsPerPage: (paginationOptions$ | async).pageSize,
currentPage: (paginationOptions$ | async).currentPage, totalItems: (objectsSelected$|async)?.payload?.page.length }; let i = index; let last = last '
class="mt-4 mb-4 d-flex"
[attr.data-test]="'list-object' | dsBrowserOnly">
<ds-selectable-list-item-control [index]="i"
[object]="object"
[selectionConfig]="{ repeatable: true, listId: listId }"></ds-selectable-list-item-control>
<ds-listable-object-component-loader [listID]="listId"
[index]="i"
[object]="object"
[showThumbnails]="false"
[viewMode]="'list'"></ds-listable-object-component-loader>
</li>
</ul>
</ds-pagination>
</ng-template>
</li>
</ul>
<div [ngbNavOutlet]="nav" class="mt-5"></div>
<div id="bulk-access-browse-panel-content">
<ul ngbNav #nav="ngbNav" [(activeId)]="activateId" class="nav-pills">
<li [ngbNavItem]="'search'" role="presentation">
<a ngbNavLink>{{'admin.access-control.bulk-access-browse.search.header' | translate}}</a>
<ng-template ngbNavContent>
<div class="mx-n3">
<ds-themed-search [configuration]="'administrativeBulkAccess'"
[selectable]="true"
[selectionConfig]="{ repeatable: true, listId: listId }"
[showThumbnails]="false"></ds-themed-search>
</div>
</ng-template>
</li>
<li [ngbNavItem]="'selected'" role="presentation">
<a ngbNavLink>
{{'admin.access-control.bulk-access-browse.selected.header' | translate: {number: ((objectsSelected$ | async)?.payload?.totalElements) ? (objectsSelected$ | async)?.payload?.totalElements : '0'} }}
</a>
<ng-template ngbNavContent>
<ds-pagination
[paginationOptions]="(paginationOptions$ | async)"
[collectionSize]="(objectsSelected$|async)?.payload?.totalElements"
[objects]="(objectsSelected$|async)"
[showPaginator]="false"
(prev)="pagePrev()"
(next)="pageNext()">
<ul *ngIf="(objectsSelected$|async)?.hasSucceeded" class="list-unstyled ml-4">
<li *ngFor='let object of (objectsSelected$|async)?.payload?.page | paginate: { itemsPerPage: (paginationOptions$ | async).pageSize,
currentPage: (paginationOptions$ | async).currentPage, totalItems: (objectsSelected$|async)?.payload?.page.length }; let i = index; let last = last '
class="mt-4 mb-4 d-flex"
[attr.data-test]="'list-object' | dsBrowserOnly">
<ds-selectable-list-item-control [index]="i"
[object]="object"
[selectionConfig]="{ repeatable: true, listId: listId }"></ds-selectable-list-item-control>
<ds-listable-object-component-loader [listID]="listId"
[index]="i"
[object]="object"
[showThumbnails]="false"
[viewMode]="'list'"></ds-listable-object-component-loader>
</li>
</ul>
</ds-pagination>
</ng-template>
</li>
</ul>
<div [ngbNavOutlet]="nav" class="mt-5"></div>
</div>
</ng-template>
</ngb-panel>
</ngb-accordion>

View File

@@ -1,16 +1,28 @@
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { of } from 'rxjs';
import { NgbAccordionModule, NgbNavModule } from '@ng-bootstrap/ng-bootstrap';
import {
ComponentFixture,
TestBed,
waitForAsync,
} from '@angular/core/testing';
import {
NgbAccordionModule,
NgbNavModule,
} from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';
import { of } from 'rxjs';
import { BulkAccessBrowseComponent } from './bulk-access-browse.component';
import { buildPaginatedList } from '../../../core/data/paginated-list.model';
import { PageInfo } from '../../../core/shared/page-info.model';
import { getMockThemeService } from '../../../shared/mocks/theme-service.mock';
import { ListableObjectComponentLoaderComponent } from '../../../shared/object-collection/shared/listable-object/listable-object-component-loader.component';
import { SelectableListItemControlComponent } from '../../../shared/object-collection/shared/selectable-list-item-control/selectable-list-item-control.component';
import { SelectableListService } from '../../../shared/object-list/selectable-list/selectable-list.service';
import { SelectableObject } from '../../../shared/object-list/selectable-list/selectable-list.service.spec';
import { PageInfo } from '../../../core/shared/page-info.model';
import { buildPaginatedList } from '../../../core/data/paginated-list.model';
import { PaginationComponent } from '../../../shared/pagination/pagination.component';
import { createSuccessfulRemoteDataObject } from '../../../shared/remote-data.utils';
import { ThemedSearchComponent } from '../../../shared/search/themed-search.component';
import { ThemeService } from '../../../shared/theme-support/theme.service';
import { BulkAccessBrowseComponent } from './bulk-access-browse.component';
describe('BulkAccessBrowseComponent', () => {
let component: BulkAccessBrowseComponent;
@@ -23,7 +35,7 @@ describe('BulkAccessBrowseComponent', () => {
const selected1 = new SelectableObject(value1);
const selected2 = new SelectableObject(value2);
const testSelection = { id: listID1, selection: [selected1, selected2] } ;
const testSelection = { id: listID1, selection: [selected1, selected2] };
const selectableListService = jasmine.createSpyObj('SelectableListService', ['getSelectableList', 'deselectAll']);
beforeEach(waitForAsync(() => {
@@ -31,14 +43,28 @@ describe('BulkAccessBrowseComponent', () => {
imports: [
NgbAccordionModule,
NgbNavModule,
TranslateModule.forRoot()
TranslateModule.forRoot(),
BulkAccessBrowseComponent,
],
providers: [
{ provide: SelectableListService, useValue: selectableListService },
{ provide: ThemeService, useValue: getMockThemeService() },
],
declarations: [BulkAccessBrowseComponent],
providers: [ { provide: SelectableListService, useValue: selectableListService }, ],
schemas: [
NO_ERRORS_SCHEMA
]
}).compileComponents();
NO_ERRORS_SCHEMA,
],
})
.overrideComponent(BulkAccessBrowseComponent, {
remove: {
imports: [
PaginationComponent,
ThemedSearchComponent,
SelectableListItemControlComponent,
ListableObjectComponentLoaderComponent,
],
},
})
.compileComponents();
}));
beforeEach(() => {
@@ -72,8 +98,8 @@ describe('BulkAccessBrowseComponent', () => {
'elementsPerPage': 5,
'totalElements': 2,
'totalPages': 1,
'currentPage': 1
}), [selected1, selected2]) ;
'currentPage': 1,
}), [selected1, selected2]);
const rd = createSuccessfulRemoteDataObject(list);
expect(component.objectsSelected$.value).toEqual(rd);

View File

@@ -1,19 +1,48 @@
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import {
AsyncPipe,
NgForOf,
NgIf,
} from '@angular/common';
import {
Component,
Input,
OnDestroy,
OnInit,
} from '@angular/core';
import {
NgbAccordionModule,
NgbNavModule,
} from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';
import { NgxPaginationModule } from 'ngx-pagination';
import {
BehaviorSubject,
Subscription,
} from 'rxjs';
import {
distinctUntilChanged,
map,
} from 'rxjs/operators';
import { BehaviorSubject, Subscription } from 'rxjs';
import { distinctUntilChanged, map } from 'rxjs/operators';
import { SEARCH_CONFIG_SERVICE } from '../../../my-dspace-page/my-dspace-page.component';
import { SearchConfigurationService } from '../../../core/shared/search/search-configuration.service';
import { SelectableListService } from '../../../shared/object-list/selectable-list/selectable-list.service';
import { SelectableListState } from '../../../shared/object-list/selectable-list/selectable-list.reducer';
import {
buildPaginatedList,
PaginatedList,
} from '../../../core/data/paginated-list.model';
import { RemoteData } from '../../../core/data/remote-data';
import { buildPaginatedList, PaginatedList } from '../../../core/data/paginated-list.model';
import { ListableObject } from '../../../shared/object-collection/shared/listable-object.model';
import { createSuccessfulRemoteDataObject } from '../../../shared/remote-data.utils';
import { PageInfo } from '../../../core/shared/page-info.model';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { SearchConfigurationService } from '../../../core/shared/search/search-configuration.service';
import { SEARCH_CONFIG_SERVICE } from '../../../my-dspace-page/my-dspace-configuration.service';
import { hasValue } from '../../../shared/empty.util';
import { ListableObject } from '../../../shared/object-collection/shared/listable-object.model';
import { ListableObjectComponentLoaderComponent } from '../../../shared/object-collection/shared/listable-object/listable-object-component-loader.component';
import { SelectableListItemControlComponent } from '../../../shared/object-collection/shared/selectable-list-item-control/selectable-list-item-control.component';
import { SelectableListState } from '../../../shared/object-list/selectable-list/selectable-list.reducer';
import { SelectableListService } from '../../../shared/object-list/selectable-list/selectable-list.service';
import { PaginationComponent } from '../../../shared/pagination/pagination.component';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { createSuccessfulRemoteDataObject } from '../../../shared/remote-data.utils';
import { ThemedSearchComponent } from '../../../shared/search/themed-search.component';
import { BrowserOnlyPipe } from '../../../shared/utils/browser-only.pipe';
@Component({
selector: 'ds-bulk-access-browse',
@@ -22,9 +51,24 @@ import { hasValue } from '../../../shared/empty.util';
providers: [
{
provide: SEARCH_CONFIG_SERVICE,
useClass: SearchConfigurationService
}
]
useClass: SearchConfigurationService,
},
],
imports: [
PaginationComponent,
AsyncPipe,
NgbAccordionModule,
TranslateModule,
NgIf,
NgbNavModule,
ThemedSearchComponent,
BrowserOnlyPipe,
NgForOf,
NgxPaginationModule,
SelectableListItemControlComponent,
ListableObjectComponentLoaderComponent,
],
standalone: true,
})
export class BulkAccessBrowseComponent implements OnInit, OnDestroy {
@@ -49,7 +93,7 @@ export class BulkAccessBrowseComponent implements OnInit, OnDestroy {
paginationOptions$: BehaviorSubject<PaginationComponentOptions> = new BehaviorSubject<PaginationComponentOptions>(Object.assign(new PaginationComponentOptions(), {
id: 'bas',
pageSize: 5,
currentPage: 1
currentPage: 1,
}));
/**
@@ -67,20 +111,20 @@ export class BulkAccessBrowseComponent implements OnInit, OnDestroy {
this.subs.push(
this.selectableListService.getSelectableList(this.listId).pipe(
distinctUntilChanged(),
map((list: SelectableListState) => this.generatePaginatedListBySelectedElements(list))
).subscribe(this.objectsSelected$)
map((list: SelectableListState) => this.generatePaginatedListBySelectedElements(list)),
).subscribe(this.objectsSelected$),
);
}
pageNext() {
this.paginationOptions$.next(Object.assign(new PaginationComponentOptions(), this.paginationOptions$.value, {
currentPage: this.paginationOptions$.value.currentPage + 1
currentPage: this.paginationOptions$.value.currentPage + 1,
}));
}
pagePrev() {
this.paginationOptions$.next(Object.assign(new PaginationComponentOptions(), this.paginationOptions$.value, {
currentPage: this.paginationOptions$.value.currentPage - 1
currentPage: this.paginationOptions$.value.currentPage - 1,
}));
}
@@ -99,12 +143,12 @@ export class BulkAccessBrowseComponent implements OnInit, OnDestroy {
elementsPerPage: this.paginationOptions$.value.pageSize,
totalElements: list?.selection.length,
totalPages: this.calculatePageCount(this.paginationOptions$.value.pageSize, list?.selection.length),
currentPage: this.paginationOptions$.value.currentPage
currentPage: this.paginationOptions$.value.currentPage,
});
if (pageInfo.currentPage > pageInfo.totalPages) {
pageInfo.currentPage = pageInfo.totalPages;
this.paginationOptions$.next(Object.assign(new PaginationComponentOptions(), this.paginationOptions$.value, {
currentPage: pageInfo.currentPage
currentPage: pageInfo.currentPage,
}));
}
return createSuccessfulRemoteDataObject(buildPaginatedList(pageInfo, list?.selection || []));

View File

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

View File

@@ -1,18 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
ComponentFixture,
TestBed,
} from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { TranslateModule } from '@ngx-translate/core';
import { of } from 'rxjs';
import { BulkAccessComponent } from './bulk-access.component';
import { BulkAccessControlService } from '../../shared/access-control-form-container/bulk-access-control.service';
import { SelectableListService } from '../../shared/object-list/selectable-list/selectable-list.service';
import { SelectableListState } from '../../shared/object-list/selectable-list/selectable-list.reducer';
import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
import { Process } from '../../process-page/processes/process.model';
import { RouterTestingModule } from '@angular/router/testing';
import { BulkAccessControlService } from '../../shared/access-control-form-container/bulk-access-control.service';
import { getMockThemeService } from '../../shared/mocks/theme-service.mock';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { SelectableListState } from '../../shared/object-list/selectable-list/selectable-list.reducer';
import { SelectableListService } from '../../shared/object-list/selectable-list/selectable-list.service';
import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
import { NotificationsServiceStub } from '../../shared/testing/notifications-service.stub';
import { ThemeService } from '../../shared/theme-support/theme.service';
import { BulkAccessComponent } from './bulk-access.component';
import { BulkAccessSettingsComponent } from './settings/bulk-access-settings.component';
describe('BulkAccessComponent', () => {
let component: BulkAccessComponent;
@@ -31,35 +36,35 @@ describe('BulkAccessComponent', () => {
'startDate': {
'year': 2026,
'month': 5,
'day': 31
'day': 31,
},
'endDate': null
}
'endDate': null,
},
],
'state': {
'item': {
'toggleStatus': true,
'accessMode': 'replace'
'accessMode': 'replace',
},
'bitstream': {
'toggleStatus': false,
'accessMode': '',
'changesLimit': '',
'selectedBitstreams': []
}
}
'selectedBitstreams': [],
},
},
};
const mockFile = {
'uuids': [
'1234', '5678'
'1234', '5678',
],
'file': { }
'file': { },
};
const mockSettings: any = jasmine.createSpyObj('AccessControlFormContainerComponent', {
getValue: jasmine.createSpy('getValue'),
reset: jasmine.createSpy('reset')
reset: jasmine.createSpy('reset'),
});
const selection: any[] = [{ indexableObject: { uuid: '1234' } }, { indexableObject: { uuid: '5678' } }];
const selectableListState: SelectableListState = { id: 'test', selection };
@@ -71,16 +76,24 @@ describe('BulkAccessComponent', () => {
await TestBed.configureTestingModule({
imports: [
RouterTestingModule,
TranslateModule.forRoot()
TranslateModule.forRoot(),
BulkAccessComponent,
],
declarations: [ BulkAccessComponent ],
providers: [
{ provide: BulkAccessControlService, useValue: bulkAccessControlServiceMock },
{ provide: NotificationsService, useValue: NotificationsServiceStub },
{ provide: SelectableListService, useValue: selectableListServiceMock }
{ provide: SelectableListService, useValue: selectableListServiceMock },
{ provide: ThemeService, useValue: getMockThemeService() },
],
schemas: [NO_ERRORS_SCHEMA]
schemas: [NO_ERRORS_SCHEMA],
})
.overrideComponent(BulkAccessComponent, {
remove: {
imports: [
BulkAccessSettingsComponent,
],
},
})
.compileComponents();
});

View File

@@ -1,17 +1,34 @@
import { Component, OnInit, ViewChild } from '@angular/core';
import {
Component,
OnInit,
ViewChild,
} from '@angular/core';
import { TranslateModule } from '@ngx-translate/core';
import {
BehaviorSubject,
Subscription,
} from 'rxjs';
import {
distinctUntilChanged,
map,
} from 'rxjs/operators';
import { BehaviorSubject, Subscription } from 'rxjs';
import { distinctUntilChanged, map } from 'rxjs/operators';
import { BulkAccessSettingsComponent } from './settings/bulk-access-settings.component';
import { BulkAccessControlService } from '../../shared/access-control-form-container/bulk-access-control.service';
import { SelectableListState } from '../../shared/object-list/selectable-list/selectable-list.reducer';
import { SelectableListService } from '../../shared/object-list/selectable-list/selectable-list.service';
import { BulkAccessBrowseComponent } from './browse/bulk-access-browse.component';
import { BulkAccessSettingsComponent } from './settings/bulk-access-settings.component';
@Component({
selector: 'ds-bulk-access',
templateUrl: './bulk-access.component.html',
styleUrls: ['./bulk-access.component.scss']
styleUrls: ['./bulk-access.component.scss'],
imports: [
TranslateModule,
BulkAccessSettingsComponent,
BulkAccessBrowseComponent,
],
standalone: true,
})
export class BulkAccessComponent implements OnInit {
@@ -37,7 +54,7 @@ export class BulkAccessComponent implements OnInit {
constructor(
private bulkAccessControlService: BulkAccessControlService,
private selectableListService: SelectableListService
private selectableListService: SelectableListService,
) {
}
@@ -45,8 +62,8 @@ export class BulkAccessComponent implements OnInit {
this.subs.push(
this.selectableListService.getSelectableList(this.listId).pipe(
distinctUntilChanged(),
map((list: SelectableListState) => this.generateIdListBySelectedElements(list))
).subscribe(this.objectsSelected$)
map((list: SelectableListState) => this.generateIdListBySelectedElements(list)),
).subscribe(this.objectsSelected$),
);
}
@@ -74,12 +91,12 @@ export class BulkAccessComponent implements OnInit {
const { file } = this.bulkAccessControlService.createPayloadFile({
bitstreamAccess,
itemAccess,
state: settings.state
state: settings.state,
});
this.bulkAccessControlService.executeScript(
this.objectsSelected$.value || [],
file
file,
).subscribe();
}

View File

@@ -1,13 +1,13 @@
<ngb-accordion #acc="ngbAccordion" [activeIds]="'settings'">
<ngb-panel [id]="'settings'">
<ng-template ngbPanelHeader>
<div class="w-100 d-flex justify-content-between collapse-toggle" ngbPanelToggle (click)="acc.toggle('settings')" data-test="settings">
<button type="button" class="btn btn-link p-0" (click)="$event.preventDefault()" [attr.aria-expanded]="!acc.isExpanded('browse')"
aria-controls="collapsePanels">
<div class="w-100 d-flex gap-3 justify-content-between collapse-toggle" ngbPanelToggle (click)="acc.toggle('settings')" data-test="settings">
<button type="button" class="btn btn-link p-0" (click)="$event.preventDefault()" [attr.aria-expanded]="acc.isExpanded('settings')"
aria-controls="bulk-access-settings-panel-content">
{{ 'admin.access-control.bulk-access-settings.header' | translate }}
</button>
<div class="text-right d-flex">
<div class="ml-3 d-inline-block">
<div class="text-right d-flex gap-2">
<div class="d-flex my-auto">
<span *ngIf="acc.isExpanded('settings')" class="fas fa-chevron-up fa-fw"></span>
<span *ngIf="!acc.isExpanded('settings')" class="fas fa-chevron-down fa-fw"></span>
</div>
@@ -15,7 +15,7 @@
</div>
</ng-template>
<ng-template ngbPanelContent>
<ds-access-control-form-container #dsAccessControlForm [showSubmit]="false"></ds-access-control-form-container>
<ds-access-control-form-container id="bulk-access-settings-panel-content" #dsAccessControlForm [showSubmit]="false"></ds-access-control-form-container>
</ng-template>
</ngb-panel>
</ngb-accordion>

View File

@@ -1,8 +1,13 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
ComponentFixture,
TestBed,
} from '@angular/core/testing';
import { NgbAccordionModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';
import { AccessControlFormContainerComponent } from '../../../shared/access-control-form-container/access-control-form-container.component';
import { BulkAccessSettingsComponent } from './bulk-access-settings.component';
import { NO_ERRORS_SCHEMA } from '@angular/core';
describe('BulkAccessSettingsComponent', () => {
let component: BulkAccessSettingsComponent;
@@ -15,36 +20,39 @@ describe('BulkAccessSettingsComponent', () => {
'startDate': {
'year': 2026,
'month': 5,
'day': 31
'day': 31,
},
'endDate': null
}
'endDate': null,
},
],
'state': {
'item': {
'toggleStatus': true,
'accessMode': 'replace'
'accessMode': 'replace',
},
'bitstream': {
'toggleStatus': false,
'accessMode': '',
'changesLimit': '',
'selectedBitstreams': []
}
}
'selectedBitstreams': [],
},
},
};
const mockControl: any = jasmine.createSpyObj('AccessControlFormContainerComponent', {
getFormValue: jasmine.createSpy('getFormValue'),
reset: jasmine.createSpy('reset')
reset: jasmine.createSpy('reset'),
});
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [NgbAccordionModule, TranslateModule.forRoot()],
declarations: [BulkAccessSettingsComponent],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
imports: [NgbAccordionModule, TranslateModule.forRoot(), BulkAccessSettingsComponent],
schemas: [NO_ERRORS_SCHEMA],
})
.overrideComponent(BulkAccessSettingsComponent, {
remove: { imports: [AccessControlFormContainerComponent] },
})
.compileComponents();
});
beforeEach(() => {

View File

@@ -1,13 +1,25 @@
import { Component, ViewChild } from '@angular/core';
import { NgIf } from '@angular/common';
import {
AccessControlFormContainerComponent
} from '../../../shared/access-control-form-container/access-control-form-container.component';
Component,
ViewChild,
} from '@angular/core';
import { NgbAccordionModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';
import { AccessControlFormContainerComponent } from '../../../shared/access-control-form-container/access-control-form-container.component';
@Component({
selector: 'ds-bulk-access-settings',
templateUrl: 'bulk-access-settings.component.html',
styleUrls: ['./bulk-access-settings.component.scss'],
exportAs: 'dsBulkSettings'
exportAs: 'dsBulkSettings',
imports: [
NgbAccordionModule,
TranslateModule,
NgIf,
AccessControlFormContainerComponent,
],
standalone: true,
})
export class BulkAccessSettingsComponent {

View File

@@ -1,5 +1,6 @@
/* eslint-disable max-classes-per-file */
import { Action } from '@ngrx/store';
import { EPerson } from '../../core/eperson/models/eperson.model';
import { type } from '../../shared/ngrx/type';

View File

@@ -2,98 +2,92 @@
<div class="epeople-registry row">
<div class="col-12">
<div class="d-flex justify-content-between border-bottom mb-3">
<h2 id="header" class="pb-2">{{labelPrefix + 'head' | translate}}</h2>
<h1 id="header" class="pb-2">{{labelPrefix + 'head' | translate}}</h1>
<div *ngIf="!isEPersonFormShown">
<div>
<button class="mr-auto btn btn-success addEPerson-button"
(click)="isEPersonFormShown = true">
[routerLink]="'create'">
<i class="fas fa-plus"></i>
<span class="d-none d-sm-inline ml-1">{{labelPrefix + 'button.add' | translate}}</span>
</button>
</div>
</div>
<ds-eperson-form *ngIf="isEPersonFormShown" (submitForm)="reset()"
(cancelForm)="isEPersonFormShown = false"></ds-eperson-form>
<div *ngIf="!isEPersonFormShown">
<h3 id="search" class="border-bottom pb-2">{{labelPrefix + 'search.head' | translate}}
</h3>
<form [formGroup]="searchForm" (ngSubmit)="search(searchForm.value)" class="d-flex justify-content-between">
<div>
<select name="scope" id="scope" formControlName="scope" class="form-control" aria-label="Search scope">
<option value="metadata">{{labelPrefix + 'search.scope.metadata' | translate}}</option>
<option value="email">{{labelPrefix + 'search.scope.email' | translate}}</option>
</select>
</div>
<div class="flex-grow-1 mr-3 ml-3">
<div class="form-group input-group">
<input type="text" name="query" id="query" formControlName="query"
class="form-control" [attr.aria-label]="labelPrefix + 'search.placeholder' | translate"
[placeholder]="(labelPrefix + 'search.placeholder' | translate)">
<span class="input-group-append">
<h2 id="search" class="border-bottom pb-2">
{{labelPrefix + 'search.head' | translate}}
</h2>
<form [formGroup]="searchForm" (ngSubmit)="search(searchForm.value)" class="d-flex justify-content-between">
<div>
<select name="scope" id="scope" formControlName="scope" class="form-control" aria-label="Search scope">
<option value="metadata">{{labelPrefix + 'search.scope.metadata' | translate}}</option>
<option value="email">{{labelPrefix + 'search.scope.email' | translate}}</option>
</select>
</div>
<div class="flex-grow-1 mr-3 ml-3">
<div class="form-group input-group">
<input type="text" name="query" id="query" formControlName="query"
class="form-control" [attr.aria-label]="labelPrefix + 'search.placeholder' | translate"
[placeholder]="(labelPrefix + 'search.placeholder' | translate)">
<span class="input-group-append">
<button type="submit" class="search-button btn btn-primary">
<i class="fas fa-search"></i> {{ labelPrefix + 'search.button' | translate }}
</button>
</span>
</div>
</div>
<div>
<button (click)="clearFormAndResetResult();"
class="search-button btn btn-secondary">{{labelPrefix + 'button.see-all' | translate}}</button>
</div>
</form>
<ds-themed-loading *ngIf="searching$ | async"></ds-themed-loading>
<ds-pagination
*ngIf="(pageInfoState$ | async)?.totalElements > 0 && !(searching$ | async)"
[paginationOptions]="config"
[pageInfoState]="pageInfoState$"
[collectionSize]="(pageInfoState$ | async)?.totalElements"
[hideGear]="true"
[hidePagerWhenSinglePage]="true">
<div class="table-responsive">
<table id="epeople" class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th scope="col">{{labelPrefix + 'table.id' | translate}}</th>
<th scope="col">{{labelPrefix + 'table.name' | translate}}</th>
<th scope="col">{{labelPrefix + 'table.email' | translate}}</th>
<th>{{labelPrefix + 'table.edit' | translate}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let epersonDto of (ePeopleDto$ | async)?.page"
[ngClass]="{'table-primary' : isActive(epersonDto.eperson) | async}">
<td>{{epersonDto.eperson.id}}</td>
<td>{{ dsoNameService.getName(epersonDto.eperson) }}</td>
<td>{{epersonDto.eperson.email}}</td>
<td>
<div class="btn-group edit-field">
<button (click)="toggleEditEPerson(epersonDto.eperson)"
class="btn btn-outline-primary btn-sm access-control-editEPersonButton"
title="{{labelPrefix + 'table.edit.buttons.edit' | translate: { name: dsoNameService.getName(epersonDto.eperson) } }}">
<i class="fas fa-edit fa-fw"></i>
</button>
<button [disabled]="!epersonDto.ableToDelete" (click)="deleteEPerson(epersonDto.eperson)"
class="delete-button btn btn-outline-danger btn-sm access-control-deleteEPersonButton"
title="{{labelPrefix + 'table.edit.buttons.remove' | translate: { name: dsoNameService.getName(epersonDto.eperson) } }}">
<i class="fas fa-trash-alt fa-fw"></i>
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</ds-pagination>
<div *ngIf="(pageInfoState$ | async)?.totalElements == 0" class="alert alert-info w-100 mb-2" role="alert">
{{labelPrefix + 'no-items' | translate}}
</div>
<div>
<button (click)="clearFormAndResetResult();"
class="search-button btn btn-secondary">{{labelPrefix + 'button.see-all' | translate}}</button>
</div>
</form>
<ds-themed-loading *ngIf="searching$ | async"></ds-themed-loading>
<ds-pagination
*ngIf="(pageInfoState$ | async)?.totalElements > 0 && (searching$ | async) !== true"
[paginationOptions]="config"
[collectionSize]="(pageInfoState$ | async)?.totalElements"
[hideGear]="true"
[hidePagerWhenSinglePage]="true">
<div class="table-responsive">
<table id="epeople" class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th scope="col">{{labelPrefix + 'table.id' | translate}}</th>
<th scope="col">{{labelPrefix + 'table.name' | translate}}</th>
<th scope="col">{{labelPrefix + 'table.email' | translate}}</th>
<th>{{labelPrefix + 'table.edit' | translate}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let epersonDto of (ePeopleDto$ | async)?.page"
[ngClass]="{'table-primary' : isActive(epersonDto.eperson) | async}">
<td>{{epersonDto.eperson.id}}</td>
<td>{{ dsoNameService.getName(epersonDto.eperson) }}</td>
<td>{{epersonDto.eperson.email}}</td>
<td>
<div class="btn-group edit-field">
<button [routerLink]="getEditEPeoplePage(epersonDto.eperson.id)"
class="btn btn-outline-primary btn-sm access-control-editEPersonButton"
title="{{labelPrefix + 'table.edit.buttons.edit' | translate: { name: dsoNameService.getName(epersonDto.eperson) } }}">
<i class="fas fa-edit fa-fw"></i>
</button>
<button *ngIf="epersonDto.ableToDelete" (click)="deleteEPerson(epersonDto.eperson)"
class="delete-button btn btn-outline-danger btn-sm access-control-deleteEPersonButton"
title="{{labelPrefix + 'table.edit.buttons.remove' | translate: { name: dsoNameService.getName(epersonDto.eperson) } }}">
<i class="fas fa-trash-alt fa-fw"></i>
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</ds-pagination>
<div *ngIf="(pageInfoState$ | async)?.totalElements === 0" class="alert alert-info w-100 mb-2" role="alert">
{{labelPrefix + 'no-items' | translate}}
</div>
</div>
</div>

View File

@@ -1,47 +1,75 @@
import { Router } from '@angular/router';
import { Observable, of as observableOf } from 'rxjs';
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 { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core';
import { buildPaginatedList, PaginatedList } from '../../core/data/paginated-list.model';
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 { RouterTestingModule } from '@angular/router/testing';
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 { RemoteData } from '../../core/data/remote-data';
import { RequestService } from '../../core/data/request.service';
import { EPersonDataService } from '../../core/eperson/eperson-data.service';
import { EPerson } from '../../core/eperson/models/eperson.model';
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 { NotificationsService } from '../../shared/notifications/notifications.service';
import { EPeopleRegistryComponent } from './epeople-registry.component';
import { EPersonMock, EPersonMock2 } from '../../shared/testing/eperson.mock';
import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
import { ThemedLoadingComponent } from '../../shared/loading/themed-loading.component';
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 { RouterMock } from '../../shared/mocks/router.mock';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { PaginationComponent } from '../../shared/pagination/pagination.component';
import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
import {
EPersonMock,
EPersonMock2,
} from '../../shared/testing/eperson.mock';
import { NotificationsServiceStub } from '../../shared/testing/notifications-service.stub';
import { RouterStub } from '../../shared/testing/router.stub';
import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service';
import { RequestService } from '../../core/data/request.service';
import { PaginationService } from '../../core/pagination/pagination.service';
import { PaginationServiceStub } from '../../shared/testing/pagination-service.stub';
import { FindListOptions } from '../../core/data/find-list-options.model';
import { EPeopleRegistryComponent } from './epeople-registry.component';
import { EPersonFormComponent } from './eperson-form/eperson-form.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 = {
@@ -52,7 +80,7 @@ describe('EPeopleRegistryComponent', () => {
elementsPerPage: this.allEpeople.length,
totalElements: this.allEpeople.length,
totalPages: 1,
currentPage: 1
currentPage: 1,
}), this.allEpeople));
},
getActiveEPerson(): Observable<EPerson> {
@@ -67,7 +95,7 @@ describe('EPeopleRegistryComponent', () => {
elementsPerPage: [result].length,
totalElements: [result].length,
totalPages: 1,
currentPage: 1
currentPage: 1,
}), [result]));
}
if (scope === 'metadata') {
@@ -76,7 +104,7 @@ describe('EPeopleRegistryComponent', () => {
elementsPerPage: this.allEpeople.length,
totalElements: this.allEpeople.length,
totalPages: 1,
currentPage: 1
currentPage: 1,
}), this.allEpeople));
}
const result = this.allEpeople.find((ePerson: EPerson) => {
@@ -86,20 +114,20 @@ describe('EPeopleRegistryComponent', () => {
elementsPerPage: [result].length,
totalElements: [result].length,
totalPages: 1,
currentPage: 1
currentPage: 1,
}), [result]));
}
return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo({
elementsPerPage: this.allEpeople.length,
totalElements: this.allEpeople.length,
totalPages: 1,
currentPage: 1
currentPage: 1,
}), this.allEpeople));
},
deleteEPerson(ePerson: EPerson): Observable<boolean> {
this.allEpeople = this.allEpeople.filter((ePerson2: EPerson) => {
return (ePerson2.uuid !== ePerson.uuid);
});
});
return observableOf(true);
},
editEPerson(ePerson: EPerson) {
@@ -113,42 +141,44 @@ describe('EPeopleRegistryComponent', () => {
},
getEPeoplePageRouterLink(): string {
return '/access-control/epeople';
}
},
};
authorizationService = jasmine.createSpyObj('authorizationService', {
isAuthorized: observableOf(true)
isAuthorized: observableOf(true),
});
builderService = getMockFormBuilderService();
translateService = getMockTranslateService();
paginationService = new PaginationServiceStub();
TestBed.configureTestingModule({
imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}),
],
declarations: [EPeopleRegistryComponent],
imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule, RouterTestingModule.withRoutes([]),
TranslateModule.forRoot(), EPeopleRegistryComponent],
providers: [
{ provide: EPersonDataService, useValue: ePersonDataServiceStub },
{ provide: NotificationsService, useValue: new NotificationsServiceStub() },
{ provide: AuthorizationDataService, useValue: authorizationService },
{ provide: FormBuilderService, useValue: builderService },
{ provide: Router, useValue: new RouterStub() },
{ provide: Router, useValue: new RouterMock() },
{ provide: RequestService, useValue: jasmine.createSpyObj('requestService', ['removeByHrefSubstring']) },
{ provide: PaginationService, useValue: paginationService }
{ provide: PaginationService, useValue: paginationService },
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
schemas: [NO_ERRORS_SCHEMA],
})
.overrideComponent(EPeopleRegistryComponent, {
remove: {
imports: [
EPersonFormComponent,
ThemedLoadingComponent,
PaginationComponent,
],
},
})
.compileComponents();
}));
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();
});
@@ -158,10 +188,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();
});
@@ -169,7 +199,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();
@@ -179,14 +209,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();
@@ -196,43 +226,13 @@ 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();
});
});
});
describe('toggleEditEPerson', () => {
describe('when you click on first edit eperson button', () => {
beforeEach(fakeAsync(() => {
const editButtons = fixture.debugElement.queryAll(By.css('.access-control-editEPersonButton'));
editButtons[0].triggerEventHandler('click', {
preventDefault: () => {/**/
}
});
tick();
fixture.detectChanges();
}));
it('editEPerson form is toggled', () => {
const ePeopleIds = fixture.debugElement.queryAll(By.css('#epeople tr td:first-child'));
ePersonDataServiceStub.getActiveEPerson().subscribe((activeEPerson: EPerson) => {
if (ePeopleIds[0] && activeEPerson === ePeopleIds[0].nativeElement.textContent) {
expect(component.isEPersonFormShown).toEqual(false);
} else {
expect(component.isEPersonFormShown).toEqual(true);
}
});
});
it('EPerson search section is hidden', () => {
expect(fixture.debugElement.query(By.css('#search'))).toBeNull();
});
});
});
describe('deleteEPerson', () => {
describe('when you click on first delete eperson button', () => {
let ePeopleIdsFoundBeforeDelete;
@@ -242,7 +242,7 @@ describe('EPeopleRegistryComponent', () => {
const deleteButtons = fixture.debugElement.queryAll(By.css('.access-control-deleteEPersonButton'));
deleteButtons[0].triggerEventHandler('click', {
preventDefault: () => {/**/
}
},
});
tick();
fixture.detectChanges();
@@ -258,19 +258,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();
});
});

View File

@@ -1,31 +1,86 @@
import { Component, OnDestroy, OnInit } from '@angular/core';
import { UntypedFormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { BehaviorSubject, combineLatest, Observable, Subscription } from 'rxjs';
import { map, switchMap, take } from 'rxjs/operators';
import { buildPaginatedList, PaginatedList } from '../../core/data/paginated-list.model';
import {
AsyncPipe,
NgClass,
NgForOf,
NgIf,
} from '@angular/common';
import {
Component,
OnDestroy,
OnInit,
} from '@angular/core';
import {
ReactiveFormsModule,
UntypedFormBuilder,
} from '@angular/forms';
import {
Router,
RouterModule,
} from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
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 { RemoteData } from '../../core/data/remote-data';
import { RequestService } from '../../core/data/request.service';
import { EPersonDataService } from '../../core/eperson/eperson-data.service';
import { EPerson } from '../../core/eperson/models/eperson.model';
import { hasValue } from '../../shared/empty.util';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { EpersonDtoModel } from '../../core/eperson/models/eperson-dto.model';
import { FeatureID } from '../../core/data/feature-authorization/feature-id';
import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service';
import { getAllSucceededRemoteData, getFirstCompletedRemoteData } from '../../core/shared/operators';
import { ConfirmationModalComponent } from '../../shared/confirmation-modal/confirmation-modal.component';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { RequestService } from '../../core/data/request.service';
import { PageInfo } from '../../core/shared/page-info.model';
import { NoContent } from '../../core/shared/NoContent.model';
import { PaginationService } from '../../core/pagination/pagination.service';
import { DSONameService } from '../../core/breadcrumbs/dso-name.service';
import { NoContent } from '../../core/shared/NoContent.model';
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 { ThemedLoadingComponent } from '../../shared/loading/themed-loading.component';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { PaginationComponent } from '../../shared/pagination/pagination.component';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import {
getEPersonEditRoute,
getEPersonsRoute,
} from '../access-control-routing-paths';
import { EPersonFormComponent } from './eperson-form/eperson-form.component';
@Component({
selector: 'ds-epeople-registry',
templateUrl: './epeople-registry.component.html',
imports: [
TranslateModule,
RouterModule,
AsyncPipe,
NgIf,
EPersonFormComponent,
ReactiveFormsModule,
ThemedLoadingComponent,
PaginationComponent,
NgClass,
NgForOf,
],
standalone: true,
})
/**
* A component used for managing all existing epeople within the repository.
@@ -61,14 +116,9 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
config: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), {
id: 'elp',
pageSize: 5,
currentPage: 1
currentPage: 1,
});
/**
* Whether or not to show the EPerson form
*/
isEPersonFormShown: boolean;
// The search form
searchForm;
@@ -114,26 +164,20 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
*/
initialisePage() {
this.searching$.next(true);
this.isEPersonFormShown = false;
this.search({scope: this.currentSearchScope, query: this.currentSearchQuery});
this.subs.push(this.epersonService.getActiveEPerson().subscribe((eperson: EPerson) => {
if (eperson != null && eperson.id) {
this.isEPersonFormShown = true;
}
}));
this.search({ scope: this.currentSearchScope, query: this.currentSearchQuery });
this.subs.push(this.ePeople$.pipe(
switchMap((epeople: PaginatedList<EPerson>) => {
if (epeople.pageInfo.totalElements > 0) {
return combineLatest([...epeople.page.map((eperson: EPerson) => {
return combineLatest(epeople.page.map((eperson: EPerson) => {
return this.authorizationService.isAuthorized(FeatureID.CanDelete, hasValue(eperson) ? eperson.self : undefined).pipe(
map((authorized) => {
const epersonDtoModel: EpersonDtoModel = new EpersonDtoModel();
epersonDtoModel.ableToDelete = authorized;
epersonDtoModel.eperson = eperson;
return epersonDtoModel;
})
}),
);
})]).pipe(map((dtos: EpersonDtoModel[]) => {
})).pipe(map((dtos: EpersonDtoModel[]) => {
return buildPaginatedList(epeople.pageInfo, dtos);
}));
} else {
@@ -157,34 +201,34 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
}
this.findListOptionsSub = this.paginationService.getCurrentPagination(this.config.id, this.config).pipe(
switchMap((findListOptions) => {
const query: string = data.query;
const scope: string = data.scope;
if (query != null && this.currentSearchQuery !== query) {
this.router.navigate([this.epersonService.getEPeoplePageRouterLink()], {
queryParamsHandling: 'merge'
});
this.currentSearchQuery = query;
this.paginationService.resetPage(this.config.id);
}
if (scope != null && this.currentSearchScope !== scope) {
this.router.navigate([this.epersonService.getEPeoplePageRouterLink()], {
queryParamsHandling: 'merge'
});
this.currentSearchScope = scope;
this.paginationService.resetPage(this.config.id);
}
return this.epersonService.searchByScope(this.currentSearchScope, this.currentSearchQuery, {
currentPage: findListOptions.currentPage,
elementsPerPage: findListOptions.pageSize
const query: string = data.query;
const scope: string = data.scope;
if (query != null && this.currentSearchQuery !== query) {
void this.router.navigate([getEPersonsRoute()], {
queryParamsHandling: 'merge',
});
this.currentSearchQuery = query;
this.paginationService.resetPage(this.config.id);
}
if (scope != null && this.currentSearchScope !== scope) {
void this.router.navigate([getEPersonsRoute()], {
queryParamsHandling: 'merge',
});
this.currentSearchScope = scope;
this.paginationService.resetPage(this.config.id);
}
return this.epersonService.searchByScope(this.currentSearchScope, this.currentSearchQuery, {
currentPage: findListOptions.currentPage,
elementsPerPage: findListOptions.pageSize,
});
},
),
getAllSucceededRemoteData(),
).subscribe((peopleRD) => {
this.ePeople$.next(peopleRD.payload);
this.pageInfoState$.next(peopleRD.payload.pageInfo);
}
this.ePeople$.next(peopleRD.payload);
this.pageInfoState$.next(peopleRD.payload.pageInfo);
},
);
}
@@ -194,7 +238,7 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
*/
isActive(eperson: EPerson): Observable<boolean> {
return this.getActiveEPerson().pipe(
map((activeEPerson) => eperson === activeEPerson)
map((activeEPerson) => eperson === activeEPerson),
);
}
@@ -205,30 +249,13 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
return this.epersonService.getActiveEPerson();
}
/**
* Start editing the selected EPerson
* @param ePerson
*/
toggleEditEPerson(ePerson: EPerson) {
this.getActiveEPerson().pipe(take(1)).subscribe((activeEPerson: EPerson) => {
if (ePerson === activeEPerson) {
this.epersonService.cancelEditEPerson();
this.isEPersonFormShown = false;
} else {
this.epersonService.editEPerson(ePerson);
this.isEPersonFormShown = true;
}
});
this.scrollToTop();
}
/**
* Deletes EPerson, show notification on success/failure & updates EPeople list
*/
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';
@@ -240,9 +267,9 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
if (hasValue(ePerson.id)) {
this.epersonService.deleteEPerson(ePerson).pipe(getFirstCompletedRemoteData()).subscribe((restResponse: RemoteData<NoContent>) => {
if (restResponse.hasSucceeded) {
this.notificationsService.success(this.translateService.get(this.labelPrefix + 'notification.deleted.success', {name: this.dsoNameService.getName(ePerson)}));
this.notificationsService.success(this.translateService.get(this.labelPrefix + 'notification.deleted.success', { name: this.dsoNameService.getName(ePerson) }));
} else {
this.notificationsService.error('Error occured when trying to delete EPerson with id: ' + ePerson.id + ' with code: ' + restResponse.statusCode + ' and message: ' + restResponse.errorMessage);
this.notificationsService.error(this.translateService.get(this.labelPrefix + 'notification.deleted.success', { id: ePerson.id, statusCode: restResponse.statusCode, errorMessage: restResponse.errorMessage }));
}
});
}
@@ -264,16 +291,6 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
this.subs.filter((sub) => hasValue(sub)).forEach((sub) => sub.unsubscribe());
}
scrollToTop() {
(function smoothscroll() {
const currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
if (currentScroll > 0) {
window.requestAnimationFrame(smoothscroll);
window.scrollTo(0, currentScroll - (currentScroll / 8));
}
})();
}
/**
* Reset all input-fields to be empty and search all search
*/
@@ -281,23 +298,10 @@ export class EPeopleRegistryComponent implements OnInit, OnDestroy {
this.searchForm.patchValue({
query: '',
});
this.search({query: ''});
this.search({ query: '' });
}
/**
* This method will set everything to stale, which will cause the lists on this page to update.
*/
reset(): void {
this.epersonService.getBrowseEndpoint().pipe(
take(1),
switchMap((href: string) => {
return this.requestService.setStaleByHrefSubstring(href).pipe(
take(1),
);
})
).subscribe(()=>{
this.epersonService.cancelEditEPerson();
this.isEPersonFormShown = false;
});
getEditEPeoplePage(id: string): string {
return getEPersonEditRoute(id);
}
}

View File

@@ -1,6 +1,12 @@
import { EPeopleRegistryCancelEPersonAction, EPeopleRegistryEditEPersonAction } from './epeople-registry.actions';
import { ePeopleRegistryReducer, EPeopleRegistryState } from './epeople-registry.reducers';
import { EPersonMock } from '../../shared/testing/eperson.mock';
import {
EPeopleRegistryCancelEPersonAction,
EPeopleRegistryEditEPersonAction,
} from './epeople-registry.actions';
import {
ePeopleRegistryReducer,
EPeopleRegistryState,
} from './epeople-registry.reducers';
const initialState: EPeopleRegistryState = {
editEPerson: null,

View File

@@ -2,7 +2,7 @@ import { EPerson } from '../../core/eperson/models/eperson.model';
import {
EPeopleRegistryAction,
EPeopleRegistryActionTypes,
EPeopleRegistryEditEPersonAction
EPeopleRegistryEditEPersonAction,
} from './epeople-registry.actions';
/**
@@ -30,13 +30,13 @@ export function ePeopleRegistryReducer(state = initialState, action: EPeopleRegi
case EPeopleRegistryActionTypes.EDIT_EPERSON: {
return Object.assign({}, state, {
editEPerson: (action as EPeopleRegistryEditEPersonAction).eperson
editEPerson: (action as EPeopleRegistryEditEPersonAction).eperson,
});
}
case EPeopleRegistryActionTypes.CANCEL_EDIT_EPERSON: {
return Object.assign({}, state, {
editEPerson: null
editEPerson: null,
});
}

View File

@@ -1,89 +1,96 @@
<div *ngIf="epersonService.getActiveEPerson() | async; then editheader; else createHeader"></div>
<div class="container">
<div class="group-form row">
<div class="col-12">
<ng-template #createHeader>
<h4>{{messagePrefix + '.create' | translate}}</h4>
</ng-template>
<div *ngIf="epersonService.getActiveEPerson() | async; then editHeader; else createHeader"></div>
<ng-template #editheader>
<h4>{{messagePrefix + '.edit' | translate}}</h4>
</ng-template>
<ng-template #createHeader>
<h1 class="border-bottom pb-2">{{messagePrefix + '.create' | translate}}</h1>
</ng-template>
<ds-form [formId]="formId"
[formModel]="formModel"
[formGroup]="formGroup"
[formLayout]="formLayout"
[displayCancel]="false"
[submitLabel]="submitLabel"
(submitForm)="onSubmit()">
<div before class="btn-group">
<button (click)="onCancel()"
class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> {{messagePrefix + '.return' | translate}}</button>
</div>
<div *ngIf="displayResetPassword" between class="btn-group">
<button class="btn btn-primary" [disabled]="!(canReset$ | async)" (click)="resetPassword()">
<i class="fa fa-key"></i> {{'admin.access-control.epeople.actions.reset' | translate}}
</button>
</div>
<div between class="btn-group ml-1">
<button *ngIf="!isImpersonated" class="btn btn-primary" [ngClass]="{'d-none' : !(canImpersonate$ | async)}" (click)="impersonate()">
<i class="fa fa-user-secret"></i> {{'admin.access-control.epeople.actions.impersonate' | translate}}
</button>
<button *ngIf="isImpersonated" class="btn btn-primary" (click)="stopImpersonating()">
<i class="fa fa-user-secret"></i> {{'admin.access-control.epeople.actions.stop-impersonating' | translate}}
</button>
</div>
<button after class="btn btn-danger delete-button" [disabled]="!(canDelete$ | async)" (click)="delete()">
<i class="fas fa-trash"></i> {{'admin.access-control.epeople.actions.delete' | translate}}
</button>
</ds-form>
<ng-template #editHeader>
<h1 class="border-bottom pb-2">{{messagePrefix + '.edit' | translate}}</h1>
</ng-template>
<ds-themed-loading [showMessage]="false" *ngIf="!formGroup"></ds-themed-loading>
<ds-form [formId]="formId"
[formModel]="formModel"
[formGroup]="formGroup"
[formLayout]="formLayout"
[displayCancel]="false"
[submitLabel]="submitLabel"
(submitForm)="onSubmit()">
<div before class="btn-group">
<button (click)="onCancel()" type="button" class="btn btn-outline-secondary">
<i class="fas fa-arrow-left"></i> {{messagePrefix + '.return' | translate}}
</button>
</div>
<div *ngIf="displayResetPassword" between class="btn-group">
<button class="btn btn-primary" [disabled]="(canReset$ | async) !== true" type="button" (click)="resetPassword()">
<i class="fa fa-key"></i> {{'admin.access-control.epeople.actions.reset' | translate}}
</button>
</div>
<div *ngIf="canImpersonate$ | async" between class="btn-group">
<button *ngIf="!isImpersonated" class="btn btn-primary" type="button" (click)="impersonate()">
<i class="fa fa-user-secret"></i> {{'admin.access-control.epeople.actions.impersonate' | translate}}
</button>
<button *ngIf="isImpersonated" class="btn btn-primary" type="button" (click)="stopImpersonating()">
<i class="fa fa-user-secret"></i> {{'admin.access-control.epeople.actions.stop-impersonating' | translate}}
</button>
</div>
<button *ngIf="canDelete$ | async" after class="btn btn-danger delete-button" type="button" (click)="delete()">
<i class="fas fa-trash"></i> {{'admin.access-control.epeople.actions.delete' | translate}}
</button>
</ds-form>
<div *ngIf="epersonService.getActiveEPerson() | async">
<h5>{{messagePrefix + '.groupsEPersonIsMemberOf' | translate}}</h5>
<ds-themed-loading [showMessage]="false" *ngIf="!formGroup"></ds-themed-loading>
<ds-themed-loading [showMessage]="false" *ngIf="!(groups | async)"></ds-themed-loading>
<div *ngIf="epersonService.getActiveEPerson() | async">
<h2>{{messagePrefix + '.groupsEPersonIsMemberOf' | translate}}</h2>
<ds-pagination
*ngIf="(groups | async)?.payload?.totalElements > 0"
[paginationOptions]="config"
[pageInfoState]="(groups | async)?.payload"
[collectionSize]="(groups | async)?.payload?.totalElements"
[hideGear]="true"
[hidePagerWhenSinglePage]="true"
(pageChange)="onPageChange($event)">
<ds-themed-loading [showMessage]="false" *ngIf="groups$ | async | dsHasNoValue"></ds-themed-loading>
<div class="table-responsive">
<table id="groups" class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th scope="col" class="align-middle">{{messagePrefix + '.table.id' | translate}}</th>
<th scope="col" class="align-middle">{{messagePrefix + '.table.name' | translate}}</th>
<th scope="col" class="align-middle">{{messagePrefix + '.table.collectionOrCommunity' | translate}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let group of (groups | async)?.payload?.page">
<td class="align-middle">{{group.id}}</td>
<td class="align-middle">
<a (click)="groupsDataService.startEditingNewGroup(group)"
[routerLink]="[groupsDataService.getGroupEditPageRouterLink(group)]">
{{ dsoNameService.getName(group) }}
</a>
</td>
<td class="align-middle">{{ dsoNameService.getName(undefined) }}</td>
</tr>
</tbody>
</table>
</div>
<ds-pagination
*ngIf="(groups$ | async)?.payload?.totalElements > 0"
[paginationOptions]="config"
[collectionSize]="(groups$ | async)?.payload?.totalElements"
[hideGear]="true"
[hidePagerWhenSinglePage]="true"
(pageChange)="onPageChange($event)">
</ds-pagination>
<div class="table-responsive">
<table id="groups" class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th scope="col" class="align-middle">{{messagePrefix + '.table.id' | translate}}</th>
<th scope="col" class="align-middle">{{messagePrefix + '.table.name' | translate}}</th>
<th scope="col" class="align-middle">{{messagePrefix + '.table.collectionOrCommunity' | translate}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let group of (groups$ | async)?.payload?.page">
<td class="align-middle">{{group.id}}</td>
<td class="align-middle">
<a (click)="groupsDataService.startEditingNewGroup(group)"
[routerLink]="[groupsDataService.getGroupEditPageRouterLink(group)]">
{{ dsoNameService.getName(group) }}
</a>
</td>
<td class="align-middle">{{ dsoNameService.getName(undefined) }}</td>
</tr>
</tbody>
</table>
</div>
<div *ngIf="(groups | async)?.payload?.totalElements == 0" class="alert alert-info w-100 mb-2" role="alert">
<div>{{messagePrefix + '.memberOfNoGroups' | translate}}</div>
<div>
<button [routerLink]="[groupsDataService.getGroupRegistryRouterLink()]"
class="btn btn-primary">{{messagePrefix + '.goToGroups' | translate}}</button>
</ds-pagination>
<div *ngIf="(groups$ | async)?.payload?.totalElements === 0" class="alert alert-info w-100 mb-2" role="alert">
<div>{{messagePrefix + '.memberOfNoGroups' | translate}}</div>
<div>
<button [routerLink]="[groupsDataService.getGroupRegistryRouterLink()]"
class="btn btn-primary">{{messagePrefix + '.goToGroups' | translate}}</button>
</div>
</div>
</div>
</div>
</div>
</div>

View File

@@ -1,36 +1,73 @@
import { Observable, of as observableOf } from 'rxjs';
import { CommonModule } from '@angular/common';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { UntypedFormControl, UntypedFormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { BrowserModule, By } from '@angular/platform-browser';
import {
ComponentFixture,
TestBed,
waitForAsync,
} from '@angular/core/testing';
import {
FormsModule,
ReactiveFormsModule,
UntypedFormControl,
UntypedFormGroup,
Validators,
} from '@angular/forms';
import {
BrowserModule,
By,
} from '@angular/platform-browser';
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { buildPaginatedList, PaginatedList } from '../../../core/data/paginated-list.model';
import {
TranslateLoader,
TranslateModule,
} from '@ngx-translate/core';
import {
Observable,
of as observableOf,
} from 'rxjs';
import { AuthService } from '../../../core/auth/auth.service';
import { EpersonRegistrationService } from '../../../core/data/eperson-registration.service';
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 { RemoteData } from '../../../core/data/remote-data';
import { RequestService } from '../../../core/data/request.service';
import { EPersonDataService } from '../../../core/eperson/eperson-data.service';
import { GroupDataService } from '../../../core/eperson/group-data.service';
import { EPerson } from '../../../core/eperson/models/eperson.model';
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 { FormComponent } from '../../../shared/form/form.component';
import { ThemedLoadingComponent } from '../../../shared/loading/themed-loading.component';
import { getMockFormBuilderService } from '../../../shared/mocks/form-builder-service.mock';
import { TranslateLoaderMock } from '../../../shared/mocks/translate-loader.mock';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { PaginationComponent } from '../../../shared/pagination/pagination.component';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { ActivatedRouteStub } from '../../../shared/testing/active-router.stub';
import { AuthServiceStub } from '../../../shared/testing/auth-service.stub';
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';
import { createPaginatedList } from '../../../shared/testing/utils.test';
import { FollowLinkConfig } from '../../../shared/utils/follow-link-config.model';
import { HasNoValuePipe } from '../../../shared/utils/has-no-value.pipe';
import { EPeopleRegistryComponent } from '../epeople-registry.component';
import { EPersonFormComponent } from './eperson-form.component';
import { EPersonMock, EPersonMock2 } from '../../../shared/testing/eperson.mock';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { getMockFormBuilderService } from '../../../shared/mocks/form-builder-service.mock';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
import { TranslateLoaderMock } from '../../../shared/mocks/translate-loader.mock';
import { AuthService } from '../../../core/auth/auth.service';
import { AuthServiceStub } from '../../../shared/testing/auth-service.stub';
import { AuthorizationDataService } from '../../../core/data/feature-authorization/authorization-data.service';
import { GroupDataService } from '../../../core/eperson/group-data.service';
import { createPaginatedList } from '../../../shared/testing/utils.test';
import { RequestService } from '../../../core/data/request.service';
import { PaginationService } from '../../../core/pagination/pagination.service';
import { PaginationServiceStub } from '../../../shared/testing/pagination-service.stub';
import { FindListOptions } from '../../../core/data/find-list-options.model';
import { ValidateEmailNotTaken } from './validators/email-taken.validator';
import { EpersonRegistrationService } from '../../../core/data/eperson-registration.service';
describe('EPersonFormComponent', () => {
let component: EPersonFormComponent;
@@ -43,6 +80,8 @@ describe('EPersonFormComponent', () => {
let authorizationService: AuthorizationDataService;
let groupsDataService: GroupDataService;
let epersonRegistrationService: EpersonRegistrationService;
let route: ActivatedRouteStub;
let router: RouterStub;
let paginationService;
@@ -106,70 +145,73 @@ describe('EPersonFormComponent', () => {
},
getEPersonByEmail(email): Observable<RemoteData<EPerson>> {
return createSuccessfulRemoteDataObject$(null);
}
},
findById(_id: string, _useCachedVersionIfAvailable = true, _reRequestOnStale = true, ..._linksToFollow: FollowLinkConfig<EPerson>[]): Observable<RemoteData<EPerson>> {
return createSuccessfulRemoteDataObject$(null);
},
};
builderService = Object.assign(getMockFormBuilderService(),{
createFormGroup(formModel, options = null) {
const controls = {};
formModel.forEach( model => {
model.parent = parent;
const controlModel = model;
const controlState = { value: controlModel.value, disabled: controlModel.disabled };
const controlOptions = this.createAbstractControlOptions(controlModel.validators, controlModel.asyncValidators, controlModel.updateOn);
controls[model.id] = new UntypedFormControl(controlState, controlOptions);
model.parent = parent;
const controlModel = model;
const controlState = { value: controlModel.value, disabled: controlModel.disabled };
const controlOptions = this.createAbstractControlOptions(controlModel.validators, controlModel.asyncValidators, controlModel.updateOn);
controls[model.id] = new UntypedFormControl(controlState, controlOptions);
});
return new UntypedFormGroup(controls, options);
},
createAbstractControlOptions(validatorsConfig = null, asyncValidatorsConfig = null, updateOn = null) {
return {
validators: validatorsConfig !== null ? this.getValidators(validatorsConfig) : null,
validators: validatorsConfig !== null ? this.getValidators(validatorsConfig) : null,
};
},
getValidators(validatorsConfig) {
return this.getValidatorFns(validatorsConfig);
return this.getValidatorFns(validatorsConfig);
},
getValidatorFns(validatorsConfig, validatorsToken = this._NG_VALIDATORS) {
let validatorFns = [];
if (this.isObject(validatorsConfig)) {
validatorFns = Object.keys(validatorsConfig).map(validatorConfigKey => {
const validatorConfigValue = validatorsConfig[validatorConfigKey];
if (this.isValidatorDescriptor(validatorConfigValue)) {
const descriptor = validatorConfigValue;
return this.getValidatorFn(descriptor.name, descriptor.args, validatorsToken);
}
return this.getValidatorFn(validatorConfigKey, validatorConfigValue, validatorsToken);
});
validatorFns = Object.keys(validatorsConfig).map(validatorConfigKey => {
const validatorConfigValue = validatorsConfig[validatorConfigKey];
if (this.isValidatorDescriptor(validatorConfigValue)) {
const descriptor = validatorConfigValue;
return this.getValidatorFn(descriptor.name, descriptor.args, validatorsToken);
}
return this.getValidatorFn(validatorConfigKey, validatorConfigValue, validatorsToken);
});
}
return validatorFns;
},
getValidatorFn(validatorName, validatorArgs = null, validatorsToken = this._NG_VALIDATORS) {
let validatorFn;
if (Validators.hasOwnProperty(validatorName)) { // Built-in Angular Validators
validatorFn = Validators[validatorName];
validatorFn = Validators[validatorName];
} else { // Custom Validators
if (this._DYNAMIC_VALIDATORS && this._DYNAMIC_VALIDATORS.has(validatorName)) {
validatorFn = this._DYNAMIC_VALIDATORS.get(validatorName);
} else if (validatorsToken) {
validatorFn = validatorsToken.find(validator => validator.name === validatorName);
}
if (this._DYNAMIC_VALIDATORS && this._DYNAMIC_VALIDATORS.has(validatorName)) {
validatorFn = this._DYNAMIC_VALIDATORS.get(validatorName);
} else if (validatorsToken) {
validatorFn = validatorsToken.find(validator => validator.name === validatorName);
}
}
if (validatorFn === undefined) { // throw when no validator could be resolved
throw new Error(`validator '${validatorName}' is not provided via NG_VALIDATORS, NG_ASYNC_VALIDATORS or DYNAMIC_FORM_VALIDATORS`);
throw new Error(`validator '${validatorName}' is not provided via NG_VALIDATORS, NG_ASYNC_VALIDATORS or DYNAMIC_FORM_VALIDATORS`);
}
if (validatorArgs !== null) {
return validatorFn(validatorArgs);
return validatorFn(validatorArgs);
}
return validatorFn;
},
},
isValidatorDescriptor(value) {
if (this.isObject(value)) {
return value.hasOwnProperty('name') && value.hasOwnProperty('args');
}
return false;
if (this.isObject(value)) {
return value.hasOwnProperty('name') && value.hasOwnProperty('args');
}
return false;
},
isObject(value) {
return typeof value === 'object' && value !== null;
}
},
});
authService = new AuthServiceStub();
authorizationService = jasmine.createSpyObj('authorizationService', {
@@ -178,20 +220,23 @@ describe('EPersonFormComponent', () => {
});
groupsDataService = jasmine.createSpyObj('groupsDataService', {
findListByHref: createSuccessfulRemoteDataObject$(createPaginatedList([])),
getGroupRegistryRouterLink: ''
getGroupRegistryRouterLink: '',
});
paginationService = new PaginationServiceStub();
route = new ActivatedRouteStub();
router = new RouterStub();
TestBed.configureTestingModule({
imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
useClass: TranslateLoaderMock,
},
}),
EPersonFormComponent,
HasNoValuePipe,
],
declarations: [EPersonFormComponent],
providers: [
{ provide: EPersonDataService, useValue: ePersonDataServiceStub },
{ provide: GroupDataService, useValue: groupsDataService },
@@ -200,16 +245,22 @@ describe('EPersonFormComponent', () => {
{ provide: AuthService, useValue: authService },
{ provide: AuthorizationDataService, useValue: authorizationService },
{ provide: PaginationService, useValue: paginationService },
{ provide: RequestService, useValue: jasmine.createSpyObj('requestService', ['removeByHrefSubstring'])},
{ provide: RequestService, useValue: jasmine.createSpyObj('requestService', ['removeByHrefSubstring']) },
{ provide: EpersonRegistrationService, useValue: epersonRegistrationService },
EPeopleRegistryComponent
{ provide: ActivatedRoute, useValue: route },
{ provide: Router, useValue: router },
EPeopleRegistryComponent,
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
schemas: [NO_ERRORS_SCHEMA],
})
.overrideComponent(EPersonFormComponent, {
remove: { imports: [ ThemedLoadingComponent, PaginationComponent,FormComponent] },
})
.compileComponents();
}));
epersonRegistrationService = jasmine.createSpyObj('epersonRegistrationService', {
registerEmail: createSuccessfulRemoteDataObject$(null)
registerEmail: createSuccessfulRemoteDataObject$(null),
});
beforeEach(() => {
@@ -241,12 +292,12 @@ describe('EPersonFormComponent', () => {
metadata: {
'eperson.firstname': [
{
value: firstName
}
value: firstName,
},
],
'eperson.lastname': [
{
value: lastName
value: lastName,
},
],
},
@@ -263,24 +314,18 @@ describe('EPersonFormComponent', () => {
fixture.detectChanges();
});
describe('firstName, lastName and email should be required', () => {
it('form should be invalid because the firstName is required', waitForAsync(() => {
fixture.whenStable().then(() => {
expect(component.formGroup.controls.firstName.valid).toBeFalse();
expect(component.formGroup.controls.firstName.errors.required).toBeTrue();
});
}));
it('form should be invalid because the lastName is required', waitForAsync(() => {
fixture.whenStable().then(() => {
expect(component.formGroup.controls.lastName.valid).toBeFalse();
expect(component.formGroup.controls.lastName.errors.required).toBeTrue();
});
}));
it('form should be invalid because the email is required', waitForAsync(() => {
fixture.whenStable().then(() => {
expect(component.formGroup.controls.email.valid).toBeFalse();
expect(component.formGroup.controls.email.errors.required).toBeTrue();
});
}));
it('form should be invalid because the firstName is required', () => {
expect(component.formGroup.controls.firstName.valid).toBeFalse();
expect(component.formGroup.controls.firstName.errors.required).toBeTrue();
});
it('form should be invalid because the lastName is required', () => {
expect(component.formGroup.controls.lastName.valid).toBeFalse();
expect(component.formGroup.controls.lastName.errors.required).toBeTrue();
});
it('form should be invalid because the email is required', () => {
expect(component.formGroup.controls.email.valid).toBeFalse();
expect(component.formGroup.controls.email.errors.required).toBeTrue();
});
});
describe('after inserting information firstName,lastName and email not required', () => {
@@ -290,24 +335,18 @@ describe('EPersonFormComponent', () => {
component.formGroup.controls.email.setValue('test@test.com');
fixture.detectChanges();
});
it('firstName should be valid because the firstName is set', waitForAsync(() => {
fixture.whenStable().then(() => {
expect(component.formGroup.controls.firstName.valid).toBeTrue();
expect(component.formGroup.controls.firstName.errors).toBeNull();
});
}));
it('lastName should be valid because the lastName is set', waitForAsync(() => {
fixture.whenStable().then(() => {
expect(component.formGroup.controls.lastName.valid).toBeTrue();
expect(component.formGroup.controls.lastName.errors).toBeNull();
});
}));
it('email should be valid because the email is set', waitForAsync(() => {
fixture.whenStable().then(() => {
expect(component.formGroup.controls.email.valid).toBeTrue();
expect(component.formGroup.controls.email.errors).toBeNull();
});
}));
it('firstName should be valid because the firstName is set', () => {
expect(component.formGroup.controls.firstName.valid).toBeTrue();
expect(component.formGroup.controls.firstName.errors).toBeNull();
});
it('lastName should be valid because the lastName is set', () => {
expect(component.formGroup.controls.lastName.valid).toBeTrue();
expect(component.formGroup.controls.lastName.errors).toBeNull();
});
it('email should be valid because the email is set', () => {
expect(component.formGroup.controls.email.valid).toBeTrue();
expect(component.formGroup.controls.email.errors).toBeNull();
});
});
@@ -316,12 +355,10 @@ describe('EPersonFormComponent', () => {
component.formGroup.controls.email.setValue('test@test');
fixture.detectChanges();
});
it('email should not be valid because the email pattern', waitForAsync(() => {
fixture.whenStable().then(() => {
expect(component.formGroup.controls.email.valid).toBeFalse();
expect(component.formGroup.controls.email.errors.pattern).toBeTruthy();
});
}));
it('email should not be valid because the email pattern', () => {
expect(component.formGroup.controls.email.valid).toBeFalse();
expect(component.formGroup.controls.email.errors.pattern).toBeTruthy();
});
});
describe('after already utilized email', () => {
@@ -329,19 +366,17 @@ describe('EPersonFormComponent', () => {
const ePersonServiceWithEperson = Object.assign(ePersonDataServiceStub,{
getEPersonByEmail(): Observable<RemoteData<EPerson>> {
return createSuccessfulRemoteDataObject$(EPersonMock);
}
},
});
component.formGroup.controls.email.setValue('test@test.com');
component.formGroup.controls.email.setAsyncValidators(ValidateEmailNotTaken.createValidator(ePersonServiceWithEperson));
fixture.detectChanges();
});
it('email should not be valid because email is already taken', waitForAsync(() => {
fixture.whenStable().then(() => {
expect(component.formGroup.controls.email.valid).toBeFalse();
expect(component.formGroup.controls.email.errors.emailTaken).toBeTruthy();
});
}));
it('email should not be valid because email is already taken', () => {
expect(component.formGroup.controls.email.valid).toBeFalse();
expect(component.formGroup.controls.email.errors.emailTaken).toBeTruthy();
});
});
@@ -366,12 +401,12 @@ describe('EPersonFormComponent', () => {
metadata: {
'eperson.firstname': [
{
value: firstName
}
value: firstName,
},
],
'eperson.lastname': [
{
value: lastName
value: lastName,
},
],
},
@@ -393,11 +428,9 @@ describe('EPersonFormComponent', () => {
fixture.detectChanges();
});
it('should emit a new eperson using the correct values', waitForAsync(() => {
fixture.whenStable().then(() => {
expect(component.submitForm.emit).toHaveBeenCalledWith(expected);
});
}));
it('should emit a new eperson using the correct values', () => {
expect(component.submitForm.emit).toHaveBeenCalledWith(expected);
});
});
describe('with an active eperson', () => {
@@ -409,30 +442,28 @@ describe('EPersonFormComponent', () => {
metadata: {
'eperson.firstname': [
{
value: firstName
}
value: firstName,
},
],
'eperson.lastname': [
{
value: lastName
value: lastName,
},
],
},
email: email,
canLogIn: canLogIn,
requireCertificate: requireCertificate,
_links: undefined
_links: undefined,
});
spyOn(ePersonDataServiceStub, 'getActiveEPerson').and.returnValue(observableOf(expectedWithId));
component.onSubmit();
fixture.detectChanges();
});
it('should emit the existing eperson using the correct values', waitForAsync(() => {
fixture.whenStable().then(() => {
expect(component.submitForm.emit).toHaveBeenCalledWith(expectedWithId);
});
}));
it('should emit the existing eperson using the correct values', () => {
expect(component.submitForm.emit).toHaveBeenCalledWith(expectedWithId);
});
});
});
@@ -443,7 +474,7 @@ describe('EPersonFormComponent', () => {
spyOn(authService, 'impersonate').and.callThrough();
ePersonId = 'testEPersonId';
component.epersonInitial = Object.assign(new EPerson(), {
id: ePersonId
id: ePersonId,
});
component.impersonate();
});
@@ -491,16 +522,16 @@ describe('EPersonFormComponent', () => {
});
it('the delete button should be active if the eperson can be deleted', () => {
it('the delete button should be visible if the ePerson can be deleted', () => {
const deleteButton = fixture.debugElement.query(By.css('.delete-button'));
expect(deleteButton.nativeElement.disabled).toBe(false);
expect(deleteButton).not.toBeNull();
});
it('the delete button should be disabled if the eperson cannot be deleted', () => {
it('the delete button should be hidden if the ePerson cannot be deleted', () => {
component.canDelete$ = observableOf(false);
fixture.detectChanges();
const deleteButton = fixture.debugElement.query(By.css('.delete-button'));
expect(deleteButton.nativeElement.disabled).toBe(true);
expect(deleteButton).toBeNull();
});
it('should call the epersonFormComponent delete when clicked on the button', () => {
@@ -531,7 +562,7 @@ describe('EPersonFormComponent', () => {
ePersonEmail = 'person.email@4science.it';
component.epersonInitial = Object.assign(new EPerson(), {
id: ePersonId,
email: ePersonEmail
email: ePersonEmail,
});
component.resetPassword();
});

View File

@@ -1,47 +1,99 @@
import { ChangeDetectorRef, Component, EventEmitter, OnDestroy, OnInit, Output } from '@angular/core';
import {
AsyncPipe,
NgClass,
NgFor,
NgIf,
} from '@angular/common';
import {
ChangeDetectorRef,
Component,
EventEmitter,
OnDestroy,
OnInit,
Output,
} from '@angular/core';
import { UntypedFormGroup } from '@angular/forms';
import {
ActivatedRoute,
Router,
RouterLink,
} from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import {
DynamicCheckboxModel,
DynamicFormControlModel,
DynamicFormLayout,
DynamicInputModel
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 {
TranslateModule,
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 { AuthService } from '../../../core/auth/auth.service';
import { DSONameService } from '../../../core/breadcrumbs/dso-name.service';
import { EpersonRegistrationService } from '../../../core/data/eperson-registration.service';
import { AuthorizationDataService } from '../../../core/data/feature-authorization/authorization-data.service';
import { FeatureID } from '../../../core/data/feature-authorization/feature-id';
import { 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';
import { GroupDataService } from '../../../core/eperson/group-data.service';
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
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';
import { ConfirmationModalComponent } from '../../../shared/confirmation-modal/confirmation-modal.component';
import { hasValue } from '../../../shared/empty.util';
import { FormBuilderService } from '../../../shared/form/builder/form-builder.service';
import { FormComponent } from '../../../shared/form/form.component';
import { ThemedLoadingComponent } from '../../../shared/loading/themed-loading.component';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { PaginationComponent } from '../../../shared/pagination/pagination.component';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { AuthService } from '../../../core/auth/auth.service';
import { AuthorizationDataService } from '../../../core/data/feature-authorization/authorization-data.service';
import { FeatureID } from '../../../core/data/feature-authorization/feature-id';
import { ConfirmationModalComponent } from '../../../shared/confirmation-modal/confirmation-modal.component';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { RequestService } from '../../../core/data/request.service';
import { NoContent } from '../../../core/shared/NoContent.model';
import { PaginationService } from '../../../core/pagination/pagination.service';
import { followLink } from '../../../shared/utils/follow-link-config.model';
import { HasNoValuePipe } from '../../../shared/utils/has-no-value.pipe';
import { getEPersonsRoute } from '../../access-control-routing-paths';
import { ValidateEmailNotTaken } from './validators/email-taken.validator';
import { Registration } from '../../../core/shared/registration.model';
import { EpersonRegistrationService } from '../../../core/data/eperson-registration.service';
import { TYPE_REQUEST_FORGOT } from '../../../register-email-form/register-email-form.component';
import { DSONameService } from '../../../core/breadcrumbs/dso-name.service';
@Component({
selector: 'ds-eperson-form',
templateUrl: './eperson-form.component.html',
imports: [
FormComponent,
NgIf,
NgFor,
AsyncPipe,
TranslateModule,
NgClass,
ThemedLoadingComponent,
PaginationComponent,
RouterLink,
HasNoValuePipe,
],
standalone: true,
})
/**
* A form used for creating and editing EPeople
@@ -81,28 +133,28 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
formLayout: DynamicFormLayout = {
firstName: {
grid: {
host: 'row'
}
host: 'row',
},
},
lastName: {
grid: {
host: 'row'
}
host: 'row',
},
},
email: {
grid: {
host: 'row'
}
host: 'row',
},
},
canLogIn: {
grid: {
host: 'col col-sm-6 d-inline-block'
}
host: 'col col-sm-6 d-inline-block',
},
},
requireCertificate: {
grid: {
host: 'col col-sm-6 d-inline-block'
}
host: 'col col-sm-6 d-inline-block',
},
},
};
@@ -145,7 +197,12 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
/**
* A list of all the groups this EPerson is a member of
*/
groups: Observable<RemoteData<PaginatedList<Group>>>;
groups$: Observable<RemoteData<PaginatedList<Group>>>;
/**
* The pagination of the {@link groups$} list.
*/
groupsPageInfoState$: Observable<PageInfo>;
/**
* Pagination config used to display the list of groups
@@ -153,7 +210,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
config: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), {
id: 'gem',
pageSize: 5,
currentPage: 1
currentPage: 1,
});
/**
@@ -194,6 +251,8 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
public requestService: RequestService,
private epersonRegistrationService: EpersonRegistrationService,
public dsoNameService: DSONameService,
protected route: ActivatedRoute,
protected router: Router,
) {
this.subs.push(this.epersonService.getActiveEPerson().subscribe((eperson: EPerson) => {
this.epersonInitial = eperson;
@@ -213,7 +272,9 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
* This method will initialise the page
*/
initialisePage() {
this.subs.push(this.epersonService.findById(this.route.snapshot.params.id).subscribe((ePersonRD: RemoteData<EPerson>) => {
this.epersonService.editEPerson(ePersonRD.payload);
}));
observableCombineLatest([
this.translateService.get(`${this.messagePrefix}.firstName`),
this.translateService.get(`${this.messagePrefix}.lastName`),
@@ -251,23 +312,23 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
required: true,
errorMessages: {
emailTaken: 'error.validation.emailTaken',
pattern: 'error.validation.NotValidEmail'
pattern: 'error.validation.NotValidEmail',
},
hint: emailHint
hint: emailHint,
});
this.canLogIn = new DynamicCheckboxModel(
{
id: 'canLogIn',
label: canLogIn,
name: 'canLogIn',
value: (this.epersonInitial != null ? this.epersonInitial.canLogIn : true)
value: (this.epersonInitial != null ? this.epersonInitial.canLogIn : true),
});
this.requireCertificate = new DynamicCheckboxModel(
{
id: 'requireCertificate',
label: requireCertificate,
name: 'requireCertificate',
value: (this.epersonInitial != null ? this.epersonInitial.requireCertificate : false)
value: (this.epersonInitial != null ? this.epersonInitial.requireCertificate : false),
});
this.formModel = [
this.firstName,
@@ -279,9 +340,9 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
this.formGroup = this.formBuilderService.createFormGroup(this.formModel);
this.subs.push(this.epersonService.getActiveEPerson().subscribe((eperson: EPerson) => {
if (eperson != null) {
this.groups = this.groupsDataService.findListByHref(eperson._links.groups.href, {
this.groups$ = this.groupsDataService.findListByHref(eperson._links.groups.href, {
currentPage: 1,
elementsPerPage: this.config.pageSize
elementsPerPage: this.config.pageSize,
});
}
this.formGroup.patchValue({
@@ -289,7 +350,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
lastName: eperson != null ? eperson.firstMetadataValue('eperson.lastname') : '',
email: eperson != null ? eperson.email : '',
canLogIn: eperson != null ? eperson.canLogIn : true,
requireCertificate: eperson != null ? eperson.requireCertificate : false
requireCertificate: eperson != null ? eperson.requireCertificate : false,
});
if (eperson === null && !!this.formGroup.controls.email) {
@@ -302,11 +363,11 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
const activeEPerson$ = this.epersonService.getActiveEPerson();
this.groups = activeEPerson$.pipe(
this.groups$ = activeEPerson$.pipe(
switchMap((eperson) => {
return observableCombineLatest([observableOf(eperson), this.paginationService.getFindListOptions(this.config.id, {
currentPage: 1,
elementsPerPage: this.config.pageSize
elementsPerPage: this.config.pageSize,
})]);
}),
switchMap(([eperson, findListOptions]) => {
@@ -314,7 +375,11 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
return this.groupsDataService.findListByHref(eperson._links.groups.href, findListOptions, true, true, followLink('object'));
}
return observableOf(undefined);
})
}),
);
this.groupsPageInfoState$ = this.groups$.pipe(
map(groupsRD => groupsRD.payload.pageInfo),
);
this.canImpersonate$ = activeEPerson$.pipe(
@@ -324,10 +389,10 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
} else {
return observableOf(false);
}
})
}),
);
this.canDelete$ = activeEPerson$.pipe(
switchMap((eperson) => this.authorizationService.isAuthorized(FeatureID.CanDelete, hasValue(eperson) ? eperson.self : undefined))
switchMap((eperson) => this.authorizationService.isAuthorized(FeatureID.CanDelete, hasValue(eperson) ? eperson.self : undefined)),
);
this.canReset$ = observableOf(true);
});
@@ -339,6 +404,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
onCancel() {
this.epersonService.cancelEditEPerson();
this.cancelForm.emit();
void this.router.navigate([getEPersonsRoute()]);
}
/**
@@ -354,12 +420,12 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
metadata: {
'eperson.firstname': [
{
value: this.firstName.value
}
value: this.firstName.value,
},
],
'eperson.lastname': [
{
value: this.lastName.value
value: this.lastName.value,
},
],
},
@@ -372,7 +438,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
} else {
this.editEPerson(ePerson, values);
}
}
},
);
}
@@ -385,11 +451,13 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
const response = this.epersonService.create(ePersonToCreate);
response.pipe(
getFirstCompletedRemoteData()
getFirstCompletedRemoteData(),
).subscribe((rd: RemoteData<EPerson>) => {
if (rd.hasSucceeded) {
this.notificationsService.success(this.translateService.get(this.labelPrefix + 'notification.created.success', { name: this.dsoNameService.getName(ePersonToCreate) }));
this.submitForm.emit(ePersonToCreate);
this.epersonService.clearEPersonRequests();
void this.router.navigateByUrl(getEPersonsRoute());
} else {
this.notificationsService.error(this.translateService.get(this.labelPrefix + 'notification.created.failure', { name: this.dsoNameService.getName(ePersonToCreate) }));
this.cancelForm.emit();
@@ -409,12 +477,12 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
metadata: {
'eperson.firstname': [
{
value: (this.firstName.value ? this.firstName.value : ePerson.firstMetadataValue('eperson.firstname'))
}
value: (this.firstName.value ? this.firstName.value : ePerson.firstMetadataValue('eperson.firstname')),
},
],
'eperson.lastname': [
{
value: (this.lastName.value ? this.lastName.value : ePerson.firstMetadataValue('eperson.lastname'))
value: (this.lastName.value ? this.lastName.value : ePerson.firstMetadataValue('eperson.lastname')),
},
],
},
@@ -429,6 +497,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
if (rd.hasSucceeded) {
this.notificationsService.success(this.translateService.get(this.labelPrefix + 'notification.edited.success', { name: this.dsoNameService.getName(editedEperson) }));
this.submitForm.emit(editedEperson);
void this.router.navigateByUrl(getEPersonsRoute());
} else {
this.notificationsService.error(this.translateService.get(this.labelPrefix + 'notification.edited.failure', { name: this.dsoNameService.getName(editedEperson) }));
this.cancelForm.emit();
@@ -447,7 +516,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
onPageChange(event) {
this.updateGroups({
currentPage: event,
elementsPerPage: this.config.pageSize
elementsPerPage: this.config.pageSize,
});
}
@@ -468,7 +537,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';
@@ -483,18 +552,19 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
this.canDelete$ = observableOf(false);
return this.epersonService.deleteEPerson(eperson).pipe(
getFirstCompletedRemoteData(),
map((restResponse: RemoteData<NoContent>) => ({ restResponse, eperson }))
map((restResponse: RemoteData<NoContent>) => ({ restResponse, eperson })),
);
} else {
return observableOf(null);
}
}),
finalize(() => this.canDelete$ = observableOf(true))
finalize(() => this.canDelete$ = observableOf(true)),
);
})
}),
).subscribe(({ restResponse, eperson }: { restResponse: RemoteData<NoContent> | null, eperson: EPerson }) => {
if (restResponse?.hasSucceeded) {
this.notificationsService.success(this.translateService.get(this.labelPrefix + 'notification.deleted.success', { name: this.dsoNameService.getName(eperson) }));
void this.router.navigate([getEPersonsRoute()]);
} else {
this.notificationsService.error(`Error occurred when trying to delete EPerson with id: ${eperson?.id} with code: ${restResponse?.statusCode} and message: ${restResponse?.errorMessage}`);
}
@@ -518,14 +588,14 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
if (hasValue(this.epersonInitial.email)) {
this.epersonRegistrationService.registerEmail(this.epersonInitial.email, null, TYPE_REQUEST_FORGOT).pipe(getFirstCompletedRemoteData())
.subscribe((response: RemoteData<Registration>) => {
if (response.hasSucceeded) {
this.notificationsService.success(this.translateService.get('admin.access-control.epeople.actions.reset'),
this.translateService.get('forgot-email.form.success.content', {email: this.epersonInitial.email}));
} else {
this.notificationsService.error(this.translateService.get('forgot-email.form.error.head'),
this.translateService.get('forgot-email.form.error.content', {email: this.epersonInitial.email}));
}
if (response.hasSucceeded) {
this.notificationsService.success(this.translateService.get('admin.access-control.epeople.actions.reset'),
this.translateService.get('forgot-email.form.success.content', { email: this.epersonInitial.email }));
} else {
this.notificationsService.error(this.translateService.get('forgot-email.form.error.head'),
this.translateService.get('forgot-email.form.error.content', { email: this.epersonInitial.email }));
}
},
);
}
}
@@ -541,16 +611,6 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
}
}
/**
* This method will ensure that the page gets reset and that the cache is cleared
*/
reset() {
this.epersonService.getActiveEPerson().pipe(take(1)).subscribe((eperson: EPerson) => {
this.requestService.removeByHrefSubstring(eperson.self);
});
this.initialisePage();
}
/**
* Checks for the given ePerson if there is already an ePerson in the system with that email
* and shows notification if this is the case
@@ -561,13 +621,13 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
// Relevant message for email in use
this.subs.push(this.epersonService.searchByScope('email', ePerson.email, {
currentPage: 1,
elementsPerPage: 0
elementsPerPage: 0,
}).pipe(getFirstSucceededRemoteData(), getRemoteDataPayload())
.subscribe((list: PaginatedList<EPerson>) => {
if (list.totalElements > 0) {
this.notificationsService.error(this.translateService.get(this.labelPrefix + 'notification.' + notificationSection + '.failure.emailInUse', {
name: this.dsoNameService.getName(ePerson),
email: ePerson.email
email: ePerson.email,
}));
}
}));
@@ -578,7 +638,7 @@ export class EPersonFormComponent implements OnInit, OnDestroy {
*/
private updateGroups(options) {
this.subs.push(this.epersonService.getActiveEPerson().subscribe((eperson: EPerson) => {
this.groups = this.groupsDataService.findListByHref(eperson._links.groups.href, options);
this.groups$ = this.groupsDataService.findListByHref(eperson._links.groups.href, options);
}));
}
}

View File

@@ -1,9 +1,12 @@
import { AbstractControl, ValidationErrors } from '@angular/forms';
import {
AbstractControl,
ValidationErrors,
} from '@angular/forms';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { EPersonDataService } from '../../../../core/eperson/eperson-data.service';
import { getFirstSucceededRemoteData, } from '../../../../core/shared/operators';
import { getFirstSucceededRemoteData } from '../../../../core/shared/operators';
export class ValidateEmailNotTaken {
@@ -17,8 +20,8 @@ export class ValidateEmailNotTaken {
.pipe(
getFirstSucceededRemoteData(),
map(res => {
return !!res.payload ? { emailTaken: true } : null;
})
return res.payload ? { emailTaken: true } : null;
}),
);
};
}

View File

@@ -0,0 +1,60 @@
import { Injectable } from '@angular/core';
import {
ActivatedRouteSnapshot,
RouterStateSnapshot,
} from '@angular/router';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { RemoteData } from '../../core/data/remote-data';
import { EPersonDataService } from '../../core/eperson/eperson-data.service';
import { EPerson } from '../../core/eperson/models/eperson.model';
import { ResolvedAction } from '../../core/resolving/resolver.actions';
import { getFirstCompletedRemoteData } from '../../core/shared/operators';
import {
followLink,
FollowLinkConfig,
} from '../../shared/utils/follow-link-config.model';
export const EPERSON_EDIT_FOLLOW_LINKS: FollowLinkConfig<EPerson>[] = [
followLink('groups'),
];
/**
* This class represents a resolver that requests a specific {@link EPerson} before the route is activated
*/
@Injectable({
providedIn: 'root',
})
export class EPersonResolver {
constructor(
protected ePersonService: EPersonDataService,
protected store: Store<any>,
) {
}
/**
* Method for resolving a {@link EPerson} based on the parameters in the current route
* @param {ActivatedRouteSnapshot} route The current ActivatedRouteSnapshot
* @param {RouterStateSnapshot} state The current RouterStateSnapshot
* @returns `Observable<<RemoteData<EPerson>>` Emits the found {@link EPerson} based on the parameters in the current
* route, or an error if something went wrong
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<RemoteData<EPerson>> {
const ePersonRD$: Observable<RemoteData<EPerson>> = this.ePersonService.findById(route.params.id,
true,
false,
...EPERSON_EDIT_FOLLOW_LINKS,
).pipe(
getFirstCompletedRemoteData(),
);
ePersonRD$.subscribe((ePersonRD: RemoteData<EPerson>) => {
this.store.dispatch(new ResolvedAction(state.url, ePersonRD.payload));
});
return ePersonRD$;
}
}

View File

@@ -2,14 +2,14 @@
<div class="group-form row">
<div class="col-12">
<div *ngIf="groupDataService.getActiveGroup() | async; then editheader; else createHeader"></div>
<div *ngIf="groupDataService.getActiveGroup() | async; then editHeader; else createHeader"></div>
<ng-template #createHeader>
<h2 class="border-bottom pb-2">{{messagePrefix + '.head.create' | translate}}</h2>
<h1 class="border-bottom pb-2">{{messagePrefix + '.head.create' | translate}}</h1>
</ng-template>
<ng-template #editheader>
<h2 class="border-bottom pb-2">
<ng-template #editHeader>
<h1 class="border-bottom pb-2">
<span
*dsContextHelp="{
content: 'admin.access-control.groups.form.tooltip.editGroupPage',
@@ -20,12 +20,12 @@
>
{{messagePrefix + '.head.edit' | translate}}
</span>
</h2>
</h1>
</ng-template>
<ds-alert *ngIf="groupBeingEdited?.permanent" [type]="AlertTypeEnum.Warning"
[content]="messagePrefix + '.alert.permanent'"></ds-alert>
<ds-alert *ngIf="!(canEdit$ | async) && (groupDataService.getActiveGroup() | async)" [type]="AlertTypeEnum.Warning"
<ds-alert *ngIf="(canEdit$ | async) !== true && (groupDataService.getActiveGroup() | async)" [type]="AlertTypeEnum.Warning"
[content]="(messagePrefix + '.alert.workflowGroup' | translate:{ name: dsoNameService.getName((getLinkedDSO(groupBeingEdited) | async)?.payload), comcol: (getLinkedDSO(groupBeingEdited) | async)?.payload?.type, comcolEditRolesRoute: (getLinkedEditRolesRoute(groupBeingEdited) | async) })">
</ds-alert>
@@ -36,22 +36,21 @@
[displayCancel]="false"
(submitForm)="onSubmit()">
<div before class="btn-group">
<button (click)="onCancel()"
<button (click)="onCancel()" type="button"
class="btn btn-outline-secondary"><i class="fas fa-arrow-left"></i> {{messagePrefix + '.return' | translate}}</button>
</div>
<div after *ngIf="groupBeingEdited != null" class="btn-group">
<button class="btn btn-danger delete-button" [disabled]="!(canEdit$ | async) || groupBeingEdited.permanent"
(click)="delete()">
<div after *ngIf="(canEdit$ | async) && !groupBeingEdited?.permanent" class="btn-group">
<button (click)="delete()" class="btn btn-danger delete-button" type="button">
<i class="fa fa-trash"></i> {{ messagePrefix + '.actions.delete' | translate}}
</button>
</div>
</ds-form>
<div class="mb-5">
<ds-members-list *ngIf="groupBeingEdited != null"
<ds-members-list *ngIf="groupBeingEdited !== undefined"
[messagePrefix]="messagePrefix + '.members-list'"></ds-members-list>
</div>
<ds-subgroups-list *ngIf="groupBeingEdited != null"
<ds-subgroups-list *ngIf="groupBeingEdited !== undefined"
[messagePrefix]="messagePrefix + '.subgroups-list'"></ds-subgroups-list>

View File

@@ -1,43 +1,79 @@
import { CommonModule } from '@angular/common';
import { HttpClient } from '@angular/common/http';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { UntypedFormControl, UntypedFormGroup, FormsModule, ReactiveFormsModule, Validators } from '@angular/forms';
import { BrowserModule, By } from '@angular/platform-browser';
import { ActivatedRoute, Router } from '@angular/router';
import {
ComponentFixture,
TestBed,
waitForAsync,
} from '@angular/core/testing';
import {
FormsModule,
ReactiveFormsModule,
UntypedFormControl,
UntypedFormGroup,
Validators,
} from '@angular/forms';
import {
BrowserModule,
By,
} from '@angular/platform-browser';
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { Store } from '@ngrx/store';
import { TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core';
import { Observable, of as observableOf } from 'rxjs';
import {
TranslateLoader,
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import { Operation } from 'fast-json-patch';
import {
Observable,
of as observableOf,
} from 'rxjs';
import { DSONameService } from '../../../core/breadcrumbs/dso-name.service';
import { RemoteDataBuildService } from '../../../core/cache/builders/remote-data-build.service';
import { ObjectCacheService } from '../../../core/cache/object-cache.service';
import { DSOChangeAnalyzer } from '../../../core/data/dso-change-analyzer.service';
import { DSpaceObjectDataService } from '../../../core/data/dspace-object-data.service';
import { AuthorizationDataService } from '../../../core/data/feature-authorization/authorization-data.service';
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 { EPersonDataService } from '../../../core/eperson/eperson-data.service';
import { GroupDataService } from '../../../core/eperson/group-data.service';
import { Group } from '../../../core/eperson/models/group.model';
import { DSpaceObject } from '../../../core/shared/dspace-object.model';
import { HALEndpointService } from '../../../core/shared/hal-endpoint.service';
import { NoContent } from '../../../core/shared/NoContent.model';
import { PageInfo } from '../../../core/shared/page-info.model';
import { UUIDService } from '../../../core/shared/uuid.service';
import { XSRFService } from '../../../core/xsrf/xsrf.service';
import { AlertComponent } from '../../../shared/alert/alert.component';
import { ContextHelpDirective } from '../../../shared/context-help.directive';
import { FormBuilderService } from '../../../shared/form/builder/form-builder.service';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { GroupMock, GroupMock2 } from '../../../shared/testing/group-mock';
import { GroupFormComponent } from './group-form.component';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { getMockFormBuilderService } from '../../../shared/mocks/form-builder-service.mock';
import { getMockTranslateService } from '../../../shared/mocks/translate.service.mock';
import { TranslateLoaderMock } from '../../../shared/testing/translate-loader.mock';
import { RouterMock } from '../../../shared/mocks/router.mock';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
import { Operation } from 'fast-json-patch';
import { ValidateGroupExists } from './validators/group-exists.validator';
import { NoContent } from '../../../core/shared/NoContent.model';
import { DSONameService } from '../../../core/breadcrumbs/dso-name.service';
import { FormComponent } from '../../../shared/form/form.component';
import { DSONameServiceMock } from '../../../shared/mocks/dso-name.service.mock';
import { getMockFormBuilderService } from '../../../shared/mocks/form-builder-service.mock';
import { RouterMock } from '../../../shared/mocks/router.mock';
import { getMockTranslateService } from '../../../shared/mocks/translate.service.mock';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import {
GroupMock,
GroupMock2,
} from '../../../shared/testing/group-mock';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
import { TranslateLoaderMock } from '../../../shared/testing/translate-loader.mock';
import { GroupFormComponent } from './group-form.component';
import { MembersListComponent } from './members-list/members-list.component';
import { SubgroupsListComponent } from './subgroup-list/subgroups-list.component';
import { ValidateGroupExists } from './validators/group-exists.validator';
describe('GroupFormComponent', () => {
let component: GroupFormComponent;
@@ -65,8 +101,8 @@ describe('GroupFormComponent', () => {
metadata: {
'dc.description': [
{
value: groupDescription
}
value: groupDescription,
},
],
},
});
@@ -105,7 +141,7 @@ describe('GroupFormComponent', () => {
create(group: Group): Observable<RemoteData<Group>> {
this.allGroups = [...this.allGroups, group];
this.createdGroup = Object.assign({}, group, {
_links: { self: { href: 'group-selflink' } }
_links: { self: { href: 'group-selflink' } },
});
return createSuccessfulRemoteDataObject$(this.createdGroup);
},
@@ -114,78 +150,78 @@ describe('GroupFormComponent', () => {
},
getGroupEditPageRouterLinkWithID(id: string) {
return `group-edit-page-for-${id}`;
}
},
};
authorizationService = jasmine.createSpyObj('authorizationService', {
isAuthorized: observableOf(true)
isAuthorized: observableOf(true),
});
dsoDataServiceStub = {
findByHref(href: string): Observable<RemoteData<DSpaceObject>> {
return null;
}
},
};
builderService = Object.assign(getMockFormBuilderService(),{
createFormGroup(formModel, options = null) {
const controls = {};
formModel.forEach( model => {
model.parent = parent;
const controlModel = model;
const controlState = { value: controlModel.value, disabled: controlModel.disabled };
const controlOptions = this.createAbstractControlOptions(controlModel.validators, controlModel.asyncValidators, controlModel.updateOn);
controls[model.id] = new UntypedFormControl(controlState, controlOptions);
model.parent = parent;
const controlModel = model;
const controlState = { value: controlModel.value, disabled: controlModel.disabled };
const controlOptions = this.createAbstractControlOptions(controlModel.validators, controlModel.asyncValidators, controlModel.updateOn);
controls[model.id] = new UntypedFormControl(controlState, controlOptions);
});
return new UntypedFormGroup(controls, options);
},
createAbstractControlOptions(validatorsConfig = null, asyncValidatorsConfig = null, updateOn = null) {
return {
validators: validatorsConfig !== null ? this.getValidators(validatorsConfig) : null,
validators: validatorsConfig !== null ? this.getValidators(validatorsConfig) : null,
};
},
getValidators(validatorsConfig) {
return this.getValidatorFns(validatorsConfig);
return this.getValidatorFns(validatorsConfig);
},
getValidatorFns(validatorsConfig, validatorsToken = this._NG_VALIDATORS) {
let validatorFns = [];
if (this.isObject(validatorsConfig)) {
validatorFns = Object.keys(validatorsConfig).map(validatorConfigKey => {
const validatorConfigValue = validatorsConfig[validatorConfigKey];
if (this.isValidatorDescriptor(validatorConfigValue)) {
const descriptor = validatorConfigValue;
return this.getValidatorFn(descriptor.name, descriptor.args, validatorsToken);
}
return this.getValidatorFn(validatorConfigKey, validatorConfigValue, validatorsToken);
});
validatorFns = Object.keys(validatorsConfig).map(validatorConfigKey => {
const validatorConfigValue = validatorsConfig[validatorConfigKey];
if (this.isValidatorDescriptor(validatorConfigValue)) {
const descriptor = validatorConfigValue;
return this.getValidatorFn(descriptor.name, descriptor.args, validatorsToken);
}
return this.getValidatorFn(validatorConfigKey, validatorConfigValue, validatorsToken);
});
}
return validatorFns;
},
getValidatorFn(validatorName, validatorArgs = null, validatorsToken = this._NG_VALIDATORS) {
let validatorFn;
if (Validators.hasOwnProperty(validatorName)) { // Built-in Angular Validators
validatorFn = Validators[validatorName];
validatorFn = Validators[validatorName];
} else { // Custom Validators
if (this._DYNAMIC_VALIDATORS && this._DYNAMIC_VALIDATORS.has(validatorName)) {
validatorFn = this._DYNAMIC_VALIDATORS.get(validatorName);
} else if (validatorsToken) {
validatorFn = validatorsToken.find(validator => validator.name === validatorName);
}
if (this._DYNAMIC_VALIDATORS && this._DYNAMIC_VALIDATORS.has(validatorName)) {
validatorFn = this._DYNAMIC_VALIDATORS.get(validatorName);
} else if (validatorsToken) {
validatorFn = validatorsToken.find(validator => validator.name === validatorName);
}
}
if (validatorFn === undefined) { // throw when no validator could be resolved
throw new Error(`validator '${validatorName}' is not provided via NG_VALIDATORS, NG_ASYNC_VALIDATORS or DYNAMIC_FORM_VALIDATORS`);
throw new Error(`validator '${validatorName}' is not provided via NG_VALIDATORS, NG_ASYNC_VALIDATORS or DYNAMIC_FORM_VALIDATORS`);
}
if (validatorArgs !== null) {
return validatorFn(validatorArgs);
return validatorFn(validatorArgs);
}
return validatorFn;
},
},
isValidatorDescriptor(value) {
if (this.isObject(value)) {
return value.hasOwnProperty('name') && value.hasOwnProperty('args');
}
return false;
if (this.isObject(value)) {
return value.hasOwnProperty('name') && value.hasOwnProperty('args');
}
return false;
},
isObject(value) {
return typeof value === 'object' && value !== null;
}
},
});
translateService = getMockTranslateService();
router = new RouterMock();
@@ -195,11 +231,9 @@ describe('GroupFormComponent', () => {
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}),
],
declarations: [GroupFormComponent],
useClass: TranslateLoaderMock,
},
}), GroupFormComponent],
providers: [
{ provide: DSONameService, useValue: new DSONameServiceMock() },
{ provide: EPersonDataService, useValue: ePersonDataServiceStub },
@@ -211,18 +245,29 @@ describe('GroupFormComponent', () => {
{ provide: HttpClient, useValue: {} },
{ provide: ObjectCacheService, useValue: {} },
{ provide: UUIDService, useValue: {} },
{ provide: XSRFService, useValue: {} },
{ provide: Store, useValue: {} },
{ provide: RemoteDataBuildService, useValue: {} },
{ provide: HALEndpointService, useValue: {} },
{
provide: ActivatedRoute,
useValue: { data: observableOf({ dso: { payload: {} } }), params: observableOf({}) }
useValue: { data: observableOf({ dso: { payload: {} } }), params: observableOf({}) },
},
{ provide: Router, useValue: router },
{ provide: AuthorizationDataService, useValue: authorizationService },
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
schemas: [NO_ERRORS_SCHEMA],
})
.overrideComponent(GroupFormComponent, {
remove: { imports: [
FormComponent,
AlertComponent,
ContextHelpDirective,
MembersListComponent,
SubgroupsListComponent,
] },
})
.compileComponents();
}));
beforeEach(() => {
@@ -257,8 +302,8 @@ describe('GroupFormComponent', () => {
metadata: {
'dc.description': [
{
value: groupDescription
}
value: groupDescription,
},
],
},
});
@@ -273,11 +318,11 @@ describe('GroupFormComponent', () => {
const operations = [{
op: 'add',
path: '/metadata/dc.description',
value: 'testDescription'
value: 'testDescription',
}, {
op: 'replace',
path: '/name',
value: 'newGroupName'
value: 'newGroupName',
}];
expect(groupsDataServiceStub.patch).toHaveBeenCalledWith(expected, operations);
});
@@ -289,7 +334,7 @@ describe('GroupFormComponent', () => {
const operations = [{
op: 'add',
path: '/metadata/dc.description',
value: 'testDescription'
value: 'testDescription',
}];
expect(groupsDataServiceStub.patch).toHaveBeenCalledWith(expected, operations);
});
@@ -301,7 +346,7 @@ describe('GroupFormComponent', () => {
const operations = [{
op: 'replace',
path: '/name',
value: 'newGroupName'
value: 'newGroupName',
}];
expect(groupsDataServiceStub.patch).toHaveBeenCalledWith(expected, operations);
});
@@ -338,8 +383,8 @@ describe('GroupFormComponent', () => {
metadata: {
'dc.description': [
{
value: groupDescription
}
value: groupDescription,
},
],
},
});
@@ -376,7 +421,7 @@ describe('GroupFormComponent', () => {
const groupsDataServiceStubWithGroup = Object.assign(groupsDataServiceStub,{
searchGroups(query: string): Observable<RemoteData<PaginatedList<Group>>> {
return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), [expected]));
}
},
});
component.formGroup.controls.groupName.setValue('testName');
component.formGroup.controls.groupName.setAsyncValidators(ValidateGroupExists.createValidator(groupsDataServiceStubWithGroup));
@@ -400,7 +445,7 @@ describe('GroupFormComponent', () => {
component.canEdit$ = observableOf(true);
component.groupBeingEdited = {
permanent: false
permanent: false,
} as Group;
fixture.detectChanges();

View File

@@ -1,24 +1,52 @@
import { Component, EventEmitter, HostListener, OnDestroy, OnInit, Output, ChangeDetectorRef } from '@angular/core';
import {
AsyncPipe,
NgIf,
} from '@angular/common';
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
DynamicTextAreaModel,
} from '@ng-dynamic-forms/core';
import { TranslateService } from '@ngx-translate/core';
import {
ObservedValueOf,
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import { Operation } from 'fast-json-patch';
import {
combineLatest as observableCombineLatest,
Observable,
of as observableOf,
Subscription,
} from 'rxjs';
import { catchError, map, switchMap, take, filter, debounceTime } from 'rxjs/operators';
import {
catchError,
debounceTime,
filter,
map,
switchMap,
take,
} from 'rxjs/operators';
import { environment } from '../../../../environments/environment';
import { getCollectionEditRolesRoute } from '../../../collection-page/collection-page-routing-paths';
import { getCommunityEditRolesRoute } from '../../../community-page/community-page-routing-paths';
import { DSONameService } from '../../../core/breadcrumbs/dso-name.service';
import { DSpaceObjectDataService } from '../../../core/data/dspace-object-data.service';
import { AuthorizationDataService } from '../../../core/data/feature-authorization/authorization-data.service';
import { FeatureID } from '../../../core/data/feature-authorization/feature-id';
@@ -31,27 +59,48 @@ import { Group } from '../../../core/eperson/models/group.model';
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 {
getRemoteDataPayload,
getFirstSucceededRemoteData,
getFirstCompletedRemoteData,
getFirstSucceededRemoteDataPayload
getFirstSucceededRemoteData,
getFirstSucceededRemoteDataPayload,
getRemoteDataPayload,
} from '../../../core/shared/operators';
import { AlertType } from '../../../shared/alert/aletr-type';
import { AlertComponent } from '../../../shared/alert/alert.component';
import { AlertType } from '../../../shared/alert/alert-type';
import { ConfirmationModalComponent } from '../../../shared/confirmation-modal/confirmation-modal.component';
import { hasValue, isNotEmpty, hasValueOperator } from '../../../shared/empty.util';
import { ContextHelpDirective } from '../../../shared/context-help.directive';
import {
hasValue,
hasValueOperator,
isNotEmpty,
} from '../../../shared/empty.util';
import { FormBuilderService } from '../../../shared/form/builder/form-builder.service';
import { FormComponent } from '../../../shared/form/form.component';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { followLink } from '../../../shared/utils/follow-link-config.model';
import { NoContent } from '../../../core/shared/NoContent.model';
import { Operation } from 'fast-json-patch';
import {
getGroupEditRoute,
getGroupsRoute,
} from '../../access-control-routing-paths';
import { MembersListComponent } from './members-list/members-list.component';
import { SubgroupsListComponent } from './subgroup-list/subgroups-list.component';
import { ValidateGroupExists } from './validators/group-exists.validator';
import { DSONameService } from '../../../core/breadcrumbs/dso-name.service';
import { environment } from '../../../../environments/environment';
@Component({
selector: 'ds-group-form',
templateUrl: './group-form.component.html'
templateUrl: './group-form.component.html',
imports: [
FormComponent,
AlertComponent,
NgIf,
AsyncPipe,
TranslateModule,
ContextHelpDirective,
MembersListComponent,
SubgroupsListComponent,
],
standalone: true,
})
/**
* A form used for creating and editing groups
@@ -83,13 +132,13 @@ export class GroupFormComponent implements OnInit, OnDestroy {
formLayout: DynamicFormLayout = {
groupName: {
grid: {
host: 'row'
}
host: 'row',
},
},
groupDescription: {
grid: {
host: 'row'
}
host: 'row',
},
},
};
@@ -165,19 +214,19 @@ export class GroupFormComponent implements OnInit, OnDestroy {
this.canEdit$ = this.groupDataService.getActiveGroup().pipe(
hasValueOperator(),
switchMap((group: Group) => {
return observableCombineLatest(
return observableCombineLatest([
this.authorizationService.isAuthorized(FeatureID.CanDelete, isNotEmpty(group) ? group.self : undefined),
this.hasLinkedDSO(group),
(isAuthorized: ObservedValueOf<Observable<boolean>>, hasLinkedDSO: ObservedValueOf<Observable<boolean>>) => {
return isAuthorized && !hasLinkedDSO;
});
})
]).pipe(
map(([isAuthorized, hasLinkedDSO]: [boolean, boolean]) => isAuthorized && !hasLinkedDSO),
);
}),
);
observableCombineLatest(
observableCombineLatest([
this.translateService.get(`${this.messagePrefix}.groupName`),
this.translateService.get(`${this.messagePrefix}.groupCommunity`),
this.translateService.get(`${this.messagePrefix}.groupDescription`)
).subscribe(([groupName, groupCommunity, groupDescription]) => {
this.translateService.get(`${this.messagePrefix}.groupDescription`),
]).subscribe(([groupName, groupCommunity, groupDescription]) => {
this.groupName = new DynamicInputModel({
id: 'groupName',
label: groupName,
@@ -207,7 +256,7 @@ export class GroupFormComponent implements OnInit, OnDestroy {
];
this.formGroup = this.formBuilderService.createFormGroup(this.formModel);
if (!!this.formGroup.controls.groupName) {
if (this.formGroup.controls.groupName) {
this.formGroup.controls.groupName.setAsyncValidators(ValidateGroupExists.createValidator(this.groupDataService));
this.groupNameValueChangeSubscribe = this.groupName.valueChanges.pipe(debounceTime(300)).subscribe(() => {
this.changeDetectorRef.detectChanges();
@@ -215,12 +264,12 @@ export class GroupFormComponent implements OnInit, OnDestroy {
}
this.subs.push(
observableCombineLatest(
observableCombineLatest([
this.groupDataService.getActiveGroup(),
this.canEdit$,
this.groupDataService.getActiveGroup()
.pipe(filter((activeGroup) => hasValue(activeGroup)),switchMap((activeGroup) => this.getLinkedDSO(activeGroup).pipe(getFirstSucceededRemoteDataPayload())))
).subscribe(([activeGroup, canEdit, linkedObject]) => {
.pipe(filter((activeGroup) => hasValue(activeGroup)),switchMap((activeGroup) => this.getLinkedDSO(activeGroup).pipe(getFirstSucceededRemoteDataPayload()))),
]).subscribe(([activeGroup, canEdit, linkedObject]) => {
if (activeGroup != null) {
@@ -230,12 +279,14 @@ export class GroupFormComponent implements OnInit, OnDestroy {
this.groupBeingEdited = activeGroup;
if (linkedObject?.name) {
this.formBuilderService.insertFormGroupControl(1, this.formGroup, this.formModel, this.groupCommunity);
this.formGroup.patchValue({
groupName: activeGroup.name,
groupCommunity: linkedObject?.name ?? '',
groupDescription: activeGroup.firstMetadataValue('dc.description'),
});
if (!this.formGroup.controls.groupCommunity) {
this.formBuilderService.insertFormGroupControl(1, this.formGroup, this.formModel, this.groupCommunity);
this.formGroup.patchValue({
groupName: activeGroup.name,
groupCommunity: linkedObject?.name ?? '',
groupDescription: activeGroup.firstMetadataValue('dc.description'),
});
}
} else {
this.formModel = [
this.groupName,
@@ -252,7 +303,7 @@ export class GroupFormComponent implements OnInit, OnDestroy {
}
}, 200);
}
})
}),
);
});
}
@@ -263,7 +314,7 @@ export class GroupFormComponent implements OnInit, OnDestroy {
onCancel() {
this.groupDataService.cancelEditGroup();
this.cancelForm.emit();
this.router.navigate([this.groupDataService.getGroupRegistryRouterLink()]);
void this.router.navigate([getGroupsRoute()]);
}
/**
@@ -280,9 +331,9 @@ export class GroupFormComponent implements OnInit, OnDestroy {
metadata: {
'dc.description': [
{
value: this.groupDescription.value
}
]
value: this.groupDescription.value,
},
],
},
};
if (group === null) {
@@ -290,7 +341,7 @@ export class GroupFormComponent implements OnInit, OnDestroy {
} else {
this.editGroup(group);
}
}
},
);
}
@@ -301,7 +352,7 @@ export class GroupFormComponent implements OnInit, OnDestroy {
createNewGroup(values) {
const groupToCreate = Object.assign(new Group(), values);
this.groupDataService.create(groupToCreate).pipe(
getFirstCompletedRemoteData()
getFirstCompletedRemoteData(),
).subscribe((rd: RemoteData<Group>) => {
if (rd.hasSucceeded) {
this.notificationsService.success(this.translateService.get(this.messagePrefix + '.notification.created.success', { name: groupToCreate.name }));
@@ -310,7 +361,7 @@ export class GroupFormComponent implements OnInit, OnDestroy {
const groupSelfLink = rd.payload._links.self.href;
this.setActiveGroupWithLink(groupSelfLink);
this.groupDataService.clearGroupsRequests();
this.router.navigateByUrl(this.groupDataService.getGroupEditPageRouterLinkWithID(rd.payload.uuid));
void this.router.navigateByUrl(getGroupEditRoute(rd.payload.uuid));
}
} else {
this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.created.failure', { name: groupToCreate.name }));
@@ -330,7 +381,7 @@ export class GroupFormComponent implements OnInit, OnDestroy {
// Relevant message for group name in use
this.subs.push(this.groupDataService.searchGroups(group.name, {
currentPage: 1,
elementsPerPage: 0
elementsPerPage: 0,
}).pipe(getFirstSucceededRemoteData(), getRemoteDataPayload())
.subscribe((list: PaginatedList<Group>) => {
if (list.totalElements > 0) {
@@ -352,7 +403,7 @@ export class GroupFormComponent implements OnInit, OnDestroy {
operations = [...operations, {
op: 'add',
path: '/metadata/dc.description',
value: this.groupDescription.value
value: this.groupDescription.value,
}];
}
@@ -360,12 +411,12 @@ export class GroupFormComponent implements OnInit, OnDestroy {
operations = [...operations, {
op: 'replace',
path: '/name',
value: this.groupName.value
value: this.groupName.value,
}];
}
this.groupDataService.patch(group, operations).pipe(
getFirstCompletedRemoteData()
getFirstCompletedRemoteData(),
).subscribe((rd: RemoteData<Group>) => {
if (rd.hasSucceeded) {
this.notificationsService.success(this.translateService.get(this.messagePrefix + '.notification.edited.success', { name: this.dsoNameService.getName(rd.payload) }));
@@ -418,7 +469,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';
@@ -504,7 +555,7 @@ export class GroupFormComponent implements OnInit, OnDestroy {
return getCollectionEditRolesRoute(rd.payload.id);
}
}
})
}),
);
}
}

View File

@@ -1,110 +1,11 @@
<ng-container>
<h3 class="border-bottom pb-2">{{messagePrefix + '.head' | translate}}</h3>
<h2 class="border-bottom pb-2">{{messagePrefix + '.head' | translate}}</h2>
<h4 id="search" class="border-bottom pb-2">
<span
*dsContextHelp="{
content: 'admin.access-control.groups.form.tooltip.editGroup.addEpeople',
id: 'edit-group-add-epeople',
iconPlacement: 'right',
tooltipPlacement: ['top', 'right', 'bottom']
}"
>
{{messagePrefix + '.search.head' | translate}}
</span>
</h4>
<h3>{{messagePrefix + '.headMembers' | translate}}</h3>
<form [formGroup]="searchForm" (ngSubmit)="search(searchForm.value)" class="d-flex justify-content-between">
<div>
<select name="scope" id="scope" formControlName="scope" class="form-control" aria-label="Search scope">
<option value="metadata">{{messagePrefix + '.search.scope.metadata' | translate}}</option>
<option value="email">{{messagePrefix + '.search.scope.email' | translate}}</option>
</select>
</div>
<div class="flex-grow-1 mr-3 ml-3">
<div class="form-group input-group">
<input type="text" name="query" id="query" formControlName="query"
class="form-control" aria-label="Search input">
<span class="input-group-append">
<button type="submit" class="search-button btn btn-primary">
<i class="fas fa-search"></i> {{ messagePrefix + '.search.button' | translate }}</button>
</span>
</div>
</div>
<div>
<button (click)="clearFormAndResetResult();"
class="btn btn-secondary">{{messagePrefix + '.button.see-all' | translate}}</button>
</div>
</form>
<ds-pagination *ngIf="(ePeopleSearchDtos | async)?.totalElements > 0"
[paginationOptions]="configSearch"
[pageInfoState]="(ePeopleSearchDtos | async)"
[collectionSize]="(ePeopleSearchDtos | async)?.totalElements"
[hideGear]="true"
[hidePagerWhenSinglePage]="true">
<div class="table-responsive">
<table id="epersonsSearch" class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th scope="col" class="align-middle">{{messagePrefix + '.table.id' | translate}}</th>
<th scope="col" class="align-middle">{{messagePrefix + '.table.name' | translate}}</th>
<th scope="col" class="align-middle">{{messagePrefix + '.table.identity' | translate}}</th>
<th class="align-middle">{{messagePrefix + '.table.edit' | translate}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let ePerson of (ePeopleSearchDtos | async)?.page">
<td class="align-middle">{{ePerson.eperson.id}}</td>
<td class="align-middle">
<a (click)="ePersonDataService.startEditingNewEPerson(ePerson.eperson)"
[routerLink]="[ePersonDataService.getEPeoplePageRouterLink()]">
{{ dsoNameService.getName(ePerson.eperson) }}
</a>
</td>
<td class="align-middle">
{{messagePrefix + '.table.email' | translate}}: {{ ePerson.eperson.email ? ePerson.eperson.email : '-' }}<br/>
{{messagePrefix + '.table.netid' | translate}}: {{ ePerson.eperson.netid ? ePerson.eperson.netid : '-' }}
</td>
<td class="align-middle">
<div class="btn-group edit-field">
<button *ngIf="ePerson.memberOfGroup"
(click)="deleteMemberFromGroup(ePerson)"
[disabled]="actionConfig.remove.disabled"
[ngClass]="['btn btn-sm', actionConfig.remove.css]"
title="{{messagePrefix + '.table.edit.buttons.remove' | translate: { name: dsoNameService.getName(ePerson.eperson) } }}">
<i [ngClass]="actionConfig.remove.icon"></i>
</button>
<button *ngIf="!ePerson.memberOfGroup"
(click)="addMemberToGroup(ePerson)"
[disabled]="actionConfig.add.disabled"
[ngClass]="['btn btn-sm', actionConfig.add.css]"
title="{{messagePrefix + '.table.edit.buttons.add' | translate: { name: dsoNameService.getName(ePerson.eperson) } }}">
<i [ngClass]="actionConfig.add.icon"></i>
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</ds-pagination>
<div *ngIf="(ePeopleSearchDtos | async)?.totalElements == 0 && searchDone"
class="alert alert-info w-100 mb-2"
role="alert">
{{messagePrefix + '.no-items' | translate}}
</div>
<h4>{{messagePrefix + '.headMembers' | translate}}</h4>
<ds-pagination *ngIf="(ePeopleMembersOfGroupDtos | async)?.totalElements > 0"
<ds-pagination *ngIf="(ePeopleMembersOfGroup | async)?.totalElements > 0"
[paginationOptions]="config"
[pageInfoState]="(ePeopleMembersOfGroupDtos | async)"
[collectionSize]="(ePeopleMembersOfGroupDtos | async)?.totalElements"
[collectionSize]="(ePeopleMembersOfGroup | async)?.totalElements"
[hideGear]="true"
[hidePagerWhenSinglePage]="true">
@@ -119,32 +20,103 @@
</tr>
</thead>
<tbody>
<tr *ngFor="let ePerson of (ePeopleMembersOfGroupDtos | async)?.page">
<td class="align-middle">{{ePerson.eperson.id}}</td>
<tr *ngFor="let eperson of (ePeopleMembersOfGroup | async)?.page">
<td class="align-middle">{{eperson.id}}</td>
<td class="align-middle">
<a (click)="ePersonDataService.startEditingNewEPerson(ePerson.eperson)"
[routerLink]="[ePersonDataService.getEPeoplePageRouterLink()]">
{{ dsoNameService.getName(ePerson.eperson) }}
<a [routerLink]="getEPersonEditRoute(eperson.id)">
{{ dsoNameService.getName(eperson) }}
</a>
</td>
<td class="align-middle">
{{messagePrefix + '.table.email' | translate}}: {{ ePerson.eperson.email ? ePerson.eperson.email : '-' }}<br/>
{{messagePrefix + '.table.netid' | translate}}: {{ ePerson.eperson.netid ? ePerson.eperson.netid : '-' }}
{{messagePrefix + '.table.email' | translate}}: {{ eperson.email ? eperson.email : '-' }}<br/>
{{messagePrefix + '.table.netid' | translate}}: {{ eperson.netid ? eperson.netid : '-' }}
</td>
<td class="align-middle">
<div class="btn-group edit-field">
<button *ngIf="ePerson.memberOfGroup"
(click)="deleteMemberFromGroup(ePerson)"
<button (click)="deleteMemberFromGroup(eperson)"
[disabled]="actionConfig.remove.disabled"
[ngClass]="['btn btn-sm', actionConfig.remove.css]"
title="{{messagePrefix + '.table.edit.buttons.remove' | translate: { name: dsoNameService.getName(ePerson.eperson) } }}">
title="{{messagePrefix + '.table.edit.buttons.remove' | translate: { name: dsoNameService.getName(eperson) } }}">
<i [ngClass]="actionConfig.remove.icon"></i>
</button>
<button *ngIf="!ePerson.memberOfGroup"
(click)="addMemberToGroup(ePerson)"
</div>
</td>
</tr>
</tbody>
</table>
</div>
</ds-pagination>
<div *ngIf="(ePeopleMembersOfGroup | async) === undefined || (ePeopleMembersOfGroup | async)?.totalElements === 0" class="alert alert-info w-100 mb-2"
role="alert">
{{messagePrefix + '.no-members-yet' | translate}}
</div>
<h3 id="search" class="border-bottom pb-2">
<span
*dsContextHelp="{
content: 'admin.access-control.groups.form.tooltip.editGroup.addEpeople',
id: 'edit-group-add-epeople',
iconPlacement: 'right',
tooltipPlacement: ['top', 'right', 'bottom']
}"
>
{{messagePrefix + '.search.head' | translate}}
</span>
</h3>
<form [formGroup]="searchForm" (ngSubmit)="search(searchForm.value)" class="d-flex justify-content-between">
<div class="flex-grow-1 mr-3">
<div class="form-group input-group mr-3">
<input type="text" name="query" id="query" formControlName="query"
class="form-control" aria-label="Search input">
<span class="input-group-append">
<button type="submit" class="search-button btn btn-primary">
<i class="fas fa-search"></i> {{ messagePrefix + '.search.button' | translate }}</button>
</span>
</div>
</div>
<div>
<button (click)="clearFormAndResetResult();"
class="btn btn-secondary">{{messagePrefix + '.button.see-all' | translate}}</button>
</div>
</form>
<ds-pagination *ngIf="(ePeopleSearch | async)?.totalElements > 0"
[paginationOptions]="configSearch"
[collectionSize]="(ePeopleSearch | async)?.totalElements"
[hideGear]="true"
[hidePagerWhenSinglePage]="true">
<div class="table-responsive">
<table id="epersonsSearch" class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th scope="col" class="align-middle">{{messagePrefix + '.table.id' | translate}}</th>
<th scope="col" class="align-middle">{{messagePrefix + '.table.name' | translate}}</th>
<th scope="col" class="align-middle">{{messagePrefix + '.table.identity' | translate}}</th>
<th class="align-middle">{{messagePrefix + '.table.edit' | translate}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let eperson of (ePeopleSearch | async)?.page">
<td class="align-middle">{{eperson.id}}</td>
<td class="align-middle">
<a [routerLink]="getEPersonEditRoute(eperson.id)">
{{ dsoNameService.getName(eperson) }}
</a>
</td>
<td class="align-middle">
{{messagePrefix + '.table.email' | translate}}: {{ eperson.email ? eperson.email : '-' }}<br/>
{{messagePrefix + '.table.netid' | translate}}: {{ eperson.netid ? eperson.netid : '-' }}
</td>
<td class="align-middle">
<div class="btn-group edit-field">
<button (click)="addMemberToGroup(eperson)"
[disabled]="actionConfig.add.disabled"
[ngClass]="['btn btn-sm', actionConfig.add.css]"
title="{{messagePrefix + '.table.edit.buttons.add' | translate: { name: dsoNameService.getName(ePerson.eperson) } }}">
title="{{messagePrefix + '.table.edit.buttons.add' | translate: { name: dsoNameService.getName(eperson) } }}">
<i [ngClass]="actionConfig.add.icon"></i>
</button>
</div>
@@ -156,9 +128,10 @@
</ds-pagination>
<div *ngIf="(ePeopleMembersOfGroupDtos | async) == undefined || (ePeopleMembersOfGroupDtos | async)?.totalElements == 0" class="alert alert-info w-100 mb-2"
<div *ngIf="(ePeopleSearch | async)?.totalElements === 0 && searchDone"
class="alert alert-info w-100 mb-2"
role="alert">
{{messagePrefix + '.no-members-yet' | translate}}
{{messagePrefix + '.no-items' | translate}}
</div>
</ng-container>

View File

@@ -1,35 +1,74 @@
import { CommonModule } from '@angular/common';
import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, fakeAsync, flush, inject, 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 {
DebugElement,
NO_ERRORS_SCHEMA,
} from '@angular/core';
import {
ComponentFixture,
fakeAsync,
flush,
inject,
TestBed,
tick,
waitForAsync,
} from '@angular/core/testing';
import {
FormsModule,
ReactiveFormsModule,
} from '@angular/forms';
import {
BrowserModule,
By,
} from '@angular/platform-browser';
import {
ActivatedRoute,
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 {
TranslateLoader,
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import {
Observable,
of as observableOf,
} from 'rxjs';
import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service';
import { RestResponse } from '../../../../core/cache/response.models';
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 { EPersonDataService } from '../../../../core/eperson/eperson-data.service';
import { GroupDataService } from '../../../../core/eperson/group-data.service';
import { EPerson } from '../../../../core/eperson/models/eperson.model';
import { Group } from '../../../../core/eperson/models/group.model';
import { PageInfo } from '../../../../core/shared/page-info.model';
import { FormBuilderService } from '../../../../shared/form/builder/form-builder.service';
import { NotificationsService } from '../../../../shared/notifications/notifications.service';
import { GroupMock, GroupMock2 } from '../../../../shared/testing/group-mock';
import { MembersListComponent } from './members-list.component';
import { EPersonMock, EPersonMock2 } from '../../../../shared/testing/eperson.mock';
import { createSuccessfulRemoteDataObject$ } from '../../../../shared/remote-data.utils';
import { getMockTranslateService } from '../../../../shared/mocks/translate.service.mock';
import { getMockFormBuilderService } from '../../../../shared/mocks/form-builder-service.mock';
import { TranslateLoaderMock } from '../../../../shared/testing/translate-loader.mock';
import { NotificationsServiceStub } from '../../../../shared/testing/notifications-service.stub';
import { RouterMock } from '../../../../shared/mocks/router.mock';
import { PaginationService } from '../../../../core/pagination/pagination.service';
import { PaginationServiceStub } from '../../../../shared/testing/pagination-service.stub';
import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service';
import { PageInfo } from '../../../../core/shared/page-info.model';
import { ContextHelpDirective } from '../../../../shared/context-help.directive';
import { FormBuilderService } from '../../../../shared/form/builder/form-builder.service';
import { DSONameServiceMock } from '../../../../shared/mocks/dso-name.service.mock';
import { getMockFormBuilderService } from '../../../../shared/mocks/form-builder-service.mock';
import { RouterMock } from '../../../../shared/mocks/router.mock';
import { getMockTranslateService } from '../../../../shared/mocks/translate.service.mock';
import { NotificationsService } from '../../../../shared/notifications/notifications.service';
import { PaginationComponent } from '../../../../shared/pagination/pagination.component';
import { createSuccessfulRemoteDataObject$ } from '../../../../shared/remote-data.utils';
import { ActivatedRouteStub } from '../../../../shared/testing/active-router.stub';
import {
EPersonMock,
EPersonMock2,
} from '../../../../shared/testing/eperson.mock';
import { GroupMock } from '../../../../shared/testing/group-mock';
import { NotificationsServiceStub } from '../../../../shared/testing/notifications-service.stub';
import { PaginationServiceStub } from '../../../../shared/testing/pagination-service.stub';
import { TranslateLoaderMock } from '../../../../shared/testing/translate-loader.mock';
import { MembersListComponent } from './members-list.component';
// todo: optimize imports
describe('MembersListComponent', () => {
let component: MembersListComponent;
@@ -39,28 +78,26 @@ describe('MembersListComponent', () => {
let ePersonDataServiceStub: any;
let groupsDataServiceStub: any;
let activeGroup;
let allEPersons: EPerson[];
let allGroups: Group[];
let epersonMembers: EPerson[];
let subgroupMembers: Group[];
let epersonNonMembers: EPerson[];
let paginationService;
beforeEach(waitForAsync(() => {
activeGroup = GroupMock;
epersonMembers = [EPersonMock2];
subgroupMembers = [GroupMock2];
allEPersons = [EPersonMock, EPersonMock2];
allGroups = [GroupMock, GroupMock2];
epersonNonMembers = [EPersonMock];
ePersonDataServiceStub = {
activeGroup: activeGroup,
epersonMembers: epersonMembers,
subgroupMembers: subgroupMembers,
epersonNonMembers: epersonNonMembers,
// This method is used to get all the current members
findListByHref(_href: string): Observable<RemoteData<PaginatedList<EPerson>>> {
return createSuccessfulRemoteDataObject$(buildPaginatedList<EPerson>(new PageInfo(), groupsDataServiceStub.getEPersonMembers()));
},
searchByScope(scope: string, query: string): Observable<RemoteData<PaginatedList<EPerson>>> {
// This method is used to search across *non-members*
searchNonMembers(query: string, group: string): Observable<RemoteData<PaginatedList<EPerson>>> {
if (query === '') {
return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), allEPersons));
return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), epersonNonMembers));
}
return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), []));
},
@@ -70,29 +107,26 @@ describe('MembersListComponent', () => {
clearLinkRequests() {
// empty
},
getEPeoplePageRouterLink(): string {
return '/access-control/epeople';
}
};
groupsDataServiceStub = {
activeGroup: activeGroup,
epersonMembers: epersonMembers,
subgroupMembers: subgroupMembers,
allGroups: allGroups,
epersonNonMembers: epersonNonMembers,
getActiveGroup(): Observable<Group> {
return observableOf(activeGroup);
},
getEPersonMembers() {
return this.epersonMembers;
},
searchGroups(query: string): Observable<RemoteData<PaginatedList<Group>>> {
if (query === '') {
return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), this.allGroups));
}
return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), []));
},
addMemberToGroup(parentGroup, eperson: EPerson): Observable<RestResponse> {
this.epersonMembers = [...this.epersonMembers, eperson];
addMemberToGroup(parentGroup, epersonToAdd: EPerson): Observable<RestResponse> {
// Add eperson to list of members
this.epersonMembers = [...this.epersonMembers, epersonToAdd];
// Remove eperson from list of non-members
this.epersonNonMembers.forEach( (eperson: EPerson, index: number) => {
if (eperson.id === epersonToAdd.id) {
this.epersonNonMembers.splice(index, 1);
}
});
return observableOf(new RestResponse(true, 200, 'Success'));
},
clearGroupsRequests() {
@@ -105,16 +139,16 @@ describe('MembersListComponent', () => {
return '/access-control/groups/' + group.id;
},
deleteMemberFromGroup(parentGroup, epersonToDelete: EPerson): Observable<RestResponse> {
this.epersonMembers = this.epersonMembers.find((eperson: EPerson) => {
if (eperson.id !== epersonToDelete.id) {
return eperson;
// Remove eperson from list of members
this.epersonMembers.forEach( (eperson: EPerson, index: number) => {
if (eperson.id === epersonToDelete.id) {
this.epersonMembers.splice(index, 1);
}
});
if (this.epersonMembers === undefined) {
this.epersonMembers = [];
}
// Add eperson to list of non-members
this.epersonNonMembers = [...this.epersonNonMembers, epersonToDelete];
return observableOf(new RestResponse(true, 200, 'Success'));
}
},
};
builderService = getMockFormBuilderService();
translateService = getMockTranslateService();
@@ -125,11 +159,9 @@ describe('MembersListComponent', () => {
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}),
],
declarations: [MembersListComponent],
useClass: TranslateLoaderMock,
},
}), MembersListComponent],
providers: [MembersListComponent,
{ provide: EPersonDataService, useValue: ePersonDataServiceStub },
{ provide: GroupDataService, useValue: groupsDataServiceStub },
@@ -138,9 +170,16 @@ describe('MembersListComponent', () => {
{ provide: Router, useValue: new RouterMock() },
{ provide: PaginationService, useValue: paginationService },
{ provide: DSONameService, useValue: new DSONameServiceMock() },
{ provide: ActivatedRoute, useValue: new ActivatedRouteStub() },
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
schemas: [NO_ERRORS_SCHEMA],
})
.overrideComponent(MembersListComponent, {
remove: {
imports: [PaginationComponent, ContextHelpDirective],
},
})
.compileComponents();
}));
beforeEach(() => {
@@ -160,13 +199,37 @@ describe('MembersListComponent', () => {
expect(comp).toBeDefined();
}));
it('should show list of eperson members of current active group', () => {
const epersonIdsFound = fixture.debugElement.queryAll(By.css('#ePeopleMembersOfGroup tr td:first-child'));
expect(epersonIdsFound.length).toEqual(1);
epersonMembers.map((eperson: EPerson) => {
expect(epersonIdsFound.find((foundEl) => {
return (foundEl.nativeElement.textContent.trim() === eperson.uuid);
})).toBeTruthy();
describe('current members list', () => {
it('should show list of eperson members of current active group', () => {
const epersonIdsFound = fixture.debugElement.queryAll(By.css('#ePeopleMembersOfGroup tr td:first-child'));
expect(epersonIdsFound.length).toEqual(1);
epersonMembers.map((eperson: EPerson) => {
expect(epersonIdsFound.find((foundEl) => {
return (foundEl.nativeElement.textContent.trim() === eperson.uuid);
})).toBeTruthy();
});
});
it('should show a delete button next to each member', () => {
const epersonsFound = fixture.debugElement.queryAll(By.css('#ePeopleMembersOfGroup tbody tr'));
epersonsFound.map((foundEPersonRowElement: DebugElement) => {
const addButton: DebugElement = foundEPersonRowElement.query(By.css('td:last-child .fa-plus'));
const deleteButton: DebugElement = foundEPersonRowElement.query(By.css('td:last-child .fa-trash-alt'));
expect(addButton).toBeNull();
expect(deleteButton).not.toBeNull();
});
});
describe('if first delete button is pressed', () => {
beforeEach(() => {
const deleteButton: DebugElement = fixture.debugElement.query(By.css('#ePeopleMembersOfGroup tbody .fa-trash-alt'));
deleteButton.nativeElement.click();
fixture.detectChanges();
});
it('then no ePerson remains as a member of the active group.', () => {
const epersonsFound = fixture.debugElement.queryAll(By.css('#ePeopleMembersOfGroup tbody tr'));
expect(epersonsFound.length).toEqual(0);
});
});
});
@@ -174,76 +237,40 @@ describe('MembersListComponent', () => {
describe('when searching without query', () => {
let epersonsFound: DebugElement[];
beforeEach(fakeAsync(() => {
spyOn(component, 'isMemberOfGroup').and.callFake((ePerson: EPerson) => {
return observableOf(activeGroup.epersons.includes(ePerson));
});
component.search({ scope: 'metadata', query: '' });
tick();
fixture.detectChanges();
epersonsFound = fixture.debugElement.queryAll(By.css('#epersonsSearch tbody tr'));
// Stop using the fake spy function (because otherwise the clicking on the buttons will not change anything
// because they don't change the value of activeGroup.epersons)
jasmine.getEnv().allowRespy(true);
spyOn(component, 'isMemberOfGroup').and.callThrough();
}));
it('should display all epersons', () => {
expect(epersonsFound.length).toEqual(2);
it('should display only non-members of the group', () => {
const epersonIdsFound = fixture.debugElement.queryAll(By.css('#epersonsSearch tbody tr td:first-child'));
expect(epersonIdsFound.length).toEqual(1);
epersonNonMembers.map((eperson: EPerson) => {
expect(epersonIdsFound.find((foundEl) => {
return (foundEl.nativeElement.textContent.trim() === eperson.uuid);
})).toBeTruthy();
});
});
describe('if eperson is already a eperson', () => {
it('should have delete button, else it should have add button', () => {
const memberIds: string[] = activeGroup.epersons.map((ePerson: EPerson) => ePerson.id);
epersonsFound.map((foundEPersonRowElement: DebugElement) => {
const epersonId: DebugElement = foundEPersonRowElement.query(By.css('td:first-child'));
const addButton: DebugElement = foundEPersonRowElement.query(By.css('td:last-child .fa-plus'));
const deleteButton: DebugElement = foundEPersonRowElement.query(By.css('td:last-child .fa-trash-alt'));
if (memberIds.includes(epersonId.nativeElement.textContent)) {
expect(addButton).toBeNull();
expect(deleteButton).not.toBeNull();
} else {
expect(deleteButton).toBeNull();
expect(addButton).not.toBeNull();
}
});
it('should display an add button next to non-members, not a delete button', () => {
epersonsFound.map((foundEPersonRowElement: DebugElement) => {
const addButton: DebugElement = foundEPersonRowElement.query(By.css('td:last-child .fa-plus'));
const deleteButton: DebugElement = foundEPersonRowElement.query(By.css('td:last-child .fa-trash-alt'));
expect(addButton).not.toBeNull();
expect(deleteButton).toBeNull();
});
});
describe('if first add button is pressed', () => {
beforeEach(fakeAsync(() => {
beforeEach(() => {
const addButton: DebugElement = fixture.debugElement.query(By.css('#epersonsSearch tbody .fa-plus'));
addButton.nativeElement.click();
tick();
fixture.detectChanges();
}));
it('then all the ePersons are member of the active group', () => {
epersonsFound = fixture.debugElement.queryAll(By.css('#epersonsSearch tbody tr'));
expect(epersonsFound.length).toEqual(2);
epersonsFound.map((foundEPersonRowElement: DebugElement) => {
const addButton: DebugElement = foundEPersonRowElement.query(By.css('td:last-child .fa-plus'));
const deleteButton: DebugElement = foundEPersonRowElement.query(By.css('td:last-child .fa-trash-alt'));
expect(addButton).toBeNull();
expect(deleteButton).not.toBeNull();
});
});
});
describe('if first delete button is pressed', () => {
beforeEach(fakeAsync(() => {
const deleteButton: DebugElement = fixture.debugElement.query(By.css('#epersonsSearch tbody .fa-trash-alt'));
deleteButton.nativeElement.click();
tick();
fixture.detectChanges();
}));
it('then no ePerson is member of the active group', () => {
it('then all (two) ePersons are member of the active group. No non-members left', () => {
epersonsFound = fixture.debugElement.queryAll(By.css('#epersonsSearch tbody tr'));
expect(epersonsFound.length).toEqual(2);
epersonsFound.map((foundEPersonRowElement: DebugElement) => {
const addButton: DebugElement = foundEPersonRowElement.query(By.css('td:last-child .fa-plus'));
const deleteButton: DebugElement = foundEPersonRowElement.query(By.css('td:last-child .fa-trash-alt'));
expect(deleteButton).toBeNull();
expect(addButton).not.toBeNull();
});
expect(epersonsFound.length).toEqual(0);
});
});
});

View File

@@ -1,41 +1,66 @@
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { UntypedFormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import {
Observable,
of as observableOf,
Subscription,
AsyncPipe,
NgClass,
NgForOf,
NgIf,
} from '@angular/common';
import {
Component,
Input,
OnDestroy,
OnInit,
} from '@angular/core';
import {
ReactiveFormsModule,
UntypedFormBuilder,
} from '@angular/forms';
import {
Router,
RouterLink,
} from '@angular/router';
import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import {
BehaviorSubject,
combineLatest as observableCombineLatest,
ObservedValueOf,
Observable,
Subscription,
} from 'rxjs';
import { defaultIfEmpty, map, mergeMap, switchMap, take } from 'rxjs/operators';
import { buildPaginatedList, PaginatedList } from '../../../../core/data/paginated-list.model';
import {
map,
switchMap,
take,
} from 'rxjs/operators';
import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service';
import { PaginatedList } from '../../../../core/data/paginated-list.model';
import { RemoteData } from '../../../../core/data/remote-data';
import { EPersonDataService } from '../../../../core/eperson/eperson-data.service';
import { GroupDataService } from '../../../../core/eperson/group-data.service';
import { EPerson } from '../../../../core/eperson/models/eperson.model';
import { Group } from '../../../../core/eperson/models/group.model';
import {
getFirstSucceededRemoteData,
getFirstCompletedRemoteData,
getAllCompletedRemoteData,
getRemoteDataPayload
} from '../../../../core/shared/operators';
import { NotificationsService } from '../../../../shared/notifications/notifications.service';
import { PaginationComponentOptions } from '../../../../shared/pagination/pagination-component-options.model';
import { EpersonDtoModel } from '../../../../core/eperson/models/eperson-dto.model';
import { PaginationService } from '../../../../core/pagination/pagination.service';
import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service';
import {
getAllCompletedRemoteData,
getFirstCompletedRemoteData,
getRemoteDataPayload,
} from '../../../../core/shared/operators';
import { ContextHelpDirective } from '../../../../shared/context-help.directive';
import { NotificationsService } from '../../../../shared/notifications/notifications.service';
import { PaginationComponent } from '../../../../shared/pagination/pagination.component';
import { PaginationComponentOptions } from '../../../../shared/pagination/pagination-component-options.model';
import { getEPersonEditRoute } from '../../../access-control-routing-paths';
// todo: optimize imports
/**
* Keys to keep track of specific subscriptions
*/
enum SubKey {
ActiveGroup,
MembersDTO,
SearchResultsDTO,
Members,
SearchResults,
}
/**
@@ -69,7 +94,19 @@ export interface EPersonListActionConfig {
@Component({
selector: 'ds-members-list',
templateUrl: './members-list.component.html'
templateUrl: './members-list.component.html',
imports: [
TranslateModule,
ContextHelpDirective,
ReactiveFormsModule,
PaginationComponent,
NgIf,
AsyncPipe,
RouterLink,
NgClass,
NgForOf,
],
standalone: true,
})
/**
* The list of members in the edit group page
@@ -77,30 +114,30 @@ export interface EPersonListActionConfig {
export class MembersListComponent implements OnInit, OnDestroy {
@Input()
messagePrefix: string;
messagePrefix: string;
@Input()
actionConfig: EPersonListActionConfig = {
add: {
css: 'btn-outline-primary',
disabled: false,
icon: 'fas fa-plus fa-fw',
},
remove: {
css: 'btn-outline-danger',
disabled: false,
icon: 'fas fa-trash-alt fa-fw'
},
};
actionConfig: EPersonListActionConfig = {
add: {
css: 'btn-outline-primary',
disabled: false,
icon: 'fas fa-plus fa-fw',
},
remove: {
css: 'btn-outline-danger',
disabled: false,
icon: 'fas fa-trash-alt fa-fw',
},
};
/**
* EPeople being displayed in search result, initially all members, after search result of search
*/
ePeopleSearchDtos: BehaviorSubject<PaginatedList<EpersonDtoModel>> = new BehaviorSubject<PaginatedList<EpersonDtoModel>>(undefined);
ePeopleSearch: BehaviorSubject<PaginatedList<EPerson>> = new BehaviorSubject<PaginatedList<EPerson>>(undefined);
/**
* List of EPeople members of currently active group being edited
*/
ePeopleMembersOfGroupDtos: BehaviorSubject<PaginatedList<EpersonDtoModel>> = new BehaviorSubject<PaginatedList<EpersonDtoModel>>(undefined);
ePeopleMembersOfGroup: BehaviorSubject<PaginatedList<EPerson>> = new BehaviorSubject<PaginatedList<EPerson>>(undefined);
/**
* Pagination config used to display the list of EPeople that are result of EPeople search
@@ -108,7 +145,7 @@ export class MembersListComponent implements OnInit, OnDestroy {
configSearch: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), {
id: 'sml',
pageSize: 5,
currentPage: 1
currentPage: 1,
});
/**
* Pagination config used to display the list of EPerson Membes of active group being edited
@@ -116,7 +153,7 @@ export class MembersListComponent implements OnInit, OnDestroy {
config: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), {
id: 'ml',
pageSize: 5,
currentPage: 1
currentPage: 1,
});
/**
@@ -129,7 +166,6 @@ export class MembersListComponent implements OnInit, OnDestroy {
// Current search in edit group - epeople search form
currentSearchQuery: string;
currentSearchScope: string;
// Whether or not user has done a EPeople search yet
searchDone: boolean;
@@ -137,6 +173,8 @@ export class MembersListComponent implements OnInit, OnDestroy {
// current active group being edited
groupBeingEdited: Group;
readonly getEPersonEditRoute = getEPersonEditRoute;
constructor(
protected groupDataService: GroupDataService,
public ePersonDataService: EPersonDataService,
@@ -148,18 +186,17 @@ export class MembersListComponent implements OnInit, OnDestroy {
public dsoNameService: DSONameService,
) {
this.currentSearchQuery = '';
this.currentSearchScope = 'metadata';
}
ngOnInit(): void {
this.searchForm = this.formBuilder.group(({
scope: 'metadata',
query: '',
}));
this.subs.set(SubKey.ActiveGroup, this.groupDataService.getActiveGroup().subscribe((activeGroup: Group) => {
if (activeGroup != null) {
this.groupBeingEdited = activeGroup;
this.retrieveMembers(this.config.currentPage);
this.search({ query: '' });
}
}));
}
@@ -171,14 +208,14 @@ export class MembersListComponent implements OnInit, OnDestroy {
* @private
*/
retrieveMembers(page: number): void {
this.unsubFrom(SubKey.MembersDTO);
this.subs.set(SubKey.MembersDTO,
this.unsubFrom(SubKey.Members);
this.subs.set(SubKey.Members,
this.paginationService.getCurrentPagination(this.config.id, this.config).pipe(
switchMap((currentPagination) => {
return this.ePersonDataService.findListByHref(this.groupBeingEdited._links.epersons.href, {
currentPage: currentPagination.currentPage,
elementsPerPage: currentPagination.pageSize
}
currentPage: currentPagination.currentPage,
elementsPerPage: currentPagination.pageSize,
},
);
}),
getAllCompletedRemoteData(),
@@ -189,49 +226,12 @@ export class MembersListComponent implements OnInit, OnDestroy {
return rd;
}
}),
switchMap((epersonListRD: RemoteData<PaginatedList<EPerson>>) => {
const dtos$ = observableCombineLatest([...epersonListRD.payload.page.map((member: EPerson) => {
const dto$: Observable<EpersonDtoModel> = observableCombineLatest(
this.isMemberOfGroup(member), (isMember: ObservedValueOf<Observable<boolean>>) => {
const epersonDtoModel: EpersonDtoModel = new EpersonDtoModel();
epersonDtoModel.eperson = member;
epersonDtoModel.memberOfGroup = isMember;
return epersonDtoModel;
});
return dto$;
})]);
return dtos$.pipe(defaultIfEmpty([]), map((dtos: EpersonDtoModel[]) => {
return buildPaginatedList(epersonListRD.payload.pageInfo, dtos);
}));
}))
.subscribe((paginatedListOfDTOs: PaginatedList<EpersonDtoModel>) => {
this.ePeopleMembersOfGroupDtos.next(paginatedListOfDTOs);
getRemoteDataPayload())
.subscribe((paginatedListOfEPersons: PaginatedList<EPerson>) => {
this.ePeopleMembersOfGroup.next(paginatedListOfEPersons);
}));
}
/**
* Whether the given ePerson is a member of the group currently being edited
* @param possibleMember EPerson that is a possible member (being tested) of the group currently being edited
*/
isMemberOfGroup(possibleMember: EPerson): Observable<boolean> {
return this.groupDataService.getActiveGroup().pipe(take(1),
mergeMap((group: Group) => {
if (group != null) {
return this.ePersonDataService.findListByHref(group._links.epersons.href, {
currentPage: 1,
elementsPerPage: 9999
})
.pipe(
getFirstSucceededRemoteData(),
getRemoteDataPayload(),
map((listEPeopleInGroup: PaginatedList<EPerson>) => listEPeopleInGroup.page.filter((ePersonInList: EPerson) => ePersonInList.id === possibleMember.id)),
map((epeople: EPerson[]) => epeople.length > 0));
} else {
return observableOf(false);
}
}));
}
/**
* Unsubscribe from a subscription if it's still subscribed, and remove it from the map of
* active subscriptions
@@ -248,14 +248,18 @@ export class MembersListComponent implements OnInit, OnDestroy {
/**
* Deletes a given EPerson from the members list of the group currently being edited
* @param ePerson EPerson we want to delete as member from group that is currently being edited
* @param eperson EPerson we want to delete as member from group that is currently being edited
*/
deleteMemberFromGroup(ePerson: EpersonDtoModel) {
ePerson.memberOfGroup = false;
deleteMemberFromGroup(eperson: EPerson) {
this.groupDataService.getActiveGroup().pipe(take(1)).subscribe((activeGroup: Group) => {
if (activeGroup != null) {
const response = this.groupDataService.deleteMemberFromGroup(activeGroup, ePerson.eperson);
this.showNotifications('deleteMember', response, this.dsoNameService.getName(ePerson.eperson), activeGroup);
const response = this.groupDataService.deleteMemberFromGroup(activeGroup, eperson);
this.showNotifications('deleteMember', response, this.dsoNameService.getName(eperson), activeGroup);
// Reload search results (if there is an active query).
// This will potentially add this deleted subgroup into the list of search results.
if (this.currentSearchQuery != null) {
this.search({ query: this.currentSearchQuery });
}
} else {
this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure.noActiveGroup'));
}
@@ -264,14 +268,18 @@ export class MembersListComponent implements OnInit, OnDestroy {
/**
* Adds a given EPerson to the members list of the group currently being edited
* @param ePerson EPerson we want to add as member to group that is currently being edited
* @param eperson EPerson we want to add as member to group that is currently being edited
*/
addMemberToGroup(ePerson: EpersonDtoModel) {
ePerson.memberOfGroup = true;
addMemberToGroup(eperson: EPerson) {
this.groupDataService.getActiveGroup().pipe(take(1)).subscribe((activeGroup: Group) => {
if (activeGroup != null) {
const response = this.groupDataService.addMemberToGroup(activeGroup, ePerson.eperson);
this.showNotifications('addMember', response, this.dsoNameService.getName(ePerson.eperson), activeGroup);
const response = this.groupDataService.addMemberToGroup(activeGroup, eperson);
this.showNotifications('addMember', response, this.dsoNameService.getName(eperson), activeGroup);
// Reload search results (if there is an active query).
// This will potentially add this deleted subgroup into the list of search results.
if (this.currentSearchQuery != null) {
this.search({ query: this.currentSearchQuery });
}
} else {
this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure.noActiveGroup'));
}
@@ -279,37 +287,25 @@ export class MembersListComponent implements OnInit, OnDestroy {
}
/**
* Search in the EPeople by name, email or metadata
* @param data Contains scope and query param
* Search all EPeople who are NOT a member of the current group by name, email or metadata
* @param data Contains query param
*/
search(data: any) {
this.unsubFrom(SubKey.SearchResultsDTO);
this.subs.set(SubKey.SearchResultsDTO,
this.unsubFrom(SubKey.SearchResults);
this.subs.set(SubKey.SearchResults,
this.paginationService.getCurrentPagination(this.configSearch.id, this.configSearch).pipe(
switchMap((paginationOptions) => {
const query: string = data.query;
const scope: string = data.scope;
if (query != null && this.currentSearchQuery !== query && this.groupBeingEdited) {
this.router.navigate([], {
queryParamsHandling: 'merge'
});
this.currentSearchQuery = query;
this.paginationService.resetPage(this.configSearch.id);
}
if (scope != null && this.currentSearchScope !== scope && this.groupBeingEdited) {
this.router.navigate([], {
queryParamsHandling: 'merge'
});
this.currentSearchScope = scope;
this.paginationService.resetPage(this.configSearch.id);
}
this.searchDone = true;
return this.ePersonDataService.searchByScope(this.currentSearchScope, this.currentSearchQuery, {
return this.ePersonDataService.searchNonMembers(this.currentSearchQuery, this.groupBeingEdited.id, {
currentPage: paginationOptions.currentPage,
elementsPerPage: paginationOptions.pageSize
});
elementsPerPage: paginationOptions.pageSize,
}, false, true);
}),
getAllCompletedRemoteData(),
map((rd: RemoteData<any>) => {
@@ -319,23 +315,9 @@ export class MembersListComponent implements OnInit, OnDestroy {
return rd;
}
}),
switchMap((epersonListRD: RemoteData<PaginatedList<EPerson>>) => {
const dtos$ = observableCombineLatest([...epersonListRD.payload.page.map((member: EPerson) => {
const dto$: Observable<EpersonDtoModel> = observableCombineLatest(
this.isMemberOfGroup(member), (isMember: ObservedValueOf<Observable<boolean>>) => {
const epersonDtoModel: EpersonDtoModel = new EpersonDtoModel();
epersonDtoModel.eperson = member;
epersonDtoModel.memberOfGroup = isMember;
return epersonDtoModel;
});
return dto$;
})]);
return dtos$.pipe(defaultIfEmpty([]), map((dtos: EpersonDtoModel[]) => {
return buildPaginatedList(epersonListRD.payload.pageInfo, dtos);
}));
}))
.subscribe((paginatedListOfDTOs: PaginatedList<EpersonDtoModel>) => {
this.ePeopleSearchDtos.next(paginatedListOfDTOs);
getRemoteDataPayload())
.subscribe((paginatedListOfEPersons: PaginatedList<EPerson>) => {
this.ePeopleSearch.next(paginatedListOfEPersons);
}));
}

View File

@@ -1,100 +1,10 @@
<ng-container>
<h3 class="border-bottom pb-2">{{messagePrefix + '.head' | translate}}</h3>
<h4 id="search" class="border-bottom pb-2">
<span *dsContextHelp="{
content: 'admin.access-control.groups.form.tooltip.editGroup.addSubgroups',
id: 'edit-group-add-subgroups',
iconPlacement: 'right',
tooltipPlacement: ['top', 'right', 'bottom']
}"
>
{{messagePrefix + '.search.head' | translate}}
</span>
</h4>
<form [formGroup]="searchForm" (ngSubmit)="search(searchForm.value)" class="d-flex justify-content-between">
<div class="flex-grow-1 mr-3">
<div class="form-group input-group mr-3">
<input type="text" name="query" id="query" formControlName="query"
class="form-control" aria-label="Search input">
<span class="input-group-append">
<button type="submit" class="search-button btn btn-primary">
<i class="fas fa-search"></i> {{ messagePrefix + '.search.button' | translate }}
</button>
</span>
</div>
</div>
<div>
<button (click)="clearFormAndResetResult();" class="btn btn-secondary float-right">
{{messagePrefix + '.button.see-all' | translate}}
</button>
</div>
</form>
<ds-pagination *ngIf="(searchResults$ | async)?.payload?.totalElements > 0"
[paginationOptions]="configSearch"
[pageInfoState]="(searchResults$ | async)?.payload"
[collectionSize]="(searchResults$ | async)?.payload?.totalElements"
[hideGear]="true"
[hidePagerWhenSinglePage]="true">
<div class="table-responsive">
<table id="groupsSearch" class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th scope="col" class="align-middle">{{messagePrefix + '.table.id' | translate}}</th>
<th scope="col" class="align-middle">{{messagePrefix + '.table.name' | translate}}</th>
<th scope="col" class="align-middle">{{messagePrefix + '.table.collectionOrCommunity' | translate}}</th>
<th class="align-middle">{{messagePrefix + '.table.edit' | translate}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let group of (searchResults$ | async)?.payload?.page">
<td class="align-middle">{{group.id}}</td>
<td class="align-middle">
<a (click)="groupDataService.startEditingNewGroup(group)"
[routerLink]="[groupDataService.getGroupEditPageRouterLink(group)]">
{{ dsoNameService.getName(group) }}
</a>
</td>
<td class="align-middle">{{ dsoNameService.getName((group.object | async)?.payload) }}</td>
<td class="align-middle">
<div class="btn-group edit-field">
<button *ngIf="(isSubgroupOfGroup(group) | async) && !(isActiveGroup(group) | async)"
(click)="deleteSubgroupFromGroup(group)"
class="btn btn-outline-danger btn-sm deleteButton"
title="{{messagePrefix + '.table.edit.buttons.remove' | translate: { name: dsoNameService.getName(group) } }}">
<i class="fas fa-trash-alt fa-fw"></i>
</button>
<span *ngIf="(isActiveGroup(group) | async)">{{ messagePrefix + '.table.edit.currentGroup' | translate }}</span>
<button *ngIf="!(isSubgroupOfGroup(group) | async) && !(isActiveGroup(group) | async)"
(click)="addSubgroupToGroup(group)"
class="btn btn-outline-primary btn-sm addButton"
title="{{messagePrefix + '.table.edit.buttons.add' | translate: { name: dsoNameService.getName(group) } }}">
<i class="fas fa-plus fa-fw"></i>
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</ds-pagination>
<div *ngIf="(searchResults$ | async)?.payload?.totalElements == 0 && searchDone" class="alert alert-info w-100 mb-2"
role="alert">
{{messagePrefix + '.no-items' | translate}}
</div>
<h4>{{messagePrefix + '.headSubgroups' | translate}}</h4>
<ds-pagination *ngIf="(subGroups$ | async)?.payload?.totalElements > 0"
[paginationOptions]="config"
[pageInfoState]="(subGroups$ | async)?.payload"
[collectionSize]="(subGroups$ | async)?.payload?.totalElements"
[hideGear]="true"
[hidePagerWhenSinglePage]="true">
@@ -134,9 +44,87 @@
</div>
</ds-pagination>
<div *ngIf="(subGroups$ | async)?.payload?.totalElements == 0" class="alert alert-info w-100 mb-2"
<div *ngIf="(subGroups$ | async)?.payload?.totalElements === 0" class="alert alert-info w-100 mb-2"
role="alert">
{{messagePrefix + '.no-subgroups-yet' | translate}}
</div>
<h4 id="search" class="border-bottom pb-2">
<span *dsContextHelp="{
content: 'admin.access-control.groups.form.tooltip.editGroup.addSubgroups',
id: 'edit-group-add-subgroups',
iconPlacement: 'right',
tooltipPlacement: ['top', 'right', 'bottom']
}"
>
{{messagePrefix + '.search.head' | translate}}
</span>
</h4>
<form [formGroup]="searchForm" (ngSubmit)="search(searchForm.value)" class="d-flex justify-content-between">
<div class="flex-grow-1 mr-3">
<div class="form-group input-group mr-3">
<input type="text" name="query" id="query" formControlName="query"
class="form-control" aria-label="Search input">
<span class="input-group-append">
<button type="submit" class="search-button btn btn-primary">
<i class="fas fa-search"></i> {{ messagePrefix + '.search.button' | translate }}
</button>
</span>
</div>
</div>
<div>
<button (click)="clearFormAndResetResult();" class="btn btn-secondary float-right">
{{messagePrefix + '.button.see-all' | translate}}
</button>
</div>
</form>
<ds-pagination *ngIf="(searchResults$ | async)?.payload?.totalElements > 0"
[paginationOptions]="configSearch"
[collectionSize]="(searchResults$ | async)?.payload?.totalElements"
[hideGear]="true"
[hidePagerWhenSinglePage]="true">
<div class="table-responsive">
<table id="groupsSearch" class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th scope="col" class="align-middle">{{messagePrefix + '.table.id' | translate}}</th>
<th scope="col" class="align-middle">{{messagePrefix + '.table.name' | translate}}</th>
<th scope="col" class="align-middle">{{messagePrefix + '.table.collectionOrCommunity' | translate}}</th>
<th class="align-middle">{{messagePrefix + '.table.edit' | translate}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let group of (searchResults$ | async)?.payload?.page">
<td class="align-middle">{{group.id}}</td>
<td class="align-middle">
<a (click)="groupDataService.startEditingNewGroup(group)"
[routerLink]="[groupDataService.getGroupEditPageRouterLink(group)]">
{{ dsoNameService.getName(group) }}
</a>
</td>
<td class="align-middle">{{ dsoNameService.getName((group.object | async)?.payload) }}</td>
<td class="align-middle">
<div class="btn-group edit-field">
<button (click)="addSubgroupToGroup(group)"
class="btn btn-outline-primary btn-sm addButton"
title="{{messagePrefix + '.table.edit.buttons.add' | translate: { name: dsoNameService.getName(group) } }}">
<i class="fas fa-plus fa-fw"></i>
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</ds-pagination>
<div *ngIf="(searchResults$ | async)?.payload?.totalElements === 0 && searchDone" class="alert alert-info w-100 mb-2"
role="alert">
{{messagePrefix + '.no-items' | translate}}
</div>
</ng-container>

View File

@@ -1,36 +1,69 @@
import { CommonModule } from '@angular/common';
import { NO_ERRORS_SCHEMA, DebugElement } from '@angular/core';
import { ComponentFixture, fakeAsync, flush, inject, 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 {
DebugElement,
NO_ERRORS_SCHEMA,
} from '@angular/core';
import {
ComponentFixture,
fakeAsync,
flush,
inject,
TestBed,
waitForAsync,
} from '@angular/core/testing';
import {
FormsModule,
ReactiveFormsModule,
} from '@angular/forms';
import {
BrowserModule,
By,
} from '@angular/platform-browser';
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core';
import { Observable, of as observableOf, BehaviorSubject } from 'rxjs';
import {
TranslateLoader,
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import {
Observable,
of as observableOf,
} from 'rxjs';
import { EPersonMock2 } from 'src/app/shared/testing/eperson.mock';
import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service';
import { RestResponse } from '../../../../core/cache/response.models';
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 { GroupDataService } from '../../../../core/eperson/group-data.service';
import { Group } from '../../../../core/eperson/models/group.model';
import { PageInfo } from '../../../../core/shared/page-info.model';
import { FormBuilderService } from '../../../../shared/form/builder/form-builder.service';
import { NotificationsService } from '../../../../shared/notifications/notifications.service';
import { GroupMock, GroupMock2 } from '../../../../shared/testing/group-mock';
import { SubgroupsListComponent } from './subgroups-list.component';
import {
createSuccessfulRemoteDataObject$,
createSuccessfulRemoteDataObject
} from '../../../../shared/remote-data.utils';
import { RouterMock } from '../../../../shared/mocks/router.mock';
import { getMockFormBuilderService } from '../../../../shared/mocks/form-builder-service.mock';
import { getMockTranslateService } from '../../../../shared/mocks/translate.service.mock';
import { TranslateLoaderMock } from '../../../../shared/testing/translate-loader.mock';
import { NotificationsServiceStub } from '../../../../shared/testing/notifications-service.stub';
import { map } from 'rxjs/operators';
import { PaginationService } from '../../../../core/pagination/pagination.service';
import { PaginationServiceStub } from '../../../../shared/testing/pagination-service.stub';
import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service';
import { PageInfo } from '../../../../core/shared/page-info.model';
import { ContextHelpDirective } from '../../../../shared/context-help.directive';
import { FormBuilderService } from '../../../../shared/form/builder/form-builder.service';
import { DSONameServiceMock } from '../../../../shared/mocks/dso-name.service.mock';
import { getMockFormBuilderService } from '../../../../shared/mocks/form-builder-service.mock';
import { RouterMock } from '../../../../shared/mocks/router.mock';
import { getMockTranslateService } from '../../../../shared/mocks/translate.service.mock';
import { NotificationsService } from '../../../../shared/notifications/notifications.service';
import { PaginationComponent } from '../../../../shared/pagination/pagination.component';
import { createSuccessfulRemoteDataObject$ } from '../../../../shared/remote-data.utils';
import { ActivatedRouteStub } from '../../../../shared/testing/active-router.stub';
import {
GroupMock,
GroupMock2,
} from '../../../../shared/testing/group-mock';
import { NotificationsServiceStub } from '../../../../shared/testing/notifications-service.stub';
import { PaginationServiceStub } from '../../../../shared/testing/pagination-service.stub';
import { TranslateLoaderMock } from '../../../../shared/testing/translate-loader.mock';
import { SubgroupsListComponent } from './subgroups-list.component';
describe('SubgroupsListComponent', () => {
let component: SubgroupsListComponent;
@@ -39,44 +72,72 @@ describe('SubgroupsListComponent', () => {
let builderService: FormBuilderService;
let ePersonDataServiceStub: any;
let groupsDataServiceStub: any;
let activeGroup;
let activeGroup: Group;
let subgroups: Group[];
let allGroups: Group[];
let groupNonMembers: Group[];
let routerStub;
let paginationService;
// Define a new mock activegroup for all tests below
let mockActiveGroup: Group = Object.assign(new Group(), {
handle: null,
subgroups: [GroupMock2],
epersons: [EPersonMock2],
selfRegistered: false,
permanent: false,
_links: {
self: {
href: 'https://rest.api/server/api/eperson/groups/activegroupid',
},
subgroups: { href: 'https://rest.api/server/api/eperson/groups/activegroupid/subgroups' },
object: { href: 'https://rest.api/server/api/eperson/groups/activegroupid/object' },
epersons: { href: 'https://rest.api/server/api/eperson/groups/activegroupid/epersons' },
},
_name: 'activegroupname',
id: 'activegroupid',
uuid: 'activegroupid',
type: 'group',
});
beforeEach(waitForAsync(() => {
activeGroup = GroupMock;
activeGroup = mockActiveGroup;
subgroups = [GroupMock2];
allGroups = [GroupMock, GroupMock2];
groupNonMembers = [GroupMock];
ePersonDataServiceStub = {};
groupsDataServiceStub = {
activeGroup: activeGroup,
subgroups$: new BehaviorSubject(subgroups),
subgroups: subgroups,
groupNonMembers: groupNonMembers,
getActiveGroup(): Observable<Group> {
return observableOf(this.activeGroup);
},
getSubgroups(): Group {
return this.activeGroup;
return this.subgroups;
},
// This method is used to get all the current subgroups
findListByHref(_href: string): Observable<RemoteData<PaginatedList<Group>>> {
return this.subgroups$.pipe(
map((currentGroups: Group[]) => {
return createSuccessfulRemoteDataObject(buildPaginatedList<Group>(new PageInfo(), currentGroups));
})
);
return createSuccessfulRemoteDataObject$(buildPaginatedList<Group>(new PageInfo(), groupsDataServiceStub.getSubgroups()));
},
getGroupEditPageRouterLink(group: Group): string {
return '/access-control/groups/' + group.id;
},
searchGroups(query: string): Observable<RemoteData<PaginatedList<Group>>> {
// This method is used to get all groups which are NOT currently a subgroup member
searchNonMemberGroups(query: string, group: string): Observable<RemoteData<PaginatedList<Group>>> {
if (query === '') {
return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), allGroups));
return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), groupNonMembers));
}
return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo(), []));
return createSuccessfulRemoteDataObject$(
buildPaginatedList(new PageInfo(), []),
);
},
addSubGroupToGroup(parentGroup, subgroup: Group): Observable<RestResponse> {
this.subgroups$.next([...this.subgroups$.getValue(), subgroup]);
addSubGroupToGroup(parentGroup, subgroupToAdd: Group): Observable<RestResponse> {
// Add group to list of subgroups
this.subgroups = [...this.subgroups, subgroupToAdd];
// Remove group from list of non-members
this.groupNonMembers.forEach( (group: Group, index: number) => {
if (group.id === subgroupToAdd.id) {
this.groupNonMembers.splice(index, 1);
}
});
return observableOf(new RestResponse(true, 200, 'Success'));
},
clearGroupsRequests() {
@@ -85,40 +146,59 @@ describe('SubgroupsListComponent', () => {
clearGroupLinkRequests() {
// empty
},
deleteSubGroupFromGroup(parentGroup, subgroup: Group): Observable<RestResponse> {
this.subgroups$.next(this.subgroups$.getValue().filter((group: Group) => {
if (group.id !== subgroup.id) {
return group;
deleteSubGroupFromGroup(parentGroup, subgroupToDelete: Group): Observable<RestResponse> {
// Remove group from list of subgroups
this.subgroups.forEach( (group: Group, index: number) => {
if (group.id === subgroupToDelete.id) {
this.subgroups.splice(index, 1);
}
}));
});
// Add group to list of non-members
this.groupNonMembers = [...this.groupNonMembers, subgroupToDelete];
return observableOf(new RestResponse(true, 200, 'Success'));
}
},
};
routerStub = new RouterMock();
builderService = getMockFormBuilderService();
translateService = getMockTranslateService();
paginationService = new PaginationServiceStub();
TestBed.configureTestingModule({
imports: [CommonModule, NgbModule, FormsModule, ReactiveFormsModule, BrowserModule,
return TestBed.configureTestingModule({
imports: [
CommonModule,
NgbModule,
FormsModule,
ReactiveFormsModule,
BrowserModule,
// ContextHelpDirective,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
useClass: TranslateLoaderMock,
},
}),
SubgroupsListComponent,
],
declarations: [SubgroupsListComponent],
providers: [SubgroupsListComponent,
providers: [
SubgroupsListComponent,
{ provide: DSONameService, useValue: new DSONameServiceMock() },
{ provide: GroupDataService, useValue: groupsDataServiceStub },
{ provide: NotificationsService, useValue: new NotificationsServiceStub() },
{
provide: NotificationsService,
useValue: new NotificationsServiceStub(),
},
{ provide: FormBuilderService, useValue: builderService },
{ provide: Router, useValue: routerStub },
{ provide: PaginationService, useValue: paginationService },
{ provide: ActivatedRoute, useValue: new ActivatedRouteStub() },
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
schemas: [NO_ERRORS_SCHEMA],
})
.overrideComponent(SubgroupsListComponent, {
remove: {
imports: [ContextHelpDirective, PaginationComponent],
},
})
.compileComponents();
}));
beforeEach(() => {
@@ -137,30 +217,38 @@ describe('SubgroupsListComponent', () => {
expect(comp).toBeDefined();
}));
it('should show list of subgroups of current active group', () => {
const groupIdsFound = fixture.debugElement.queryAll(By.css('#subgroupsOfGroup tr td:first-child'));
expect(groupIdsFound.length).toEqual(1);
activeGroup.subgroups.map((group: Group) => {
expect(groupIdsFound.find((foundEl) => {
return (foundEl.nativeElement.textContent.trim() === group.uuid);
})).toBeTruthy();
});
});
describe('if first group delete button is pressed', () => {
let groupsFound: DebugElement[];
beforeEach(fakeAsync(() => {
const addButton = fixture.debugElement.query(By.css('#subgroupsOfGroup tbody .deleteButton'));
addButton.triggerEventHandler('click', {
preventDefault: () => {/**/
}
describe('current subgroup list', () => {
it('should show list of subgroups of current active group', () => {
const groupIdsFound = fixture.debugElement.queryAll(By.css('#subgroupsOfGroup tr td:first-child'));
expect(groupIdsFound.length).toEqual(1);
subgroups.map((group: Group) => {
expect(groupIdsFound.find((foundEl) => {
return (foundEl.nativeElement.textContent.trim() === group.uuid);
})).toBeTruthy();
});
});
it('should show a delete button next to each subgroup', () => {
const subgroupsFound = fixture.debugElement.queryAll(By.css('#subgroupsOfGroup tbody tr'));
subgroupsFound.map((foundGroupRowElement: DebugElement) => {
const addButton: DebugElement = foundGroupRowElement.query(By.css('td:last-child .fa-plus'));
const deleteButton: DebugElement = foundGroupRowElement.query(By.css('td:last-child .fa-trash-alt'));
expect(addButton).toBeNull();
expect(deleteButton).not.toBeNull();
});
});
describe('if first group delete button is pressed', () => {
let groupsFound: DebugElement[];
beforeEach(() => {
const deleteButton = fixture.debugElement.query(By.css('#subgroupsOfGroup tbody .deleteButton'));
deleteButton.nativeElement.click();
fixture.detectChanges();
});
it('then no subgroup remains as a member of the active group', () => {
groupsFound = fixture.debugElement.queryAll(By.css('#subgroupsOfGroup tbody tr'));
expect(groupsFound.length).toEqual(0);
});
tick();
fixture.detectChanges();
}));
it('one less subgroup in list from 1 to 0 (of 2 total groups)', () => {
groupsFound = fixture.debugElement.queryAll(By.css('#subgroupsOfGroup tbody tr'));
expect(groupsFound.length).toEqual(0);
});
});
@@ -169,54 +257,38 @@ describe('SubgroupsListComponent', () => {
let groupsFound: DebugElement[];
beforeEach(fakeAsync(() => {
component.search({ query: '' });
fixture.detectChanges();
groupsFound = fixture.debugElement.queryAll(By.css('#groupsSearch tbody tr'));
}));
it('should display all groups', () => {
fixture.detectChanges();
groupsFound = fixture.debugElement.queryAll(By.css('#groupsSearch tbody tr'));
expect(groupsFound.length).toEqual(2);
groupsFound = fixture.debugElement.queryAll(By.css('#groupsSearch tbody tr'));
it('should display only non-member groups (i.e. groups that are not a subgroup)', () => {
const groupIdsFound: DebugElement[] = fixture.debugElement.queryAll(By.css('#groupsSearch tbody tr td:first-child'));
allGroups.map((group: Group) => {
expect(groupIdsFound.length).toEqual(1);
groupNonMembers.map((group: Group) => {
expect(groupIdsFound.find((foundEl: DebugElement) => {
return (foundEl.nativeElement.textContent.trim() === group.uuid);
})).toBeTruthy();
});
});
describe('if group is already a subgroup', () => {
it('should have delete button, else it should have add button', () => {
it('should display an add button next to non-member groups, not a delete button', () => {
groupsFound.map((foundGroupRowElement: DebugElement) => {
const addButton: DebugElement = foundGroupRowElement.query(By.css('td:last-child .fa-plus'));
const deleteButton: DebugElement = foundGroupRowElement.query(By.css('td:last-child .fa-trash-alt'));
expect(addButton).not.toBeNull();
expect(deleteButton).toBeNull();
});
});
describe('if first add button is pressed', () => {
beforeEach(() => {
const addButton: DebugElement = fixture.debugElement.query(By.css('#groupsSearch tbody .fa-plus'));
addButton.nativeElement.click();
fixture.detectChanges();
});
it('then all (two) Groups are subgroups of the active group. No non-members left', () => {
groupsFound = fixture.debugElement.queryAll(By.css('#groupsSearch tbody tr'));
const getSubgroups = groupsDataServiceStub.getSubgroups().subgroups;
if (getSubgroups !== undefined && getSubgroups.length > 0) {
groupsFound.map((foundGroupRowElement: DebugElement) => {
const groupId: DebugElement = foundGroupRowElement.query(By.css('td:first-child'));
const addButton: DebugElement = foundGroupRowElement.query(By.css('td:last-child .fa-plus'));
const deleteButton: DebugElement = foundGroupRowElement.query(By.css('td:last-child .fa-trash-alt'));
expect(addButton).toBeNull();
if (activeGroup.id === groupId.nativeElement.textContent) {
expect(deleteButton).toBeNull();
} else {
expect(deleteButton).not.toBeNull();
}
});
} else {
const subgroupIds: string[] = activeGroup.subgroups.map((group: Group) => group.id);
groupsFound.map((foundGroupRowElement: DebugElement) => {
const groupId: DebugElement = foundGroupRowElement.query(By.css('td:first-child'));
const addButton: DebugElement = foundGroupRowElement.query(By.css('td:last-child .fa-plus'));
const deleteButton: DebugElement = foundGroupRowElement.query(By.css('td:last-child .fa-trash-alt'));
if (subgroupIds.includes(groupId.nativeElement.textContent)) {
expect(addButton).toBeNull();
expect(deleteButton).not.toBeNull();
} else {
expect(deleteButton).toBeNull();
expect(addButton).not.toBeNull();
}
});
}
expect(groupsFound.length).toEqual(0);
});
});
});

View File

@@ -1,24 +1,54 @@
import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { UntypedFormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { BehaviorSubject, Observable, of as observableOf, Subscription } from 'rxjs';
import { map, mergeMap, switchMap, take } from 'rxjs/operators';
import {
AsyncPipe,
NgForOf,
NgIf,
} from '@angular/common';
import {
Component,
Input,
OnDestroy,
OnInit,
} from '@angular/core';
import {
ReactiveFormsModule,
UntypedFormBuilder,
} from '@angular/forms';
import {
Router,
RouterLink,
} from '@angular/router';
import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import {
BehaviorSubject,
Observable,
Subscription,
} from 'rxjs';
import {
map,
switchMap,
take,
} from 'rxjs/operators';
import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service';
import { PaginatedList } from '../../../../core/data/paginated-list.model';
import { RemoteData } from '../../../../core/data/remote-data';
import { GroupDataService } from '../../../../core/eperson/group-data.service';
import { Group } from '../../../../core/eperson/models/group.model';
import {
getFirstCompletedRemoteData,
getFirstSucceededRemoteData,
getRemoteDataPayload
} from '../../../../core/shared/operators';
import { NotificationsService } from '../../../../shared/notifications/notifications.service';
import { PaginationComponentOptions } from '../../../../shared/pagination/pagination-component-options.model';
import { NoContent } from '../../../../core/shared/NoContent.model';
import { PaginationService } from '../../../../core/pagination/pagination.service';
import { NoContent } from '../../../../core/shared/NoContent.model';
import {
getAllCompletedRemoteData,
getFirstCompletedRemoteData,
} from '../../../../core/shared/operators';
import { PageInfo } from '../../../../core/shared/page-info.model';
import { ContextHelpDirective } from '../../../../shared/context-help.directive';
import { NotificationsService } from '../../../../shared/notifications/notifications.service';
import { PaginationComponent } from '../../../../shared/pagination/pagination.component';
import { PaginationComponentOptions } from '../../../../shared/pagination/pagination-component-options.model';
import { followLink } from '../../../../shared/utils/follow-link-config.model';
import { DSONameService } from '../../../../core/breadcrumbs/dso-name.service';
/**
* Keys to keep track of specific subscriptions
@@ -31,7 +61,18 @@ enum SubKey {
@Component({
selector: 'ds-subgroups-list',
templateUrl: './subgroups-list.component.html'
templateUrl: './subgroups-list.component.html',
imports: [
RouterLink,
AsyncPipe,
NgForOf,
ContextHelpDirective,
TranslateModule,
ReactiveFormsModule,
PaginationComponent,
NgIf,
],
standalone: true,
})
/**
* The list of subgroups in the edit group page
@@ -39,7 +80,7 @@ enum SubKey {
export class SubgroupsListComponent implements OnInit, OnDestroy {
@Input()
messagePrefix: string;
messagePrefix: string;
/**
* Result of search groups, initially all groups
@@ -50,6 +91,8 @@ export class SubgroupsListComponent implements OnInit, OnDestroy {
*/
subGroups$: BehaviorSubject<RemoteData<PaginatedList<Group>>> = new BehaviorSubject(undefined);
subGroupsPageInfoState$: Observable<PageInfo>;
/**
* Map of active subscriptions
*/
@@ -61,7 +104,7 @@ export class SubgroupsListComponent implements OnInit, OnDestroy {
configSearch: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), {
id: 'ssgl',
pageSize: 5,
currentPage: 1
currentPage: 1,
});
/**
* Pagination config used to display the list of subgroups of currently active group being edited
@@ -69,7 +112,7 @@ export class SubgroupsListComponent implements OnInit, OnDestroy {
config: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), {
id: 'sgl',
pageSize: 5,
currentPage: 1
currentPage: 1,
});
// The search form
@@ -103,8 +146,12 @@ export class SubgroupsListComponent implements OnInit, OnDestroy {
if (activeGroup != null) {
this.groupBeingEdited = activeGroup;
this.retrieveSubGroups();
this.search({ query: '' });
}
}));
this.subGroupsPageInfoState$ = this.subGroups$.pipe(
map(subGroupsRD => subGroupsRD?.payload?.pageInfo),
);
}
/**
@@ -119,59 +166,18 @@ export class SubgroupsListComponent implements OnInit, OnDestroy {
SubKey.Members,
this.paginationService.getCurrentPagination(this.config.id, this.config).pipe(
switchMap((config) => this.groupDataService.findListByHref(this.groupBeingEdited._links.subgroups.href, {
currentPage: config.currentPage,
elementsPerPage: config.pageSize
},
true,
true,
followLink('object')
))
currentPage: config.currentPage,
elementsPerPage: config.pageSize,
},
true,
true,
followLink('object'),
)),
).subscribe((rd: RemoteData<PaginatedList<Group>>) => {
this.subGroups$.next(rd);
}));
}
/**
* Whether or not the given group is a subgroup of the group currently being edited
* @param possibleSubgroup Group that is a possible subgroup (being tested) of the group currently being edited
*/
isSubgroupOfGroup(possibleSubgroup: Group): Observable<boolean> {
return this.groupDataService.getActiveGroup().pipe(take(1),
mergeMap((activeGroup: Group) => {
if (activeGroup != null) {
if (activeGroup.uuid === possibleSubgroup.uuid) {
return observableOf(false);
} else {
return this.groupDataService.findListByHref(activeGroup._links.subgroups.href, {
currentPage: 1,
elementsPerPage: 9999
})
.pipe(
getFirstSucceededRemoteData(),
getRemoteDataPayload(),
map((listTotalGroups: PaginatedList<Group>) => listTotalGroups.page.filter((groupInList: Group) => groupInList.id === possibleSubgroup.id)),
map((groups: Group[]) => groups.length > 0));
}
} else {
return observableOf(false);
}
}));
}
/**
* Whether or not the given group is the current group being edited
* @param group Group that is possibly the current group being edited
*/
isActiveGroup(group: Group): Observable<boolean> {
return this.groupDataService.getActiveGroup().pipe(take(1),
mergeMap((activeGroup: Group) => {
if (activeGroup != null && activeGroup.uuid === group.uuid) {
return observableOf(true);
}
return observableOf(false);
}));
}
/**
* Deletes given subgroup from the group currently being edited
* @param subgroup Group we want to delete from the subgroups of the group currently being edited
@@ -181,6 +187,11 @@ export class SubgroupsListComponent implements OnInit, OnDestroy {
if (activeGroup != null) {
const response = this.groupDataService.deleteSubGroupFromGroup(activeGroup, subgroup);
this.showNotifications('deleteSubgroup', response, this.dsoNameService.getName(subgroup), activeGroup);
// Reload search results (if there is an active query).
// This will potentially add this deleted subgroup into the list of search results.
if (this.currentSearchQuery != null) {
this.search({ query: this.currentSearchQuery });
}
} else {
this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure.noActiveGroup'));
}
@@ -197,6 +208,11 @@ export class SubgroupsListComponent implements OnInit, OnDestroy {
if (activeGroup.uuid !== subgroup.uuid) {
const response = this.groupDataService.addSubGroupToGroup(activeGroup, subgroup);
this.showNotifications('addSubgroup', response, this.dsoNameService.getName(subgroup), activeGroup);
// Reload search results (if there is an active query).
// This will potentially remove this added subgroup from search results.
if (this.currentSearchQuery != null) {
this.search({ query: this.currentSearchQuery });
}
} else {
this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure.subgroupToAddIsActiveGroup'));
}
@@ -207,28 +223,38 @@ export class SubgroupsListComponent implements OnInit, OnDestroy {
}
/**
* Search in the groups (searches by group name and by uuid exact match)
* Search all non-member groups (searches by group name and by uuid exact match). Used to search for
* groups that could be added to current group as a subgroup.
* @param data Contains query param
*/
search(data: any) {
const query: string = data.query;
if (query != null && this.currentSearchQuery !== query) {
this.router.navigateByUrl(this.groupDataService.getGroupEditPageRouterLink(this.groupBeingEdited));
this.currentSearchQuery = query;
this.configSearch.currentPage = 1;
}
this.searchDone = true;
this.unsubFrom(SubKey.SearchResults);
this.subs.set(SubKey.SearchResults, this.paginationService.getCurrentPagination(this.configSearch.id, this.configSearch).pipe(
switchMap((config) => this.groupDataService.searchGroups(this.currentSearchQuery, {
currentPage: config.currentPage,
elementsPerPage: config.pageSize
}, true, true, followLink('object')
))
).subscribe((rd: RemoteData<PaginatedList<Group>>) => {
this.searchResults$.next(rd);
}));
this.subs.set(SubKey.SearchResults,
this.paginationService.getCurrentPagination(this.configSearch.id, this.configSearch).pipe(
switchMap((paginationOptions) => {
const query: string = data.query;
if (query != null && this.currentSearchQuery !== query && this.groupBeingEdited) {
this.currentSearchQuery = query;
this.paginationService.resetPage(this.configSearch.id);
}
this.searchDone = true;
return this.groupDataService.searchNonMemberGroups(this.currentSearchQuery, this.groupBeingEdited.id, {
currentPage: paginationOptions.currentPage,
elementsPerPage: paginationOptions.pageSize,
}, false, true, followLink('object'));
}),
getAllCompletedRemoteData(),
map((rd: RemoteData<any>) => {
if (rd.hasFailed) {
this.notificationsService.error(this.translateService.get(this.messagePrefix + '.notification.failure', { cause: rd.errorMessage }));
} else {
return rd;
}
}))
.subscribe((rd: RemoteData<PaginatedList<Group>>) => {
this.searchResults$.next(rd);
}));
}
/**

View File

@@ -1,10 +1,13 @@
import { AbstractControl, ValidationErrors } from '@angular/forms';
import {
AbstractControl,
ValidationErrors,
} from '@angular/forms';
import { Observable } from 'rxjs';
import { map} from 'rxjs/operators';
import { map } from 'rxjs/operators';
import { GroupDataService } from '../../../../core/eperson/group-data.service';
import { getFirstSucceededRemoteListPayload } from '../../../../core/shared/operators';
import { Group } from '../../../../core/eperson/models/group.model';
import { getFirstSucceededRemoteListPayload } from '../../../../core/shared/operators';
export class ValidateGroupExists {
@@ -16,9 +19,9 @@ export class ValidateGroupExists {
static createValidator(groupDataService: GroupDataService) {
return (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
return groupDataService.searchGroups(control.value, {
currentPage: 1,
elementsPerPage: 100
})
currentPage: 1,
elementsPerPage: 100,
})
.pipe(
getFirstSucceededRemoteListPayload(),
map( (groups: Group[]) => {

View File

@@ -1,10 +1,14 @@
import { GroupPageGuard } from './group-page.guard';
import { HALEndpointService } from '../../core/shared/hal-endpoint.service';
import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service';
import { ActivatedRouteSnapshot, Router } from '@angular/router';
import {
ActivatedRouteSnapshot,
Router,
} from '@angular/router';
import { of as observableOf } from 'rxjs';
import { AuthService } from '../../core/auth/auth.service';
import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service';
import { FeatureID } from '../../core/data/feature-authorization/feature-id';
import { HALEndpointService } from '../../core/shared/hal-endpoint.service';
import { GroupPageGuard } from './group-page.guard';
describe('GroupPageGuard', () => {
const groupsEndpointUrl = 'https://test.org/api/eperson/groups';
@@ -13,7 +17,7 @@ describe('GroupPageGuard', () => {
const routeSnapshotWithGroupId = {
params: {
groupId: groupUuid,
}
},
} as unknown as ActivatedRouteSnapshot;
let guard: GroupPageGuard;
@@ -50,10 +54,10 @@ describe('GroupPageGuard', () => {
it('should return true', (done) => {
guard.canActivate(
routeSnapshotWithGroupId, { url: 'current-url'} as any
routeSnapshotWithGroupId, { url: 'current-url' } as any,
).subscribe((result) => {
expect(authorizationService.isAuthorized).toHaveBeenCalledWith(
FeatureID.CanManageGroup, groupEndpointUrl, undefined
FeatureID.CanManageGroup, groupEndpointUrl, undefined,
);
expect(result).toBeTrue();
done();
@@ -68,10 +72,10 @@ describe('GroupPageGuard', () => {
it('should not return true', (done) => {
guard.canActivate(
routeSnapshotWithGroupId, { url: 'current-url'} as any
routeSnapshotWithGroupId, { url: 'current-url' } as any,
).subscribe((result) => {
expect(authorizationService.isAuthorized).toHaveBeenCalledWith(
FeatureID.CanManageGroup, groupEndpointUrl, undefined
FeatureID.CanManageGroup, groupEndpointUrl, undefined,
);
expect(result).not.toBeTrue();
done();

View File

@@ -1,15 +1,23 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';
import { Observable, of as observableOf } from 'rxjs';
import { FeatureID } from '../../core/data/feature-authorization/feature-id';
import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service';
import { AuthService } from '../../core/auth/auth.service';
import { SomeFeatureAuthorizationGuard } from '../../core/data/feature-authorization/feature-authorization-guard/some-feature-authorization.guard';
import { HALEndpointService } from '../../core/shared/hal-endpoint.service';
import {
ActivatedRouteSnapshot,
Router,
RouterStateSnapshot,
} from '@angular/router';
import {
Observable,
of as observableOf,
} from 'rxjs';
import { map } from 'rxjs/operators';
import { AuthService } from '../../core/auth/auth.service';
import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service';
import { SomeFeatureAuthorizationGuard } from '../../core/data/feature-authorization/feature-authorization-guard/some-feature-authorization.guard';
import { FeatureID } from '../../core/data/feature-authorization/feature-id';
import { HALEndpointService } from '../../core/shared/hal-endpoint.service';
@Injectable({
providedIn: 'root'
providedIn: 'root',
})
export class GroupPageGuard extends SomeFeatureAuthorizationGuard {
@@ -28,7 +36,7 @@ export class GroupPageGuard extends SomeFeatureAuthorizationGuard {
getObjectUrl(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<string> {
return this.halEndpointService.getEndpoint(this.groupsEndpoint).pipe(
map(groupsUrl => `${groupsUrl}/${route?.params?.groupId}`)
map(groupsUrl => `${groupsUrl}/${route?.params?.groupId}`),
);
}

View File

@@ -1,5 +1,6 @@
/* eslint-disable max-classes-per-file */
import { Action } from '@ngrx/store';
import { Group } from '../../core/eperson/models/group.model';
import { type } from '../../shared/ngrx/type';

View File

@@ -1,6 +1,12 @@
import { GroupMock } from '../../shared/testing/group-mock';
import { GroupRegistryCancelGroupAction, GroupRegistryEditGroupAction } from './group-registry.actions';
import { groupRegistryReducer, GroupRegistryState } from './group-registry.reducers';
import {
GroupRegistryCancelGroupAction,
GroupRegistryEditGroupAction,
} from './group-registry.actions';
import {
groupRegistryReducer,
GroupRegistryState,
} from './group-registry.reducers';
const initialState: GroupRegistryState = {
editGroup: null,

View File

@@ -1,5 +1,9 @@
import { Group } from '../../core/eperson/models/group.model';
import { GroupRegistryAction, GroupRegistryActionTypes, GroupRegistryEditGroupAction } from './group-registry.actions';
import {
GroupRegistryAction,
GroupRegistryActionTypes,
GroupRegistryEditGroupAction,
} from './group-registry.actions';
/**
* The metadata registry state.
@@ -27,13 +31,13 @@ export function groupRegistryReducer(state = initialState, action: GroupRegistry
case GroupRegistryActionTypes.EDIT_GROUP: {
return Object.assign({}, state, {
editGroup: (action as GroupRegistryEditGroupAction).group
editGroup: (action as GroupRegistryEditGroupAction).group,
});
}
case GroupRegistryActionTypes.CANCEL_EDIT_GROUP: {
return Object.assign({}, state, {
editGroup: null
editGroup: null,
});
}

View File

@@ -2,17 +2,17 @@
<div class="groups-registry row">
<div class="col-12">
<div class="d-flex justify-content-between border-bottom mb-3">
<h2 id="header" class="pb-2">{{messagePrefix + 'head' | translate}}</h2>
<h1 id="header" class="pb-2">{{messagePrefix + 'head' | translate}}</h1>
<div>
<button class="mr-auto btn btn-success"
[routerLink]="['newGroup']">
[routerLink]="'create'">
<i class="fas fa-plus"></i>
<span class="d-none d-sm-inline ml-1">{{messagePrefix + 'button.add' | translate}}</span>
</button>
</div>
</div>
<h3 id="search" class="border-bottom pb-2">{{messagePrefix + 'search.head' | translate}}</h3>
<h2 id="search" class="border-bottom pb-2">{{messagePrefix + 'search.head' | translate}}</h2>
<form [formGroup]="searchForm" (ngSubmit)="search(searchForm.value)" class="d-flex justify-content-between">
<div class="flex-grow-1 mr-3">
<div class="form-group input-group">
@@ -35,9 +35,8 @@
<ds-themed-loading *ngIf="loading$ | async"></ds-themed-loading>
<ds-pagination
*ngIf="(pageInfoState$ | async)?.totalElements > 0 && !(loading$ | async)"
*ngIf="(pageInfoState$ | async)?.totalElements > 0 && (loading$ | async) !== true"
[paginationOptions]="config"
[pageInfoState]="pageInfoState$"
[collectionSize]="(pageInfoState$ | async)?.totalElements"
[hideGear]="true"
[hidePagerWhenSinglePage]="true">
@@ -91,7 +90,7 @@
</div>
</ds-pagination>
<div *ngIf="(pageInfoState$ | async)?.totalElements == 0" class="alert alert-info w-100 mb-2" role="alert">
<div *ngIf="(pageInfoState$ | async)?.totalElements === 0" class="alert alert-info w-100 mb-2" role="alert">
{{messagePrefix + 'no-items' | translate}}
</div>

View File

@@ -1,39 +1,79 @@
import { CommonModule } from '@angular/common';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, fakeAsync, inject, 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 {
ComponentFixture,
fakeAsync,
inject,
TestBed,
tick,
waitForAsync,
} from '@angular/core/testing';
import {
FormsModule,
ReactiveFormsModule,
} from '@angular/forms';
import {
BrowserModule,
By,
} from '@angular/platform-browser';
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { Observable, of as observableOf } from 'rxjs';
import { provideMockStore } from '@ngrx/store/testing';
import {
TranslateLoader,
TranslateModule,
} from '@ngx-translate/core';
import {
Observable,
of as observableOf,
of,
} from 'rxjs';
import { APP_DATA_SERVICES_MAP } from '../../../config/app-config.interface';
import { DSONameService } from '../../core/breadcrumbs/dso-name.service';
import { ConfigurationDataService } from '../../core/data/configuration-data.service';
import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service';
import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service';
import { buildPaginatedList, PaginatedList } from '../../core/data/paginated-list.model';
import { FeatureID } from '../../core/data/feature-authorization/feature-id';
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';
import { GroupDataService } from '../../core/eperson/group-data.service';
import { EPerson } from '../../core/eperson/models/eperson.model';
import { Group } from '../../core/eperson/models/group.model';
import { PaginationService } from '../../core/pagination/pagination.service';
import { RouteService } from '../../core/services/route.service';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { PageInfo } from '../../core/shared/page-info.model';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { GroupMock, GroupMock2 } from '../../shared/testing/group-mock';
import { GroupsRegistryComponent } from './groups-registry.component';
import { EPersonMock, EPersonMock2 } from '../../shared/testing/eperson.mock';
import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
import { TranslateLoaderMock } from '../../shared/testing/translate-loader.mock';
import { NotificationsServiceStub } from '../../shared/testing/notifications-service.stub';
import { routeServiceStub } from '../../shared/testing/route-service.stub';
import { RouterMock } from '../../shared/mocks/router.mock';
import { PaginationService } from '../../core/pagination/pagination.service';
import { PaginationServiceStub } from '../../shared/testing/pagination-service.stub';
import { FeatureID } from '../../core/data/feature-authorization/feature-id';
import { NoContent } from '../../core/shared/NoContent.model';
import { DSONameService } from '../../core/breadcrumbs/dso-name.service';
import { DSONameServiceMock, UNDEFINED_NAME } from '../../shared/mocks/dso-name.service.mock';
import { PageInfo } from '../../core/shared/page-info.model';
import {
DSONameServiceMock,
UNDEFINED_NAME,
} from '../../shared/mocks/dso-name.service.mock';
import { RouterMock } from '../../shared/mocks/router.mock';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
import { ActivatedRouteStub } from '../../shared/testing/active-router.stub';
import {
EPersonMock,
EPersonMock2,
} from '../../shared/testing/eperson.mock';
import {
GroupMock,
GroupMock2,
} from '../../shared/testing/group-mock';
import { NotificationsServiceStub } from '../../shared/testing/notifications-service.stub';
import { PaginationServiceStub } from '../../shared/testing/pagination-service.stub';
import { routeServiceStub } from '../../shared/testing/route-service.stub';
import { TranslateLoaderMock } from '../../shared/testing/translate-loader.mock';
import { GroupsRegistryComponent } from './groups-registry.component';
describe('GroupsRegistryComponent', () => {
let component: GroupsRegistryComponent;
@@ -42,6 +82,7 @@ describe('GroupsRegistryComponent', () => {
let groupsDataServiceStub: any;
let dsoDataServiceStub: any;
let authorizationService: AuthorizationDataService;
let configurationDataService: jasmine.SpyObj<ConfigurationDataService>;
let mockGroups;
let mockEPeople;
@@ -78,24 +119,24 @@ describe('GroupsRegistryComponent', () => {
elementsPerPage: 1,
totalElements: 0,
totalPages: 0,
currentPage: 1
currentPage: 1,
}), []));
case 'https://dspace.4science.it/dspace-spring-rest/api/eperson/groups/testgroupid/epersons':
return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo({
elementsPerPage: 1,
totalElements: 1,
totalPages: 1,
currentPage: 1
currentPage: 1,
}), [EPersonMock]));
default:
return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo({
elementsPerPage: 1,
totalElements: 0,
totalPages: 0,
currentPage: 1
currentPage: 1,
}), []));
}
}
},
};
groupsDataServiceStub = {
allGroups: mockGroups,
@@ -106,21 +147,21 @@ describe('GroupsRegistryComponent', () => {
elementsPerPage: 1,
totalElements: 0,
totalPages: 0,
currentPage: 1
currentPage: 1,
}), []));
case 'https://dspace.4science.it/dspace-spring-rest/api/eperson/groups/testgroupid/groups':
return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo({
elementsPerPage: 1,
totalElements: 1,
totalPages: 1,
currentPage: 1
currentPage: 1,
}), [GroupMock2]));
default:
return createSuccessfulRemoteDataObject$(buildPaginatedList(new PageInfo({
elementsPerPage: 1,
totalElements: 0,
totalPages: 0,
currentPage: 1
currentPage: 1,
}), []));
}
},
@@ -136,7 +177,7 @@ describe('GroupsRegistryComponent', () => {
elementsPerPage: this.allGroups.length,
totalElements: this.allGroups.length,
totalPages: 1,
currentPage: 1
currentPage: 1,
}), this.allGroups));
}
const result = this.allGroups.find((group: Group) => {
@@ -146,7 +187,7 @@ describe('GroupsRegistryComponent', () => {
elementsPerPage: [result].length,
totalElements: [result].length,
totalPages: 1,
currentPage: 1
currentPage: 1,
}), [result]));
},
delete(objectId: string, copyVirtualMetadata?: string[]): Observable<RemoteData<NoContent>> {
@@ -156,9 +197,13 @@ describe('GroupsRegistryComponent', () => {
dsoDataServiceStub = {
findByHref(href: string): Observable<RemoteData<DSpaceObject>> {
return createSuccessfulRemoteDataObject$(undefined);
}
},
};
configurationDataService = jasmine.createSpyObj('ConfigurationDataService', {
findByPropertyName: of({ payload: { value: 'test' } }),
});
authorizationService = jasmine.createSpyObj('authorizationService', ['isAuthorized']);
setIsAuthorized(true, true);
paginationService = new PaginationServiceStub();
@@ -167,24 +212,26 @@ describe('GroupsRegistryComponent', () => {
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useClass: TranslateLoaderMock
}
}),
],
declarations: [GroupsRegistryComponent],
useClass: TranslateLoaderMock,
},
}), GroupsRegistryComponent],
providers: [GroupsRegistryComponent,
{ provide: DSONameService, useValue: new DSONameServiceMock() },
{ provide: EPersonDataService, useValue: ePersonDataServiceStub },
{ provide: GroupDataService, useValue: groupsDataServiceStub },
{ provide: DSpaceObjectDataService, useValue: dsoDataServiceStub },
{ provide: NotificationsService, useValue: new NotificationsServiceStub() },
{ provide: ConfigurationDataService, useValue: configurationDataService },
{ provide: RouteService, useValue: routeServiceStub },
{ provide: ActivatedRoute, useValue: new ActivatedRouteStub() },
{ provide: Router, useValue: new RouterMock() },
{ provide: AuthorizationDataService, useValue: authorizationService },
{ provide: PaginationService, useValue: paginationService },
{ provide: RequestService, useValue: jasmine.createSpyObj('requestService', ['removeByHrefSubstring']) }
{ provide: RequestService, useValue: jasmine.createSpyObj('requestService', ['removeByHrefSubstring']) },
{ provide: APP_DATA_SERVICES_MAP, useValue: {} },
provideMockStore(),
],
schemas: [NO_ERRORS_SCHEMA]
schemas: [NO_ERRORS_SCHEMA],
}).compileComponents();
}));
@@ -237,16 +284,16 @@ describe('GroupsRegistryComponent', () => {
it('should not check the canManageGroup permissions', () => {
expect(authorizationService.isAuthorized).not.toHaveBeenCalledWith(
FeatureID.CanManageGroup, mockGroups[0].self
FeatureID.CanManageGroup, mockGroups[0].self,
);
expect(authorizationService.isAuthorized).not.toHaveBeenCalledWith(
FeatureID.CanManageGroup, mockGroups[0].self, undefined // treated differently
FeatureID.CanManageGroup, mockGroups[0].self, undefined, // treated differently
);
expect(authorizationService.isAuthorized).not.toHaveBeenCalledWith(
FeatureID.CanManageGroup, mockGroups[1].self
FeatureID.CanManageGroup, mockGroups[1].self,
);
expect(authorizationService.isAuthorized).not.toHaveBeenCalledWith(
FeatureID.CanManageGroup, mockGroups[1].self, undefined // treated differently
FeatureID.CanManageGroup, mockGroups[1].self, undefined, // treated differently
);
});
});

View File

@@ -1,47 +1,94 @@
import { Component, OnDestroy, OnInit } from '@angular/core';
import { UntypedFormBuilder } from '@angular/forms';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import {
AsyncPipe,
NgForOf,
NgIf,
NgSwitch,
NgSwitchCase,
} from '@angular/common';
import {
Component,
OnDestroy,
OnInit,
} from '@angular/core';
import {
ReactiveFormsModule,
UntypedFormBuilder,
} from '@angular/forms';
import {
Router,
RouterLink,
} from '@angular/router';
import { NgbTooltipModule } from '@ng-bootstrap/ng-bootstrap';
import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import {
BehaviorSubject,
combineLatest as observableCombineLatest,
EMPTY,
Observable,
of as observableOf,
Subscription
Subscription,
} from 'rxjs';
import { catchError, defaultIfEmpty, map, switchMap, tap } from 'rxjs/operators';
import {
catchError,
defaultIfEmpty,
map,
switchMap,
tap,
} from 'rxjs/operators';
import { DSONameService } from '../../core/breadcrumbs/dso-name.service';
import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service';
import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service';
import { FeatureID } from '../../core/data/feature-authorization/feature-id';
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';
import { GroupDataService } from '../../core/eperson/group-data.service';
import { EPerson } from '../../core/eperson/models/eperson.model';
import { GroupDtoModel } from '../../core/eperson/models/group-dto.model';
import { Group } from '../../core/eperson/models/group.model';
import { GroupDtoModel } from '../../core/eperson/models/group-dto.model';
import { PaginationService } from '../../core/pagination/pagination.service';
import { RouteService } from '../../core/services/route.service';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { NoContent } from '../../core/shared/NoContent.model';
import {
getAllSucceededRemoteData,
getFirstCompletedRemoteData,
getFirstSucceededRemoteData,
getRemoteDataPayload
getRemoteDataPayload,
} from '../../core/shared/operators';
import { PageInfo } from '../../core/shared/page-info.model';
import { hasValue } from '../../shared/empty.util';
import { ThemedLoadingComponent } from '../../shared/loading/themed-loading.component';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { PaginationComponent } from '../../shared/pagination/pagination.component';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { NoContent } from '../../core/shared/NoContent.model';
import { PaginationService } from '../../core/pagination/pagination.service';
import { followLink } from '../../shared/utils/follow-link-config.model';
import { DSONameService } from '../../core/breadcrumbs/dso-name.service';
@Component({
selector: 'ds-groups-registry',
templateUrl: './groups-registry.component.html',
imports: [
ThemedLoadingComponent,
TranslateModule,
RouterLink,
ReactiveFormsModule,
AsyncPipe,
NgIf,
PaginationComponent,
NgSwitch,
NgSwitchCase,
NgbTooltipModule,
NgForOf,
],
standalone: true,
})
/**
* A component used for managing all existing groups within the repository.
@@ -57,7 +104,7 @@ export class GroupsRegistryComponent implements OnInit, OnDestroy {
config: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), {
id: 'gl',
pageSize: 5,
currentPage: 1
currentPage: 1,
});
/**
@@ -133,7 +180,7 @@ export class GroupsRegistryComponent implements OnInit, OnDestroy {
const query: string = data.query;
if (query != null && this.currentSearchQuery !== query) {
this.currentSearchQuery = query;
this.paginationService.updateRouteWithUrl(this.config.id, [], {page: 1});
this.paginationService.updateRouteWithUrl(this.config.id, [], { page: 1 });
}
return this.groupService.searchGroups(this.currentSearchQuery.trim(), {
currentPage: paginationOptions.currentPage,
@@ -155,19 +202,19 @@ export class GroupsRegistryComponent implements OnInit, OnDestroy {
this.canManageGroup$(isSiteAdmin, group),
this.hasLinkedDSO(group),
this.getSubgroups(group),
this.getMembers(group)
this.getMembers(group),
]).pipe(
map(([canDelete, canManageGroup, hasLinkedDSO, subgroups, members]:
[boolean, boolean, boolean, RemoteData<PaginatedList<Group>>, RemoteData<PaginatedList<EPerson>>]) => {
const groupDtoModel: GroupDtoModel = new GroupDtoModel();
groupDtoModel.ableToDelete = canDelete && !hasLinkedDSO;
groupDtoModel.ableToEdit = canManageGroup;
groupDtoModel.group = group;
groupDtoModel.subgroups = subgroups.payload;
groupDtoModel.epersons = members.payload;
return groupDtoModel;
}
)
const groupDtoModel: GroupDtoModel = new GroupDtoModel();
groupDtoModel.ableToDelete = canDelete && !hasLinkedDSO;
groupDtoModel.ableToEdit = canManageGroup;
groupDtoModel.group = group;
groupDtoModel.subgroups = subgroups.payload;
groupDtoModel.epersons = members.payload;
return groupDtoModel;
},
),
);
} else {
return EMPTY;
@@ -175,9 +222,9 @@ export class GroupsRegistryComponent implements OnInit, OnDestroy {
})]).pipe(defaultIfEmpty([]), map((dtos: GroupDtoModel[]) => {
return buildPaginatedList(groups.pageInfo, dtos);
}));
})
}),
);
})
}),
).subscribe((value: PaginatedList<GroupDtoModel>) => {
this.groupsDto$.next(value);
this.pageInfoState$.next(value.pageInfo);
@@ -185,7 +232,7 @@ export class GroupsRegistryComponent implements OnInit, OnDestroy {
});
this.subs.push(this.searchSub);
}
}
canManageGroup$(isSiteAdmin: boolean, group: Group): Observable<boolean> {
if (isSiteAdmin) {
@@ -210,24 +257,34 @@ export class GroupsRegistryComponent implements OnInit, OnDestroy {
this.translateService.get(this.messagePrefix + 'notification.deleted.failure.title', { name: this.dsoNameService.getName(group.group) }),
this.translateService.get(this.messagePrefix + 'notification.deleted.failure.content', { cause: rd.errorMessage }));
}
});
});
}
}
/**
* Get the members (epersons embedded value of a group)
* NOTE: At this time we only grab the *first* member in order to receive the `totalElements` value
* needed for our HTML template.
* @param group
*/
getMembers(group: Group): Observable<RemoteData<PaginatedList<EPerson>>> {
return this.ePersonDataService.findListByHref(group._links.epersons.href).pipe(getFirstSucceededRemoteData());
return this.ePersonDataService.findListByHref(group._links.epersons.href, {
currentPage: 1,
elementsPerPage: 1,
}).pipe(getFirstSucceededRemoteData());
}
/**
* Get the subgroups (groups embedded value of a group)
* NOTE: At this time we only grab the *first* subgroup in order to receive the `totalElements` value
* needed for our HTML template.
* @param group
*/
getSubgroups(group: Group): Observable<RemoteData<PaginatedList<Group>>> {
return this.groupService.findListByHref(group._links.subgroups.href).pipe(getFirstSucceededRemoteData());
return this.groupService.findListByHref(group._links.subgroups.href, {
currentPage: 1,
elementsPerPage: 1,
}).pipe(getFirstSucceededRemoteData());
}
/**

View File

@@ -1,4 +1,4 @@
<div class="container">
<h2>{{'admin.curation-tasks.header' |translate }}</h2>
<h1>{{'admin.curation-tasks.header' |translate }}</h1>
<ds-curation-form></ds-curation-form>
</div>

View File

@@ -1,7 +1,13 @@
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { AdminCurationTasksComponent } from './admin-curation-tasks.component';
import { TranslateModule } from '@ngx-translate/core';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import {
ComponentFixture,
TestBed,
waitForAsync,
} from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { CurationFormComponent } from '../../curation-form/curation-form.component';
import { AdminCurationTasksComponent } from './admin-curation-tasks.component';
describe('AdminCurationTasksComponent', () => {
let comp: AdminCurationTasksComponent;
@@ -9,10 +15,15 @@ describe('AdminCurationTasksComponent', () => {
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot()],
declarations: [AdminCurationTasksComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
}).compileComponents();
imports: [TranslateModule.forRoot(), AdminCurationTasksComponent],
schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
.overrideComponent(AdminCurationTasksComponent, {
remove: {
imports: [CurationFormComponent],
},
})
.compileComponents();
}));
beforeEach(() => {

View File

@@ -1,4 +1,7 @@
import { Component } from '@angular/core';
import { TranslateModule } from '@ngx-translate/core';
import { CurationFormComponent } from '../../curation-form/curation-form.component';
/**
* Component responsible for rendering the system wide Curation Task UI
@@ -6,6 +9,11 @@ import { Component } from '@angular/core';
@Component({
selector: 'ds-admin-curation-task',
templateUrl: './admin-curation-tasks.component.html',
imports: [
CurationFormComponent,
TranslateModule,
],
standalone: true,
})
export class AdminCurationTasksComponent {

View File

@@ -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>&nbsp;
@@ -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"

View File

@@ -1,22 +1,32 @@
import { ComponentFixture, fakeAsync, TestBed, waitForAsync } from '@angular/core/testing';
import { BatchImportPageComponent } from './batch-import-page.component';
import { NotificationsServiceStub } from '../../shared/testing/notifications-service.stub';
import { createFailedRemoteDataObject$, createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
import { FormsModule } from '@angular/forms';
import { TranslateModule } from '@ngx-translate/core';
import { RouterTestingModule } from '@angular/router/testing';
import { FileValueAccessorDirective } from '../../shared/utils/file-value-accessor.directive';
import { FileValidator } from '../../shared/utils/require-file.validator';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import {
BATCH_IMPORT_SCRIPT_NAME,
ScriptDataService
} from '../../core/data/processes/script-data.service';
import { Router } from '@angular/router';
import { Location } from '@angular/common';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
ComponentFixture,
fakeAsync,
TestBed,
waitForAsync,
} from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { TranslateModule } from '@ngx-translate/core';
import {
BATCH_IMPORT_SCRIPT_NAME,
ScriptDataService,
} from '../../core/data/processes/script-data.service';
import { ProcessParameter } from '../../process-page/processes/process-parameter.model';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import {
createFailedRemoteDataObject$,
createSuccessfulRemoteDataObject$,
} from '../../shared/remote-data.utils';
import { NotificationsServiceStub } from '../../shared/testing/notifications-service.stub';
import { FileDropzoneNoUploaderComponent } from '../../shared/upload/file-dropzone-no-uploader/file-dropzone-no-uploader.component';
import { FileValueAccessorDirective } from '../../shared/utils/file-value-accessor.directive';
import { FileValidator } from '../../shared/utils/require-file.validator';
import { BatchImportPageComponent } from './batch-import-page.component';
describe('BatchImportPageComponent', () => {
let component: BatchImportPageComponent;
@@ -31,14 +41,14 @@ describe('BatchImportPageComponent', () => {
notificationService = new NotificationsServiceStub();
scriptService = jasmine.createSpyObj('scriptService',
{
invoke: createSuccessfulRemoteDataObject$({ processId: '46' })
}
invoke: createSuccessfulRemoteDataObject$({ processId: '46' }),
},
);
router = jasmine.createSpyObj('router', {
navigateByUrl: jasmine.createSpy('navigateByUrl')
navigateByUrl: jasmine.createSpy('navigateByUrl'),
});
locationStub = jasmine.createSpyObj('location', {
back: jasmine.createSpy('back')
back: jasmine.createSpy('back'),
});
}
@@ -48,17 +58,23 @@ describe('BatchImportPageComponent', () => {
imports: [
FormsModule,
TranslateModule.forRoot(),
RouterTestingModule.withRoutes([])
RouterTestingModule.withRoutes([]),
BatchImportPageComponent, FileValueAccessorDirective, FileValidator,
],
declarations: [BatchImportPageComponent, FileValueAccessorDirective, FileValidator],
providers: [
{ provide: NotificationsService, useValue: notificationService },
{ provide: ScriptDataService, useValue: scriptService },
{ provide: Router, useValue: router },
{ provide: Location, useValue: locationStub },
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
schemas: [NO_ERRORS_SCHEMA],
})
.overrideComponent(BatchImportPageComponent, {
remove: {
imports: [FileDropzoneNoUploaderComponent],
},
})
.compileComponents();
}));
beforeEach(() => {
@@ -108,7 +124,7 @@ describe('BatchImportPageComponent', () => {
it('metadata-import script is invoked with --zip fileName and the mockFile', () => {
const parameterValues: ProcessParameter[] = [
Object.assign(new ProcessParameter(), { name: '--add' }),
Object.assign(new ProcessParameter(), { name: '--zip', value: 'filename.zip' })
Object.assign(new ProcessParameter(), { name: '--zip', value: 'filename.zip' }),
];
expect(scriptService.invoke).toHaveBeenCalledWith(BATCH_IMPORT_SCRIPT_NAME, parameterValues, [fileMock]);
});
@@ -181,7 +197,7 @@ describe('BatchImportPageComponent', () => {
it('metadata-import script is invoked with --url and the file url', () => {
const parameterValues: ProcessParameter[] = [
Object.assign(new ProcessParameter(), { name: '--add' }),
Object.assign(new ProcessParameter(), { name: '--url', value: 'example.fileURL.com' })
Object.assign(new ProcessParameter(), { name: '--url', value: 'example.fileURL.com' }),
];
expect(scriptService.invoke).toHaveBeenCalledWith(BATCH_IMPORT_SCRIPT_NAME, parameterValues, [null]);
});

View File

@@ -1,26 +1,48 @@
import { Component } from '@angular/core';
import { Location } from '@angular/common';
import { TranslateService } from '@ngx-translate/core';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { BATCH_IMPORT_SCRIPT_NAME, ScriptDataService } from '../../core/data/processes/script-data.service';
import { Router } from '@angular/router';
import { ProcessParameter } from '../../process-page/processes/process-parameter.model';
import { getFirstCompletedRemoteData } from '../../core/shared/operators';
import { RemoteData } from '../../core/data/remote-data';
import { Process } from '../../process-page/processes/process.model';
import { isEmpty, isNotEmpty } from '../../shared/empty.util';
import { getProcessDetailRoute } from '../../process-page/process-page-routing.paths';
import {
ImportBatchSelectorComponent
} from '../../shared/dso-selector/modal-wrappers/import-batch-selector/import-batch-selector.component';
Location,
NgIf,
} from '@angular/common';
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import { UiSwitchModule } from 'ngx-ui-switch';
import { take } from 'rxjs/operators';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { DSONameService } from '../../core/breadcrumbs/dso-name.service';
import {
BATCH_IMPORT_SCRIPT_NAME,
ScriptDataService,
} from '../../core/data/processes/script-data.service';
import { RemoteData } from '../../core/data/remote-data';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { getFirstCompletedRemoteData } from '../../core/shared/operators';
import { getProcessDetailRoute } from '../../process-page/process-page-routing.paths';
import { Process } from '../../process-page/processes/process.model';
import { ProcessParameter } from '../../process-page/processes/process-parameter.model';
import { ImportBatchSelectorComponent } from '../../shared/dso-selector/modal-wrappers/import-batch-selector/import-batch-selector.component';
import {
isEmpty,
isNotEmpty,
} from '../../shared/empty.util';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { FileDropzoneNoUploaderComponent } from '../../shared/upload/file-dropzone-no-uploader/file-dropzone-no-uploader.component';
@Component({
selector: 'ds-batch-import-page',
templateUrl: './batch-import-page.component.html'
templateUrl: './batch-import-page.component.html',
imports: [
NgIf,
TranslateModule,
FormsModule,
UiSwitchModule,
FileDropzoneNoUploaderComponent,
],
standalone: true,
})
export class BatchImportPageComponent {
/**
@@ -91,7 +113,7 @@ export class BatchImportPageComponent {
}
} else {
const parameterValues: ProcessParameter[] = [
Object.assign(new ProcessParameter(), { name: '--add' })
Object.assign(new ProcessParameter(), { name: '--add' }),
];
if (this.isUpload) {
parameterValues.push(Object.assign(new ProcessParameter(), { name: '--zip', value: this.fileObject.name }));

View File

@@ -1,5 +1,5 @@
<div class="container">
<h2 id="header">{{'admin.metadata-import.page.header' | translate}}</h2>
<h1 id="header">{{'admin.metadata-import.page.header' | translate}}</h1>
<p>{{'admin.metadata-import.page.help' | translate}}</p>
<div class="form-group">
<div class="form-check">

View File

@@ -1,19 +1,32 @@
import { Location } from '@angular/common';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ComponentFixture, fakeAsync, TestBed, waitForAsync } from '@angular/core/testing';
import {
ComponentFixture,
fakeAsync,
TestBed,
waitForAsync,
} from '@angular/core/testing';
import { FormsModule } from '@angular/forms';
import { By } from '@angular/platform-browser';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { TranslateModule } from '@ngx-translate/core';
import { METADATA_IMPORT_SCRIPT_NAME, ScriptDataService } from '../../core/data/processes/script-data.service';
import {
METADATA_IMPORT_SCRIPT_NAME,
ScriptDataService,
} from '../../core/data/processes/script-data.service';
import { ProcessParameter } from '../../process-page/processes/process-parameter.model';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import {
createFailedRemoteDataObject$,
createSuccessfulRemoteDataObject$,
} from '../../shared/remote-data.utils';
import { NotificationsServiceStub } from '../../shared/testing/notifications-service.stub';
import { FileDropzoneNoUploaderComponent } from '../../shared/upload/file-dropzone-no-uploader/file-dropzone-no-uploader.component';
import { FileValueAccessorDirective } from '../../shared/utils/file-value-accessor.directive';
import { FileValidator } from '../../shared/utils/require-file.validator';
import { MetadataImportPageComponent } from './metadata-import-page.component';
import { createFailedRemoteDataObject$, createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
describe('MetadataImportPageComponent', () => {
let comp: MetadataImportPageComponent;
@@ -28,14 +41,14 @@ describe('MetadataImportPageComponent', () => {
notificationService = new NotificationsServiceStub();
scriptService = jasmine.createSpyObj('scriptService',
{
invoke: createSuccessfulRemoteDataObject$({ processId: '45' })
}
invoke: createSuccessfulRemoteDataObject$({ processId: '45' }),
},
);
router = jasmine.createSpyObj('router', {
navigateByUrl: jasmine.createSpy('navigateByUrl')
navigateByUrl: jasmine.createSpy('navigateByUrl'),
});
locationStub = jasmine.createSpyObj('location', {
back: jasmine.createSpy('back')
back: jasmine.createSpy('back'),
});
}
@@ -45,17 +58,23 @@ describe('MetadataImportPageComponent', () => {
imports: [
FormsModule,
TranslateModule.forRoot(),
RouterTestingModule.withRoutes([])
RouterTestingModule.withRoutes([]),
MetadataImportPageComponent, FileValueAccessorDirective, FileValidator,
],
declarations: [MetadataImportPageComponent, FileValueAccessorDirective, FileValidator],
providers: [
{ provide: NotificationsService, useValue: notificationService },
{ provide: ScriptDataService, useValue: scriptService },
{ provide: Router, useValue: router },
{ provide: Location, useValue: locationStub },
],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
schemas: [NO_ERRORS_SCHEMA],
})
.overrideComponent(MetadataImportPageComponent, {
remove: {
imports: [FileDropzoneNoUploaderComponent],
},
})
.compileComponents();
}));
beforeEach(() => {

View File

@@ -1,19 +1,34 @@
import { Location } from '@angular/common';
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { Router } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';
import { METADATA_IMPORT_SCRIPT_NAME, ScriptDataService } from '../../core/data/processes/script-data.service';
import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import {
METADATA_IMPORT_SCRIPT_NAME,
ScriptDataService,
} from '../../core/data/processes/script-data.service';
import { RemoteData } from '../../core/data/remote-data';
import { getFirstCompletedRemoteData } from '../../core/shared/operators';
import { getProcessDetailRoute } from '../../process-page/process-page-routing.paths';
import { Process } from '../../process-page/processes/process.model';
import { ProcessParameter } from '../../process-page/processes/process-parameter.model';
import { isNotEmpty } from '../../shared/empty.util';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { RemoteData } from '../../core/data/remote-data';
import { Process } from '../../process-page/processes/process.model';
import { getFirstCompletedRemoteData } from '../../core/shared/operators';
import { getProcessDetailRoute } from '../../process-page/process-page-routing.paths';
import { FileDropzoneNoUploaderComponent } from '../../shared/upload/file-dropzone-no-uploader/file-dropzone-no-uploader.component';
@Component({
selector: 'ds-metadata-import-page',
templateUrl: './metadata-import-page.component.html'
templateUrl: './metadata-import-page.component.html',
imports: [
TranslateModule,
FormsModule,
FileDropzoneNoUploaderComponent,
],
standalone: true,
})
/**

View File

@@ -0,0 +1,38 @@
import { Routes } from '@angular/router';
import { i18nBreadcrumbResolver } from '../../core/breadcrumbs/i18n-breadcrumb.resolver';
import { navigationBreadcrumbResolver } from '../../core/breadcrumbs/navigation-breadcrumb.resolver';
import { LdnServiceFormComponent } from './ldn-service-form/ldn-service-form.component';
import { LdnServicesOverviewComponent } from './ldn-services-directory/ldn-services-directory.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' },
},
];
export const ROUTES = 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 };
}),
} };
});

View File

@@ -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>&nbsp;{{ 'submission.general.back.submit' | translate }}</span>
</button>
<button class="btn btn-primary" type="submit">
<span><i class="fas fa-save"></i>&nbsp;{{ '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>

View File

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

View File

@@ -0,0 +1,266 @@
import {
ChangeDetectorRef,
EventEmitter,
} from '@angular/core';
import {
ComponentFixture,
fakeAsync,
TestBed,
tick,
} from '@angular/core/testing';
import {
FormArray,
FormBuilder,
FormControl,
FormGroup,
ReactiveFormsModule,
} from '@angular/forms';
import { By } from '@angular/platform-browser';
import {
ActivatedRoute,
Router,
} from '@angular/router';
import {
NgbDropdownModule,
NgbModal,
} from '@ng-bootstrap/ng-bootstrap';
import { provideMockStore } from '@ngrx/store/testing';
import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import { PaginationService } from 'ngx-pagination';
import {
of as observableOf,
of,
} from 'rxjs';
import { RouteService } from '../../../core/services/route.service';
import { MockActivatedRoute } from '../../../shared/mocks/active-router.mock';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
import { RouterStub } from '../../../shared/testing/router.stub';
import { LdnItemfiltersService } from '../ldn-services-data/ldn-itemfilters-data.service';
import { LdnServicesService } from '../ldn-services-data/ldn-services-data.service';
import { LdnServiceFormComponent } from './ldn-service-form.component';
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, 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();
});
});

View File

@@ -0,0 +1,611 @@
import {
animate,
state,
style,
transition,
trigger,
} from '@angular/animations';
import {
AsyncPipe,
NgForOf,
NgIf,
} from '@angular/common';
import {
ChangeDetectorRef,
Component,
OnDestroy,
OnInit,
TemplateRef,
ViewChild,
} from '@angular/core';
import {
FormArray,
FormBuilder,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import {
ActivatedRoute,
Router,
} from '@angular/router';
import {
NgbDropdownModule,
NgbModal,
} from '@ng-bootstrap/ng-bootstrap';
import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import { Operation } from 'fast-json-patch';
import {
combineLatestWith,
Observable,
Subscription,
} from 'rxjs';
import { RemoteData } from 'src/app/core/data/remote-data';
import { FindListOptions } from '../../../core/data/find-list-options.model';
import { PaginatedList } from '../../../core/data/paginated-list.model';
import { PaginationService } from '../../../core/pagination/pagination.service';
import { getFirstCompletedRemoteData } from '../../../core/shared/operators';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { IpV4Validator } from '../../../shared/utils/ipV4.validator';
import { LdnItemfiltersService } from '../ldn-services-data/ldn-itemfilters-data.service';
import { LdnServicesService } from '../ldn-services-data/ldn-services-data.service';
import { LDN_SERVICE } from '../ldn-services-model/ldn-service.resource-type';
import { Itemfilter } from '../ldn-services-model/ldn-service-itemfilters';
import { NotifyServicePattern } from '../ldn-services-model/ldn-service-patterns.model';
import { LdnService } from '../ldn-services-model/ldn-services.model';
import { notifyPatterns } from '../ldn-services-patterns/ldn-service-coar-patterns';
/**
* 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'],
standalone: true,
animations: [
trigger('toggleAnimation', [
state('true', style({})),
state('false', style({})),
transition('true <=> false', animate('300ms ease-in')),
]),
],
imports: [
ReactiveFormsModule,
TranslateModule,
NgIf,
NgbDropdownModule,
NgForOf,
AsyncPipe,
],
})
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');
const 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();
const servicesToUse = this.ldnService.notifyServiceInboundPatterns;
servicesToUse.forEach((patternObj: NotifyServicePattern) => {
const 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 });
}
}

View File

@@ -0,0 +1,115 @@
import {
Observable,
of,
} from 'rxjs';
import { PaginatedList } from '../../../core/data/paginated-list.model';
import { RemoteData } from '../../../core/data/remote-data';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { LDN_SERVICE } from '../ldn-services-model/ldn-service.resource-type';
import { LdnService } from '../ldn-services-model/ldn-services.model';
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>>);

View File

@@ -0,0 +1,93 @@
import {
cold,
getTestScheduler,
} from 'jasmine-marbles';
import { of } from 'rxjs';
import { TestScheduler } from 'rxjs/testing';
import { RemoteDataBuildService } from '../../../core/cache/builders/remote-data-build.service';
import { ObjectCacheService } from '../../../core/cache/object-cache.service';
import { RestResponse } from '../../../core/cache/response.models';
import { FindAllData } from '../../../core/data/base/find-all-data';
import { testFindAllDataImplementation } from '../../../core/data/base/find-all-data.spec';
import { RemoteData } from '../../../core/data/remote-data';
import { RequestService } from '../../../core/data/request.service';
import { RequestEntry } from '../../../core/data/request-entry.model';
import { RequestEntryState } from '../../../core/data/request-entry-state.model';
import { HALEndpointService } from '../../../core/shared/hal-endpoint.service';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { LdnItemfiltersService } from './ldn-itemfilters-data.service';
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();
});
});
});
});

View File

@@ -0,0 +1,60 @@
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { RemoteDataBuildService } from '../../../core/cache/builders/remote-data-build.service';
import { ObjectCacheService } from '../../../core/cache/object-cache.service';
import {
FindAllData,
FindAllDataImpl,
} from '../../../core/data/base/find-all-data';
import { IdentifiableDataService } from '../../../core/data/base/identifiable-data.service';
import { FindListOptions } from '../../../core/data/find-list-options.model';
import { PaginatedList } from '../../../core/data/paginated-list.model';
import { RemoteData } from '../../../core/data/remote-data';
import { RequestService } from '../../../core/data/request.service';
import { HALEndpointService } from '../../../core/shared/hal-endpoint.service';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { FollowLinkConfig } from '../../../shared/utils/follow-link-config.model';
import { Itemfilter } from '../ldn-services-model/ldn-service-itemfilters';
/**
* A service responsible for fetching/sending data from/to the REST API on the itemfilters endpoint
*/
@Injectable({ providedIn: 'root' })
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);
}
}

View File

@@ -0,0 +1,134 @@
import {
cold,
getTestScheduler,
} from 'jasmine-marbles';
import { of as observableOf } from 'rxjs';
import { TestScheduler } from 'rxjs/testing';
import { RemoteDataBuildService } from '../../../core/cache/builders/remote-data-build.service';
import { RequestParam } from '../../../core/cache/models/request-param.model';
import { ObjectCacheService } from '../../../core/cache/object-cache.service';
import { RestResponse } from '../../../core/cache/response.models';
import { CreateData } from '../../../core/data/base/create-data';
import { testCreateDataImplementation } from '../../../core/data/base/create-data.spec';
import { DeleteData } from '../../../core/data/base/delete-data';
import { testDeleteDataImplementation } from '../../../core/data/base/delete-data.spec';
import { FindAllData } from '../../../core/data/base/find-all-data';
import { testFindAllDataImplementation } from '../../../core/data/base/find-all-data.spec';
import { PatchData } from '../../../core/data/base/patch-data';
import { testPatchDataImplementation } from '../../../core/data/base/patch-data.spec';
import { SearchData } from '../../../core/data/base/search-data';
import { testSearchDataImplementation } from '../../../core/data/base/search-data.spec';
import { FindListOptions } from '../../../core/data/find-list-options.model';
import { RemoteData } from '../../../core/data/remote-data';
import { RequestService } from '../../../core/data/request.service';
import { RequestEntry } from '../../../core/data/request-entry.model';
import { RequestEntryState } from '../../../core/data/request-entry-state.model';
import { HALEndpointService } from '../../../core/shared/hal-endpoint.service';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { createPaginatedList } from '../../../shared/testing/utils.test';
import { mockLdnService } from '../ldn-service-serviceMock/ldnServicesRD$-mock';
import { LdnServicesService } from './ldn-services-data.service';
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();
});
});
});
});

View File

@@ -0,0 +1,227 @@
import { Injectable } from '@angular/core';
import { Operation } from 'fast-json-patch';
import { Observable } from 'rxjs';
import {
map,
take,
} from 'rxjs/operators';
import { RemoteDataBuildService } from '../../../core/cache/builders/remote-data-build.service';
import { RequestParam } from '../../../core/cache/models/request-param.model';
import { ObjectCacheService } from '../../../core/cache/object-cache.service';
import {
CreateData,
CreateDataImpl,
} from '../../../core/data/base/create-data';
import {
DeleteData,
DeleteDataImpl,
} from '../../../core/data/base/delete-data';
import {
FindAllData,
FindAllDataImpl,
} from '../../../core/data/base/find-all-data';
import { IdentifiableDataService } from '../../../core/data/base/identifiable-data.service';
import {
PatchData,
PatchDataImpl,
} from '../../../core/data/base/patch-data';
import { SearchDataImpl } from '../../../core/data/base/search-data';
import { ChangeAnalyzer } from '../../../core/data/change-analyzer';
import { FindListOptions } from '../../../core/data/find-list-options.model';
import { PaginatedList } from '../../../core/data/paginated-list.model';
import { RemoteData } from '../../../core/data/remote-data';
import { MultipartPostRequest } from '../../../core/data/request.models';
import { RequestService } from '../../../core/data/request.service';
import { RestRequest } from '../../../core/data/rest-request.model';
import { RestRequestMethod } from '../../../core/data/rest-request-method';
import { HALEndpointService } from '../../../core/shared/hal-endpoint.service';
import { NoContent } from '../../../core/shared/NoContent.model';
import { URLCombiner } from '../../../core/url-combiner/url-combiner';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { FollowLinkConfig } from '../../../shared/utils/follow-link-config.model';
import { LdnServiceConstrain } from '../ldn-services-model/ldn-service.constrain.model';
import { LdnService } from '../ldn-services-model/ldn-services.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({ providedIn: 'root' })
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;
}
}

View File

@@ -0,0 +1,98 @@
<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"
[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>

View File

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

View File

@@ -0,0 +1,190 @@
import {
ChangeDetectorRef,
EventEmitter,
NO_ERRORS_SCHEMA,
} from '@angular/core';
import {
ComponentFixture,
fakeAsync,
TestBed,
tick,
} from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import { of } from 'rxjs';
import { PaginatedList } from '../../../core/data/paginated-list.model';
import { RemoteData } from '../../../core/data/remote-data';
import { PaginationService } from '../../../core/pagination/pagination.service';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { PaginationComponent } from '../../../shared/pagination/pagination.component';
import { createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
import { ActivatedRouteStub } from '../../../shared/testing/active-router.stub';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
import { PaginationServiceStub } from '../../../shared/testing/pagination-service.stub';
import { createPaginatedList } from '../../../shared/testing/utils.test';
import { TruncatableComponent } from '../../../shared/truncatable/truncatable.component';
import { TruncatablePartComponent } from '../../../shared/truncatable/truncatable-part/truncatable-part.component';
import { LdnServicesService } from '../ldn-services-data/ldn-services-data.service';
import { LdnService } from '../ldn-services-model/ldn-services.model';
import { LdnServicesOverviewComponent } from './ldn-services-directory.component';
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(), LdnServicesOverviewComponent],
providers: [
{
provide: LdnServicesService,
useValue: ldnServicesService,
},
{ provide: PaginationService, useValue: paginationService },
{
provide: NgbModal, useValue: {
open: () => {
//
},
},
},
{ provide: ChangeDetectorRef, useValue: {} },
{ provide: NotificationsService, useValue: new NotificationsServiceStub() },
{ provide: TranslateService, useValue: translateServiceStub },
{ provide: ActivatedRoute, useValue: new ActivatedRouteStub() },
],
schemas: [NO_ERRORS_SCHEMA],
})
.overrideComponent(LdnServicesOverviewComponent, {
remove: {
imports: [
PaginationComponent,
TruncatableComponent,
TruncatablePartComponent,
],
},
})
.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();
component.ldnServicesRD$.subscribe((rd) => {
expect(rd.payload.page).toEqual(mockLdnServicesRD.page);
});
}));
});
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();
}));
});
});

View File

@@ -0,0 +1,207 @@
import {
AsyncPipe,
NgClass,
NgFor,
NgIf,
} from '@angular/common';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
OnDestroy,
OnInit,
TemplateRef,
ViewChild,
} from '@angular/core';
import { RouterLink } from '@angular/router';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import { Operation } from 'fast-json-patch';
import {
Observable,
Subscription,
} from 'rxjs';
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 { FindListOptions } from '../../../core/data/find-list-options.model';
import { PaginatedList } from '../../../core/data/paginated-list.model';
import { RemoteData } from '../../../core/data/remote-data';
import { getFirstCompletedRemoteData } from '../../../core/shared/operators';
import { hasValue } from '../../../shared/empty.util';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { PaginationComponent } from '../../../shared/pagination/pagination.component';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { TruncatableComponent } from '../../../shared/truncatable/truncatable.component';
import { TruncatablePartComponent } from '../../../shared/truncatable/truncatable-part/truncatable-part.component';
import { LdnService } from '../ldn-services-model/ldn-services.model';
/**
* 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,
imports: [
NgIf,
NgFor,
TranslateModule,
AsyncPipe,
PaginationComponent,
TruncatableComponent,
TruncatablePartComponent,
NgClass,
RouterLink,
],
standalone: true,
})
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'));
}
},
);
}
}

View File

@@ -0,0 +1,36 @@
import {
autoserialize,
deserialize,
inheritSerialization,
} from 'cerialize';
import { typedObject } from '../../../core/cache/builders/build-decorators';
import { CacheableObject } from '../../../core/cache/cacheable-object.model';
import { ResourceType } from '../../../core/shared/resource-type';
import { excludeFromEquals } from '../../../core/utilities/equals.decorators';
import { LDN_SERVICE_CONSTRAINT_FILTER } from './ldn-service.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;
}
}

View File

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

View File

@@ -0,0 +1,8 @@
/**
* List of services statuses
*/
export enum LdnServiceStatus {
UNKOWN,
DISABLED,
ENABLED,
}

View File

@@ -0,0 +1,3 @@
export class LdnServiceConstrain {
void: any;
}

View File

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

View File

@@ -0,0 +1,77 @@
import {
autoserialize,
deserialize,
deserializeAs,
inheritSerialization,
} from 'cerialize';
import { typedObject } from '../../../core/cache/builders/build-decorators';
import { CacheableObject } from '../../../core/cache/cacheable-object.model';
import { ResourceType } from '../../../core/shared/resource-type';
import { excludeFromEquals } from '../../../core/utilities/equals.decorators';
import { LDN_SERVICE } from './ldn-service.resource-type';
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;
}
}

View File

@@ -0,0 +1,10 @@
/**
* List of parameter types used for scripts
*/
export enum LdnServiceConstrainType {
STRING = 'String',
DATE = 'date',
BOOLEAN = 'boolean',
FILE = 'InputStream',
OUTPUT = 'OutputStream'
}

View File

@@ -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',
];

View File

@@ -0,0 +1,35 @@
import { Injectable } from '@angular/core';
import {
ActivatedRouteSnapshot,
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({ providedIn: 'root' })
export class NotificationsSuggestionTargetsPageResolver {
/**
* 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),
};
}
}

View File

@@ -0,0 +1 @@
<ds-publication-claim [source]="'openaire'"></ds-publication-claim>

View File

@@ -0,0 +1,45 @@
import { CommonModule } from '@angular/common';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
ComponentFixture,
TestBed,
waitForAsync,
} from '@angular/core/testing';
import { TranslateModule } from '@ngx-translate/core';
import { PublicationClaimComponent } from '../../../notifications/suggestion-targets/publication-claim/publication-claim.component';
import { AdminNotificationsPublicationClaimPageComponent } from './admin-notifications-publication-claim-page.component';
describe('AdminNotificationsPublicationClaimPageComponent', () => {
let component: AdminNotificationsPublicationClaimPageComponent;
let fixture: ComponentFixture<AdminNotificationsPublicationClaimPageComponent>;
beforeEach(waitForAsync(() => {
TestBed.configureTestingModule({
imports: [
CommonModule,
TranslateModule.forRoot(),
AdminNotificationsPublicationClaimPageComponent,
],
providers: [
AdminNotificationsPublicationClaimPageComponent,
],
schemas: [NO_ERRORS_SCHEMA],
}).overrideComponent(AdminNotificationsPublicationClaimPageComponent, {
remove: {
imports: [PublicationClaimComponent],
},
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(AdminNotificationsPublicationClaimPageComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,16 @@
import { Component } from '@angular/core';
import { PublicationClaimComponent } from '../../../notifications/suggestion-targets/publication-claim/publication-claim.component';
@Component({
selector: 'ds-admin-notifications-publication-claim-page',
templateUrl: './admin-notifications-publication-claim-page.component.html',
styleUrls: ['./admin-notifications-publication-claim-page.component.scss'],
imports: [
PublicationClaimComponent,
],
standalone: true,
})
export class AdminNotificationsPublicationClaimPageComponent {
}

View File

@@ -0,0 +1,98 @@
import { Route } from '@angular/router';
import { authenticatedGuard } from '../../core/auth/authenticated.guard';
import { i18nBreadcrumbResolver } from '../../core/breadcrumbs/i18n-breadcrumb.resolver';
import { qualityAssuranceBreadcrumbResolver } from '../../core/breadcrumbs/quality-assurance-breadcrumb.resolver';
import { AdminNotificationsPublicationClaimPageResolver } from '../../quality-assurance-notifications-pages/notifications-suggestion-targets-page/notifications-suggestion-targets-page-resolver.service';
import { QualityAssuranceEventsPageComponent } from '../../quality-assurance-notifications-pages/quality-assurance-events-page/quality-assurance-events-page.component';
import { qualityAssuranceEventsPageResolver } from '../../quality-assurance-notifications-pages/quality-assurance-events-page/quality-assurance-events-page.resolver';
import { qualityAssuranceSourceDataResolver } from '../../quality-assurance-notifications-pages/quality-assurance-source-page-component/quality-assurance-source-data.resolver';
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 { 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 { AdminNotificationsPublicationClaimPageComponent } from './admin-notifications-publication-claim-page/admin-notifications-publication-claim-page.component';
import {
PUBLICATION_CLAIMS_PATH,
QUALITY_ASSURANCE_EDIT_PATH,
} from './admin-notifications-routing-paths';
export const ROUTES: Route[] = [
{
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: QualityAssuranceTopicsPageComponent,
pathMatch: 'full',
resolve: {
breadcrumb: qualityAssuranceBreadcrumbResolver,
openaireQualityAssuranceTopicsParams: QualityAssuranceTopicsPageResolver,
},
data: {
title: 'admin.quality-assurance.page.title',
breadcrumbKey: 'admin.quality-assurance',
showBreadcrumbsFluid: false,
},
},
{
canActivate: [ authenticatedGuard ],
path: `${QUALITY_ASSURANCE_EDIT_PATH}/:sourceId/target/:targetId`,
component: QualityAssuranceTopicsPageComponent,
pathMatch: 'full',
resolve: {
breadcrumb: i18nBreadcrumbResolver,
openaireQualityAssuranceTopicsParams: QualityAssuranceTopicsPageResolver,
},
data: {
title: 'admin.quality-assurance.page.title',
breadcrumbKey: 'admin.quality-assurance',
showBreadcrumbsFluid: false,
},
},
{
canActivate: [authenticatedGuard],
path: `${QUALITY_ASSURANCE_EDIT_PATH}`,
component: QualityAssuranceSourcePageComponent,
pathMatch: 'full',
resolve: {
breadcrumb: i18nBreadcrumbResolver,
openaireQualityAssuranceSourceParams: QualityAssuranceSourcePageResolver,
sourceData: qualityAssuranceSourceDataResolver,
},
data: {
title: 'admin.notifications.source.breadcrumbs',
breadcrumbKey: 'admin.notifications.source',
showBreadcrumbsFluid: false,
},
},
{
canActivate: [authenticatedGuard],
path: `${QUALITY_ASSURANCE_EDIT_PATH}/:sourceId/:topicId`,
component: QualityAssuranceEventsPageComponent,
pathMatch: 'full',
resolve: {
breadcrumb: qualityAssuranceBreadcrumbResolver,
openaireQualityAssuranceEventsParams: qualityAssuranceEventsPageResolver,
},
data: {
title: 'admin.notifications.event.page.title',
breadcrumbKey: 'admin.notifications.event',
showBreadcrumbsFluid: false,
},
},
];

View File

@@ -0,0 +1,7 @@
export const QUALITY_ASSURANCE_EDIT_PATH = 'quality-assurance';
export const PUBLICATION_CLAIMS_PATH = 'publication-claim';
export function getQualityAssuranceEditRoute() {
return `/${QUALITY_ASSURANCE_EDIT_PATH}`;
}

View File

@@ -0,0 +1,51 @@
import {
mapToCanActivate,
Route,
} from '@angular/router';
import { i18nBreadcrumbResolver } from '../../core/breadcrumbs/i18n-breadcrumb.resolver';
import { notifyInfoGuard } from '../../core/coar-notify/notify-info/notify-info.guard';
import { SiteAdministratorGuard } from '../../core/data/feature-authorization/feature-authorization-guard/site-administrator.guard';
import { AdminNotifyDashboardComponent } from './admin-notify-dashboard.component';
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';
export const ROUTES: Route[] = [
{
canActivate: [...mapToCanActivate([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: [...mapToCanActivate([SiteAdministratorGuard]), notifyInfoGuard],
data: {
title: 'admin.notify.dashboard.page.title',
breadcrumbKey: 'admin.notify.dashboard',
},
},
{
path: 'outbound',
resolve: {
breadcrumb: i18nBreadcrumbResolver,
},
component: AdminNotifyOutgoingComponent,
canActivate: [...mapToCanActivate([SiteAdministratorGuard]), notifyInfoGuard],
data: {
title: 'admin.notify.dashboard.page.title',
breadcrumbKey: 'admin.notify.dashboard',
},
},
];

View File

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

View File

@@ -0,0 +1,71 @@
import { NO_ERRORS_SCHEMA } from '@angular/core';
import {
ComponentFixture,
TestBed,
} from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { NgbNavModule } from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';
import { buildPaginatedList } from '../../core/data/paginated-list.model';
import { SearchService } from '../../core/shared/search/search.service';
import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils';
import { ActivatedRouteStub } from '../../shared/testing/active-router.stub';
import { AdminNotifyDashboardComponent } from './admin-notify-dashboard.component';
import { AdminNotifyMetricsComponent } from './admin-notify-metrics/admin-notify-metrics.component';
import { AdminNotifyMessage } from './models/admin-notify-message.model';
import { AdminNotifySearchResult } from './models/admin-notify-message-search-result.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, AdminNotifyDashboardComponent],
providers: [
{ provide: SearchService, useValue: { search: () => createSuccessfulRemoteDataObject$(results) } },
{ provide: ActivatedRoute, useValue: new ActivatedRouteStub() },
],
schemas: [NO_ERRORS_SCHEMA],
}).overrideComponent(AdminNotifyDashboardComponent, {
remove: {
imports: [AdminNotifyMetricsComponent],
},
})
.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();
});
});

View File

@@ -0,0 +1,119 @@
import {
AsyncPipe,
NgIf,
} from '@angular/common';
import {
Component,
OnInit,
} from '@angular/core';
import { RouterLink } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
import {
forkJoin,
Observable,
} from 'rxjs';
import { map } from 'rxjs/operators';
import { environment } from '../../../environments/environment';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { getFirstCompletedRemoteData } from '../../core/shared/operators';
import { SearchService } from '../../core/shared/search/search.service';
import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service';
import { SEARCH_CONFIG_SERVICE } from '../../my-dspace-page/my-dspace-configuration.service';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { PaginatedSearchOptions } from '../../shared/search/models/paginated-search-options.model';
import { SearchObjects } from '../../shared/search/models/search-objects.model';
import { AdminNotifyMetricsComponent } from './admin-notify-metrics/admin-notify-metrics.component';
import {
AdminNotifyMetricsBox,
AdminNotifyMetricsRow,
} from './admin-notify-metrics/admin-notify-metrics.model';
@Component({
selector: 'ds-admin-notify-dashboard',
templateUrl: './admin-notify-dashboard.component.html',
providers: [
{
provide: SEARCH_CONFIG_SERVICE,
useClass: SearchConfigurationService,
},
],
standalone: true,
imports: [
AdminNotifyMetricsComponent,
RouterLink,
NgIf,
TranslateModule,
AsyncPipe,
],
})
/**
* 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)),
};
});
}
}

View File

@@ -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">&times;</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>

View File

@@ -0,0 +1,38 @@
import {
ComponentFixture,
TestBed,
} from '@angular/core/testing';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import { TranslateModule } from '@ngx-translate/core';
import { AdminNotifyDetailModalComponent } from './admin-notify-detail-modal.component';
describe('AdminNotifyDetailModalComponent', () => {
let component: AdminNotifyDetailModalComponent;
let fixture: ComponentFixture<AdminNotifyDetailModalComponent>;
const modalStub = jasmine.createSpyObj('modalStub', ['close']);
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [TranslateModule.forRoot(), 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);
});
});

View File

@@ -0,0 +1,68 @@
import {
NgForOf,
NgIf,
} from '@angular/common';
import {
Component,
EventEmitter,
Input,
Output,
} from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
import {
TranslateModule,
TranslateService,
} from '@ngx-translate/core';
import { fadeIn } from '../../../shared/animations/fade';
import { MissingTranslationHelper } from '../../../shared/translate/missing-translation.helper';
import { AdminNotifyMessage } from '../models/admin-notify-message.model';
@Component({
selector: 'ds-admin-notify-detail-modal',
templateUrl: './admin-notify-detail-modal.component.html',
animations: [
fadeIn,
],
standalone: true,
imports: [
NgForOf,
TranslateModule,
NgIf,
],
})
/**
* 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;
}
}

View File

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

View File

@@ -0,0 +1,65 @@
import {
ComponentFixture,
TestBed,
} from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { provideMockStore } from '@ngrx/store/testing';
import { TranslateModule } from '@ngx-translate/core';
import { APP_DATA_SERVICES_MAP } from '../../../../../config/app-config.interface';
import { RemoteDataBuildService } from '../../../../core/cache/builders/remote-data-build.service';
import { RequestService } from '../../../../core/data/request.service';
import { RouteService } from '../../../../core/services/route.service';
import { HALEndpointService } from '../../../../core/shared/hal-endpoint.service';
import { SearchConfigurationService } from '../../../../core/shared/search/search-configuration.service';
import { SEARCH_CONFIG_SERVICE } from '../../../../my-dspace-page/my-dspace-configuration.service';
import { MockActivatedRoute } from '../../../../shared/mocks/active-router.mock';
import { getMockRemoteDataBuildService } from '../../../../shared/mocks/remote-data-build.service.mock';
import { routeServiceStub } from '../../../../shared/testing/route-service.stub';
import { AdminNotifyLogsResultComponent } from '../admin-notify-logs-result/admin-notify-logs-result.component';
import { AdminNotifyIncomingComponent } from './admin-notify-incoming.component';
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(), 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 },
{ provide: APP_DATA_SERVICES_MAP, useValue: {} },
provideMockStore({}),
],
}).overrideComponent(AdminNotifyIncomingComponent, {
remove: { imports: [AdminNotifyLogsResultComponent] },
})
.compileComponents();
fixture = TestBed.createComponent(AdminNotifyIncomingComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,31 @@
import {
Component,
Inject,
} from '@angular/core';
import { RouterLink } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
import { SearchConfigurationService } from '../../../../core/shared/search/search-configuration.service';
import { SEARCH_CONFIG_SERVICE } from '../../../../my-dspace-page/my-dspace-configuration.service';
import { AdminNotifyLogsResultComponent } from '../admin-notify-logs-result/admin-notify-logs-result.component';
@Component({
selector: 'ds-admin-notify-incoming',
templateUrl: './admin-notify-incoming.component.html',
providers: [
{
provide: SEARCH_CONFIG_SERVICE,
useClass: SearchConfigurationService,
},
],
standalone: true,
imports: [
RouterLink,
AdminNotifyLogsResultComponent,
TranslateModule,
],
})
export class AdminNotifyIncomingComponent {
constructor(@Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService) {
}
}

View File

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

View File

@@ -0,0 +1,66 @@
import {
ComponentFixture,
TestBed,
} from '@angular/core/testing';
import {
ActivatedRoute,
Router,
} from '@angular/router';
import { provideMockStore } from '@ngrx/store/testing';
import { TranslateModule } from '@ngx-translate/core';
import { APP_DATA_SERVICES_MAP } from '../../../../../config/app-config.interface';
import { RemoteDataBuildService } from '../../../../core/cache/builders/remote-data-build.service';
import { ObjectCacheService } from '../../../../core/cache/object-cache.service';
import { RequestService } from '../../../../core/data/request.service';
import { RouteService } from '../../../../core/services/route.service';
import { HALEndpointService } from '../../../../core/shared/hal-endpoint.service';
import { MockActivatedRoute } from '../../../../shared/mocks/active-router.mock';
import { SearchLabelsComponent } from '../../../../shared/search/search-labels/search-labels.component';
import { ThemedSearchComponent } from '../../../../shared/search/themed-search.component';
import { routeServiceStub } from '../../../../shared/testing/route-service.stub';
import { RouterStub } from '../../../../shared/testing/router.stub';
import { AdminNotifyLogsResultComponent } from './admin-notify-logs-result.component';
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(), 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: APP_DATA_SERVICES_MAP, useValue: {} },
{ provide: RemoteDataBuildService, useValue: rdbService },
provideMockStore({}),
],
})
.overrideComponent(AdminNotifyLogsResultComponent, {
remove: {
imports: [
SearchLabelsComponent,
ThemedSearchComponent,
],
},
})
.compileComponents();
fixture = TestBed.createComponent(AdminNotifyLogsResultComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,99 @@
import {
AsyncPipe,
NgIf,
} from '@angular/common';
import {
ChangeDetectorRef,
Component,
Inject,
Input,
OnInit,
} from '@angular/core';
import {
ActivatedRoute,
ActivatedRouteSnapshot,
Router,
} from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Context } from '../../../../core/shared/context.model';
import { SearchConfigurationService } from '../../../../core/shared/search/search-configuration.service';
import { ViewMode } from '../../../../core/shared/view-mode.model';
import { SEARCH_CONFIG_SERVICE } from '../../../../my-dspace-page/my-dspace-configuration.service';
import { SearchLabelsComponent } from '../../../../shared/search/search-labels/search-labels.component';
import { ThemedSearchComponent } from '../../../../shared/search/themed-search.component';
@Component({
selector: 'ds-admin-notify-logs-result',
templateUrl: './admin-notify-logs-result.component.html',
providers: [
{
provide: SEARCH_CONFIG_SERVICE,
useClass: SearchConfigurationService,
},
],
standalone: true,
imports: [
SearchLabelsComponent,
ThemedSearchComponent,
AsyncPipe,
TranslateModule,
NgIf,
],
})
/**
* 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('/');
}
}

View File

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

View File

@@ -0,0 +1,65 @@
import {
ComponentFixture,
TestBed,
} from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { provideMockStore } from '@ngrx/store/testing';
import { TranslateModule } from '@ngx-translate/core';
import { APP_DATA_SERVICES_MAP } from '../../../../../config/app-config.interface';
import { RemoteDataBuildService } from '../../../../core/cache/builders/remote-data-build.service';
import { RequestService } from '../../../../core/data/request.service';
import { RouteService } from '../../../../core/services/route.service';
import { HALEndpointService } from '../../../../core/shared/hal-endpoint.service';
import { SearchConfigurationService } from '../../../../core/shared/search/search-configuration.service';
import { SEARCH_CONFIG_SERVICE } from '../../../../my-dspace-page/my-dspace-configuration.service';
import { MockActivatedRoute } from '../../../../shared/mocks/active-router.mock';
import { getMockRemoteDataBuildService } from '../../../../shared/mocks/remote-data-build.service.mock';
import { routeServiceStub } from '../../../../shared/testing/route-service.stub';
import { AdminNotifyLogsResultComponent } from '../admin-notify-logs-result/admin-notify-logs-result.component';
import { AdminNotifyOutgoingComponent } from './admin-notify-outgoing.component';
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()],
providers: [
{ provide: SEARCH_CONFIG_SERVICE, useValue: SearchConfigurationService },
{ provide: APP_DATA_SERVICES_MAP, useValue: {} },
{ provide: RouteService, useValue: routeServiceStub },
{ provide: ActivatedRoute, useValue: new MockActivatedRoute() },
{ provide: HALEndpointService, useValue: halService },
{ provide: RequestService, useValue: requestService },
{ provide: RemoteDataBuildService, useValue: rdbService },
provideMockStore({}),
],
})
.overrideComponent(AdminNotifyOutgoingComponent, {
remove: { imports: [AdminNotifyLogsResultComponent] },
})
.compileComponents();
fixture = TestBed.createComponent(AdminNotifyOutgoingComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@@ -0,0 +1,31 @@
import {
Component,
Inject,
} from '@angular/core';
import { RouterLink } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
import { SearchConfigurationService } from '../../../../core/shared/search/search-configuration.service';
import { SEARCH_CONFIG_SERVICE } from '../../../../my-dspace-page/my-dspace-configuration.service';
import { AdminNotifyLogsResultComponent } from '../admin-notify-logs-result/admin-notify-logs-result.component';
@Component({
selector: 'ds-admin-notify-outgoing',
templateUrl: './admin-notify-outgoing.component.html',
providers: [
{
provide: SEARCH_CONFIG_SERVICE,
useClass: SearchConfigurationService,
},
],
standalone: true,
imports: [
RouterLink,
AdminNotifyLogsResultComponent,
TranslateModule,
],
})
export class AdminNotifyOutgoingComponent {
constructor(@Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService) {
}
}

View File

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

View File

@@ -0,0 +1,73 @@
import {
ComponentFixture,
TestBed,
} from '@angular/core/testing';
import { Router } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
import { ViewMode } from '../../../core/shared/view-mode.model';
import { RouterStub } from '../../../shared/testing/router.stub';
import { AdminNotifyMetricsComponent } from './admin-notify-metrics.component';
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(), 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);
});
});

View File

@@ -0,0 +1,66 @@
import { NgForOf } from '@angular/common';
import {
Component,
Input,
} from '@angular/core';
import { Router } from '@angular/router';
import { TranslateModule } from '@ngx-translate/core';
import { ViewMode } from '../../../core/shared/view-mode.model';
import { NotificationBoxComponent } from '../../../shared/notification-box/notification-box.component';
import { AdminNotifyMetricsRow } from './admin-notify-metrics.model';
@Component({
selector: 'ds-admin-notify-metrics',
templateUrl: './admin-notify-metrics.component.html',
standalone: true,
imports: [
NotificationBoxComponent,
TranslateModule,
NgForOf,
],
})
/**
* 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,
},
});
}
}

View File

@@ -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[]
}

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