diff --git a/src/app/+admin/admin-registries/admin-registries-routing.module.ts b/src/app/+admin/admin-registries/admin-registries-routing.module.ts index afdc46bf17..8833b307b9 100644 --- a/src/app/+admin/admin-registries/admin-registries-routing.module.ts +++ b/src/app/+admin/admin-registries/admin-registries-routing.module.ts @@ -4,6 +4,7 @@ import { NgModule } from '@angular/core'; import { MetadataSchemaComponent } from './metadata-schema/metadata-schema.component'; import { URLCombiner } from '../../core/url-combiner/url-combiner'; import { getRegistriesModulePath } from '../admin-routing.module'; +import { I18nBreadcrumbResolver } from '../../core/breadcrumbs/i18n-breadcrumb.resolver'; const BITSTREAMFORMATS_MODULE_PATH = 'bitstream-formats'; @@ -14,16 +15,28 @@ export function getBitstreamFormatsModulePath() { @NgModule({ imports: [ RouterModule.forChild([ - {path: 'metadata', component: MetadataRegistryComponent, data: {title: 'admin.registries.metadata.title'}}, { - path: 'metadata/:schemaName', - component: MetadataSchemaComponent, - data: {title: 'admin.registries.schema.title'} + path: 'metadata', + resolve: { breadcrumb: I18nBreadcrumbResolver }, + data: {title: 'admin.registries.metadata.title', breadcrumbKey: 'admin.registries.metadata'}, + children: [ + { + path: '', + component: MetadataRegistryComponent + }, + { + path: ':schemaName', + resolve: { breadcrumb: I18nBreadcrumbResolver }, + component: MetadataSchemaComponent, + data: {title: 'admin.registries.schema.title', breadcrumbKey: 'admin.registries.schema'} + } + ] }, { path: BITSTREAMFORMATS_MODULE_PATH, + resolve: { breadcrumb: I18nBreadcrumbResolver }, loadChildren: './bitstream-formats/bitstream-formats.module#BitstreamFormatsModule', - data: {title: 'admin.registries.bitstream-formats.title'} + data: {title: 'admin.registries.bitstream-formats.title', breadcrumbKey: 'admin.registries.bitstream-formats'} }, ]) ] diff --git a/src/app/+admin/admin-registries/bitstream-formats/bitstream-formats-routing.module.ts b/src/app/+admin/admin-registries/bitstream-formats/bitstream-formats-routing.module.ts index 67f6aa373e..2f08f8257c 100644 --- a/src/app/+admin/admin-registries/bitstream-formats/bitstream-formats-routing.module.ts +++ b/src/app/+admin/admin-registries/bitstream-formats/bitstream-formats-routing.module.ts @@ -4,6 +4,7 @@ import { BitstreamFormatsResolver } from './bitstream-formats.resolver'; import { EditBitstreamFormatComponent } from './edit-bitstream-format/edit-bitstream-format.component'; import { BitstreamFormatsComponent } from './bitstream-formats.component'; import { AddBitstreamFormatComponent } from './add-bitstream-format/add-bitstream-format.component'; +import { I18nBreadcrumbResolver } from '../../../core/breadcrumbs/i18n-breadcrumb.resolver'; const BITSTREAMFORMAT_EDIT_PATH = ':id/edit'; const BITSTREAMFORMAT_ADD_PATH = 'add'; @@ -17,14 +18,18 @@ const BITSTREAMFORMAT_ADD_PATH = 'add'; }, { path: BITSTREAMFORMAT_ADD_PATH, + resolve: { breadcrumb: I18nBreadcrumbResolver }, component: AddBitstreamFormatComponent, + data: {breadcrumbKey: 'admin.registries.bitstream-formats.create'} }, { path: BITSTREAMFORMAT_EDIT_PATH, component: EditBitstreamFormatComponent, resolve: { - bitstreamFormat: BitstreamFormatsResolver - } + bitstreamFormat: BitstreamFormatsResolver, + breadcrumb: I18nBreadcrumbResolver + }, + data: {breadcrumbKey: 'admin.registries.bitstream-formats.edit'} }, ]) ], diff --git a/src/app/+admin/admin-registries/metadata-registry/metadata-registry.component.html b/src/app/+admin/admin-registries/metadata-registry/metadata-registry.component.html index a254f20428..42b7558397 100644 --- a/src/app/+admin/admin-registries/metadata-registry/metadata-registry.component.html +++ b/src/app/+admin/admin-registries/metadata-registry/metadata-registry.component.html @@ -11,7 +11,6 @@ = new BehaviorSubject(true); + constructor(private registryService: RegistryService, private notificationsService: NotificationsService, private router: Router, @@ -50,14 +57,17 @@ export class MetadataRegistryComponent { */ onPageChange(event) { this.config.currentPage = event; - this.updateSchemas(); + this.forceUpdateSchemas(); } /** * Update the list of schemas by fetching it from the rest api or cache */ private updateSchemas() { - this.metadataSchemas = this.registryService.getMetadataSchemas(this.config); + this.metadataSchemas = this.needsUpdate$.pipe( + filter((update) => update === true), + switchMap(() => this.registryService.getMetadataSchemas(toFindListOptions(this.config))) + ); } /** @@ -65,8 +75,7 @@ export class MetadataRegistryComponent { * a new REST call */ public forceUpdateSchemas() { - this.registryService.clearMetadataSchemaRequests().subscribe(); - this.updateSchemas(); + this.needsUpdate$.next(true); } /** @@ -125,6 +134,7 @@ export class MetadataRegistryComponent { * Delete all the selected metadata schemas */ deleteSchemas() { + this.registryService.clearMetadataSchemaRequests().subscribe(); this.registryService.getSelectedMetadataSchemas().pipe(take(1)).subscribe( (schemas) => { const tasks$ = []; diff --git a/src/app/+admin/admin-registries/metadata-registry/metadata-schema-form/metadata-schema-form.component.spec.ts b/src/app/+admin/admin-registries/metadata-registry/metadata-schema-form/metadata-schema-form.component.spec.ts index db2294ab59..a840d68dcf 100644 --- a/src/app/+admin/admin-registries/metadata-registry/metadata-schema-form/metadata-schema-form.component.spec.ts +++ b/src/app/+admin/admin-registries/metadata-registry/metadata-schema-form/metadata-schema-form.component.spec.ts @@ -21,7 +21,8 @@ describe('MetadataSchemaFormComponent', () => { const registryServiceStub = { getActiveMetadataSchema: () => observableOf(undefined), createOrUpdateMetadataSchema: (schema: MetadataSchema) => observableOf(schema), - cancelEditMetadataSchema: () => {} + cancelEditMetadataSchema: () => {}, + clearMetadataSchemaRequests: () => observableOf(undefined) }; const formBuilderServiceStub = { createFormGroup: () => { diff --git a/src/app/+admin/admin-registries/metadata-registry/metadata-schema-form/metadata-schema-form.component.ts b/src/app/+admin/admin-registries/metadata-registry/metadata-schema-form/metadata-schema-form.component.ts index 23e7309a00..79129d68a4 100644 --- a/src/app/+admin/admin-registries/metadata-registry/metadata-schema-form/metadata-schema-form.component.ts +++ b/src/app/+admin/admin-registries/metadata-registry/metadata-schema-form/metadata-schema-form.component.ts @@ -128,6 +128,7 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy { * Emit the updated/created schema using the EventEmitter submitForm */ onSubmit() { + this.registryService.clearMetadataSchemaRequests().subscribe(); this.registryService.getActiveMetadataSchema().pipe(take(1)).subscribe( (schema) => { const values = { @@ -139,7 +140,7 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy { this.submitForm.emit(newSchema); }); } else { - this.registryService.createOrUpdateMetadataSchema(Object.assign(new MetadataSchema(), { + this.registryService.createOrUpdateMetadataSchema(Object.assign(new MetadataSchema(), schema, { id: schema.id, prefix: (values.prefix ? values.prefix : schema.prefix), namespace: (values.namespace ? values.namespace : schema.namespace) @@ -148,6 +149,7 @@ export class MetadataSchemaFormComponent implements OnInit, OnDestroy { }); } this.clearFields(); + this.registryService.cancelEditMetadataSchema(); } ); } diff --git a/src/app/+admin/admin-registries/metadata-schema/metadata-field-form/metadata-field-form.component.spec.ts b/src/app/+admin/admin-registries/metadata-schema/metadata-field-form/metadata-field-form.component.spec.ts index 402f9c0c86..98128a6a61 100644 --- a/src/app/+admin/admin-registries/metadata-schema/metadata-field-form/metadata-field-form.component.spec.ts +++ b/src/app/+admin/admin-registries/metadata-schema/metadata-field-form/metadata-field-form.component.spec.ts @@ -30,6 +30,7 @@ describe('MetadataFieldFormComponent', () => { createOrUpdateMetadataField: (field: MetadataField) => observableOf(field), cancelEditMetadataField: () => {}, cancelEditMetadataSchema: () => {}, + clearMetadataFieldRequests: () => observableOf(undefined) }; const formBuilderServiceStub = { createFormGroup: () => { diff --git a/src/app/+admin/admin-registries/metadata-schema/metadata-field-form/metadata-field-form.component.ts b/src/app/+admin/admin-registries/metadata-schema/metadata-field-form/metadata-field-form.component.ts index 0811530343..42f6441791 100644 --- a/src/app/+admin/admin-registries/metadata-schema/metadata-field-form/metadata-field-form.component.ts +++ b/src/app/+admin/admin-registries/metadata-schema/metadata-field-form/metadata-field-form.component.ts @@ -153,6 +153,7 @@ export class MetadataFieldFormComponent implements OnInit, OnDestroy { * Emit the updated/created field using the EventEmitter submitForm */ onSubmit() { + this.registryService.clearMetadataFieldRequests().subscribe(); this.registryService.getActiveMetadataField().pipe(take(1)).subscribe( (field) => { const values = { @@ -166,7 +167,7 @@ export class MetadataFieldFormComponent implements OnInit, OnDestroy { this.submitForm.emit(newField); }); } else { - this.registryService.createOrUpdateMetadataField(Object.assign(new MetadataField(), { + this.registryService.createOrUpdateMetadataField(Object.assign(new MetadataField(), field, { id: field.id, schema: this.metadataSchema, element: (values.element ? values.element : field.element), @@ -177,6 +178,7 @@ export class MetadataFieldFormComponent implements OnInit, OnDestroy { }); } this.clearFields(); + this.registryService.cancelEditMetadataField(); } ); } diff --git a/src/app/+admin/admin-registries/metadata-schema/metadata-schema.component.html b/src/app/+admin/admin-registries/metadata-schema/metadata-schema.component.html index 4a7a4cf34d..49ef748349 100644 --- a/src/app/+admin/admin-registries/metadata-schema/metadata-schema.component.html +++ b/src/app/+admin/admin-registries/metadata-schema/metadata-schema.component.html @@ -1,36 +1,37 @@
{ it('should not call deleteAndReturnResponse on the bitstreamService for the unmarked field', () => { expect(bitstreamService.deleteAndReturnResponse).not.toHaveBeenCalledWith(bitstream1.id); }); + }); - it('should send out a patch for the move operations', () => { + describe('when dropBitstream is called', () => { + const event = { + fromIndex: 0, + toIndex: 50, + // tslint:disable-next-line:no-empty + finish: () => {} + }; + + beforeEach(() => { + comp.dropBitstream(bundle, event); + }); + + it('should send out a patch for the move operation', () => { expect(bundleService.patch).toHaveBeenCalled(); }); }); diff --git a/src/app/+item-page/edit-item-page/item-bitstreams/item-bitstreams.component.ts b/src/app/+item-page/edit-item-page/item-bitstreams/item-bitstreams.component.ts index 009cc978b2..45b8e23108 100644 --- a/src/app/+item-page/edit-item-page/item-bitstreams/item-bitstreams.component.ts +++ b/src/app/+item-page/edit-item-page/item-bitstreams/item-bitstreams.component.ts @@ -1,6 +1,6 @@ -import { ChangeDetectorRef, Component, Inject, OnDestroy } from '@angular/core'; +import { ChangeDetectorRef, Component, NgZone, OnDestroy } from '@angular/core'; import { AbstractItemUpdateComponent } from '../abstract-item-update/abstract-item-update.component'; -import { filter, map, switchMap, take, tap } from 'rxjs/operators'; +import { filter, map, switchMap, take } from 'rxjs/operators'; import { Observable } from 'rxjs/internal/Observable'; import { Subscription } from 'rxjs/internal/Subscription'; import { ItemDataService } from '../../../core/data/item-data.service'; @@ -9,8 +9,8 @@ import { ActivatedRoute, Router } from '@angular/router'; import { NotificationsService } from '../../../shared/notifications/notifications.service'; import { TranslateService } from '@ngx-translate/core'; import { BitstreamDataService } from '../../../core/data/bitstream-data.service'; -import { hasValue, isNotEmpty, isNotEmptyOperator } from '../../../shared/empty.util'; -import { zip as observableZip, combineLatest as observableCombineLatest, of as observableOf } from 'rxjs'; +import { hasValue, isNotEmpty } from '../../../shared/empty.util'; +import { zip as observableZip, of as observableOf } from 'rxjs'; import { ErrorResponse, RestResponse } from '../../../core/cache/response.models'; import { ObjectCacheService } from '../../../core/cache/object-cache.service'; import { RequestService } from '../../../core/data/request.service'; @@ -22,8 +22,6 @@ import { Bundle } from '../../../core/shared/bundle.model'; import { FieldUpdate, FieldUpdates } from '../../../core/data/object-updates/object-updates.reducer'; import { Bitstream } from '../../../core/shared/bitstream.model'; import { FieldChangeType } from '../../../core/data/object-updates/object-updates.actions'; -import { Operation } from 'fast-json-patch'; -import { MoveOperation } from 'fast-json-patch/lib/core'; import { BundleDataService } from '../../../core/data/bundle-data.service'; import { PaginatedSearchOptions } from '../../../shared/search/paginated-search-options.model'; import { ResponsiveColumnSizes } from '../../../shared/responsive-table-sizes/responsive-column-sizes'; @@ -90,7 +88,8 @@ export class ItemBitstreamsComponent extends AbstractItemUpdateComponent impleme public objectCache: ObjectCacheService, public requestService: RequestService, public cdRef: ChangeDetectorRef, - public bundleService: BundleDataService + public bundleService: BundleDataService, + public zone: NgZone ) { super(itemService, objectUpdatesService, router, notificationsService, translateService, route); } @@ -143,7 +142,6 @@ export class ItemBitstreamsComponent extends AbstractItemUpdateComponent impleme /** * Submit the current changes - * Bitstreams that were dragged around send out a patch request with move operations to the rest API * Bitstreams marked as deleted send out a delete request to the rest API * Display notifications and reset the current item/updates */ @@ -151,32 +149,6 @@ export class ItemBitstreamsComponent extends AbstractItemUpdateComponent impleme this.submitting = true; const bundlesOnce$ = this.bundles$.pipe(take(1)); - // Fetch all move operations for each bundle - const moveOperations$ = bundlesOnce$.pipe( - switchMap((bundles: Bundle[]) => observableZip(...bundles.map((bundle: Bundle) => - this.objectUpdatesService.getMoveOperations(bundle.self).pipe( - take(1), - map((operations: MoveOperation[]) => [...operations.map((operation: MoveOperation) => Object.assign(operation, { - from: `/_links/bitstreams${operation.from}/href`, - path: `/_links/bitstreams${operation.path}/href` - }))]) - ) - ))) - ); - - // Send out an immediate patch request for each bundle - const patchResponses$ = observableCombineLatest(bundlesOnce$, moveOperations$).pipe( - switchMap(([bundles, moveOperationList]: [Bundle[], Operation[][]]) => - observableZip(...bundles.map((bundle: Bundle, index: number) => { - if (isNotEmpty(moveOperationList[index])) { - return this.bundleService.patch(bundle, moveOperationList[index]); - } else { - return observableOf(undefined); - } - })) - ) - ); - // Fetch all removed bitstreams from the object update service const removedBitstreams$ = bundlesOnce$.pipe( switchMap((bundles: Bundle[]) => observableZip( @@ -201,19 +173,42 @@ export class ItemBitstreamsComponent extends AbstractItemUpdateComponent impleme ); // Perform the setup actions from above in order and display notifications - patchResponses$.pipe( - switchMap((responses: RestResponse[]) => { - this.displayNotifications('item.edit.bitstreams.notifications.move', responses); - return removedResponses$ - }), - take(1) - ).subscribe((responses: RestResponse[]) => { + removedResponses$.pipe(take(1)).subscribe((responses: RestResponse[]) => { this.displayNotifications('item.edit.bitstreams.notifications.remove', responses); this.reset(); this.submitting = false; }); } + /** + * A bitstream was dropped in a new location. Send out a Move Patch request to the REST API, display notifications, + * refresh the bundle's cache (so the lists can properly reload) and call the event's callback function (which will + * navigate the user to the correct page) + * @param bundle The bundle to send patch requests to + * @param event The event containing the index the bitstream came from and was dropped to + */ + dropBitstream(bundle: Bundle, event: any) { + this.zone.runOutsideAngular(() => { + if (hasValue(event) && hasValue(event.fromIndex) && hasValue(event.toIndex) && hasValue(event.finish)) { + const moveOperation = Object.assign({ + op: 'move', + from: `/_links/bitstreams/${event.fromIndex}/href`, + path: `/_links/bitstreams/${event.toIndex}/href` + }); + this.bundleService.patch(bundle, [moveOperation]).pipe(take(1)).subscribe((response: RestResponse) => { + this.zone.run(() => { + this.displayNotifications('item.edit.bitstreams.notifications.move', [response]); + // Remove all cached requests from this bundle and call the event's callback when the requests are cleared + this.requestService.removeByHrefSubstring(bundle.self).pipe( + filter((isCached) => isCached), + take(1) + ).subscribe(() => event.finish()); + }); + }); + } + }); + } + /** * Display notifications * - Error notification for each failed response with their message diff --git a/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component.html b/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component.html index 58273bb931..c28ef9b525 100644 --- a/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component.html +++ b/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component.html @@ -17,5 +17,5 @@
- + diff --git a/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component.ts b/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component.ts index 115e326241..72e2055bf7 100644 --- a/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component.ts +++ b/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/item-edit-bitstream-bundle.component.ts @@ -1,4 +1,4 @@ -import { Component, Input, OnInit, ViewChild, ViewContainerRef } from '@angular/core'; +import { Component, EventEmitter, Input, OnInit, Output, ViewChild, ViewContainerRef } from '@angular/core'; import { Bundle } from '../../../../core/shared/bundle.model'; import { Item } from '../../../../core/shared/item.model'; import { ResponsiveColumnSizes } from '../../../../shared/responsive-table-sizes/responsive-column-sizes'; @@ -36,6 +36,13 @@ export class ItemEditBitstreamBundleComponent implements OnInit { */ @Input() columnSizes: ResponsiveTableSizes; + /** + * Send an event when the user drops an object on the pagination + * The event contains details about the index the object came from and is dropped to (across the entirety of the list, + * not just within a single page) + */ + @Output() dropObject: EventEmitter = new EventEmitter(); + /** * The bootstrap sizes used for the Bundle Name column * This column stretches over the first 3 columns and thus is a combination of their sizes processed in ngOnInit diff --git a/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/paginated-drag-and-drop-bitstream-list/paginated-drag-and-drop-bitstream-list.component.html b/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/paginated-drag-and-drop-bitstream-list/paginated-drag-and-drop-bitstream-list.component.html index 25941f472e..9197b89796 100644 --- a/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/paginated-drag-and-drop-bitstream-list/paginated-drag-and-drop-bitstream-list.component.html +++ b/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/paginated-drag-and-drop-bitstream-list/paginated-drag-and-drop-bitstream-list.component.html @@ -7,24 +7,29 @@ [collectionSize]="(objectsRD$ | async)?.payload?.totalElements" [disableRouteParameterUpdate]="true" (pageChange)="switchPage($event)"> -
-
+
+ +
- -
- + +
+ +
+
-
+
-
+ + diff --git a/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/paginated-drag-and-drop-bitstream-list/paginated-drag-and-drop-bitstream-list.component.spec.ts b/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/paginated-drag-and-drop-bitstream-list/paginated-drag-and-drop-bitstream-list.component.spec.ts index 03d1d00520..118f2b1619 100644 --- a/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/paginated-drag-and-drop-bitstream-list/paginated-drag-and-drop-bitstream-list.component.spec.ts +++ b/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/paginated-drag-and-drop-bitstream-list/paginated-drag-and-drop-bitstream-list.component.spec.ts @@ -16,12 +16,15 @@ import { ResponsiveTableSizes } from '../../../../../shared/responsive-table-siz import { ResponsiveColumnSizes } from '../../../../../shared/responsive-table-sizes/responsive-column-sizes'; import { createSuccessfulRemoteDataObject$ } from '../../../../../shared/remote-data.utils'; import { createPaginatedList } from '../../../../../shared/testing/utils.test'; +import { RequestService } from '../../../../../core/data/request.service'; describe('PaginatedDragAndDropBitstreamListComponent', () => { let comp: PaginatedDragAndDropBitstreamListComponent; let fixture: ComponentFixture; let objectUpdatesService: ObjectUpdatesService; let bundleService: BundleDataService; + let objectValuesPipe: ObjectValuesPipe; + let requestService: RequestService; const columnSizes = new ResponsiveTableSizes([ new ResponsiveColumnSizes(2, 2, 3, 4, 4), @@ -97,15 +100,24 @@ describe('PaginatedDragAndDropBitstreamListComponent', () => { ); bundleService = jasmine.createSpyObj('bundleService', { - getBitstreams: createSuccessfulRemoteDataObject$(createPaginatedList([bitstream1, bitstream2])) + getBitstreams: createSuccessfulRemoteDataObject$(createPaginatedList([bitstream1, bitstream2])), + getBitstreamsEndpoint: observableOf('') + }); + + objectValuesPipe = new ObjectValuesPipe(); + + requestService = jasmine.createSpyObj('requestService', { + hasByHrefObservable: observableOf(true) }); TestBed.configureTestingModule({ imports: [TranslateModule.forRoot()], - declarations: [PaginatedDragAndDropBitstreamListComponent, VarDirective, ObjectValuesPipe], + declarations: [PaginatedDragAndDropBitstreamListComponent, VarDirective], providers: [ { provide: ObjectUpdatesService, useValue: objectUpdatesService }, - { provide: BundleDataService, useValue: bundleService } + { provide: BundleDataService, useValue: bundleService }, + { provide: ObjectValuesPipe, useValue: objectValuesPipe }, + { provide: RequestService, useValue: requestService } ], schemas: [ NO_ERRORS_SCHEMA ] diff --git a/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/paginated-drag-and-drop-bitstream-list/paginated-drag-and-drop-bitstream-list.component.ts b/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/paginated-drag-and-drop-bitstream-list/paginated-drag-and-drop-bitstream-list.component.ts index 5548da4029..a288e9993a 100644 --- a/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/paginated-drag-and-drop-bitstream-list/paginated-drag-and-drop-bitstream-list.component.ts +++ b/src/app/+item-page/edit-item-page/item-bitstreams/item-edit-bitstream-bundle/paginated-drag-and-drop-bitstream-list/paginated-drag-and-drop-bitstream-list.component.ts @@ -8,6 +8,8 @@ import { switchMap } from 'rxjs/operators'; import { PaginatedSearchOptions } from '../../../../../shared/search/paginated-search-options.model'; import { ResponsiveTableSizes } from '../../../../../shared/responsive-table-sizes/responsive-table-sizes'; import { followLink } from '../../../../../shared/utils/follow-link-config.model'; +import { ObjectValuesPipe } from '../../../../../shared/utils/object-values-pipe'; +import { RequestService } from '../../../../../core/data/request.service'; @Component({ selector: 'ds-paginated-drag-and-drop-bitstream-list', @@ -33,8 +35,10 @@ export class PaginatedDragAndDropBitstreamListComponent extends AbstractPaginate constructor(protected objectUpdatesService: ObjectUpdatesService, protected elRef: ElementRef, - protected bundleService: BundleDataService) { - super(objectUpdatesService, elRef); + protected objectValuesPipe: ObjectValuesPipe, + protected bundleService: BundleDataService, + protected requestService: RequestService) { + super(objectUpdatesService, elRef, objectValuesPipe); } ngOnInit() { @@ -46,11 +50,17 @@ export class PaginatedDragAndDropBitstreamListComponent extends AbstractPaginate */ initializeObjectsRD(): void { this.objectsRD$ = this.currentPage$.pipe( - switchMap((page: number) => this.bundleService.getBitstreams( - this.bundle.id, - new PaginatedSearchOptions({pagination: Object.assign({}, this.options, { currentPage: page })}), - followLink('format') - )) + switchMap((page: number) => { + const paginatedOptions = new PaginatedSearchOptions({pagination: Object.assign({}, this.options, { currentPage: page })}); + return this.bundleService.getBitstreamsEndpoint(this.bundle.id, paginatedOptions).pipe( + switchMap((href) => this.requestService.hasByHrefObservable(href)), + switchMap(() => this.bundleService.getBitstreams( + this.bundle.id, + paginatedOptions, + followLink('format') + )) + ); + }) ); } diff --git a/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.html b/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.html index 911ba26b31..4809f206ae 100644 --- a/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.html +++ b/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.html @@ -7,9 +7,9 @@
diff --git a/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.spec.ts b/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.spec.ts index ac9eea6c0c..16b50d18f0 100644 --- a/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.spec.ts +++ b/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.spec.ts @@ -1,5 +1,5 @@ import { ChangeDetectorRef, Component, NO_ERRORS_SCHEMA } from '@angular/core'; -import { async, ComponentFixture, inject, TestBed } from '@angular/core/testing'; +import { async, ComponentFixture, inject, TestBed, tick, fakeAsync } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { Store } from '@ngrx/store'; @@ -21,6 +21,8 @@ import { NotificationsServiceStub } from '../../shared/testing/notifications-ser import { SharedModule } from '../../shared/shared.module'; import { getMockScrollToService } from '../../shared/mocks/scroll-to-service.mock'; import { UploaderService } from '../../shared/uploader/uploader.service'; +import { By } from '@angular/platform-browser'; +import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; describe('MyDSpaceNewSubmissionComponent test', () => { @@ -54,6 +56,11 @@ describe('MyDSpaceNewSubmissionComponent test', () => { { provide: ScrollToService, useValue: getMockScrollToService() }, { provide: Store, useValue: store }, { provide: TranslateService, useValue: translateService }, + { + provide: NgbModal, useValue: { + open: () => {/*comment*/} + } + }, ChangeDetectorRef, MyDSpaceNewSubmissionComponent, UploaderService @@ -86,6 +93,25 @@ describe('MyDSpaceNewSubmissionComponent test', () => { })); }); + describe('', () => { + let fixture: ComponentFixture; + let comp: MyDSpaceNewSubmissionComponent; + + beforeEach(() => { + fixture = TestBed.createComponent(MyDSpaceNewSubmissionComponent); + comp = fixture.componentInstance; + }); + + it('should call app.openDialog', () => { + spyOn(comp, 'openDialog'); + const submissionButton = fixture.debugElement.query(By.css('button.btn-primary')); + submissionButton.triggerEventHandler('click', { + preventDefault: () => {/**/ + } + }); + expect(comp.openDialog).toHaveBeenCalled(); + }); + }); }); // declare a test component diff --git a/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.ts b/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.ts index 81d66bb5f7..8d20a5736a 100644 --- a/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.ts +++ b/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.ts @@ -15,6 +15,9 @@ import { HALEndpointService } from '../../core/shared/hal-endpoint.service'; import { NotificationType } from '../../shared/notifications/models/notification-type'; import { hasValue } from '../../shared/empty.util'; import { SearchResult } from '../../shared/search/search-result.model'; +import { Router } from '@angular/router'; +import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; +import { CreateItemParentSelectorComponent } from 'src/app/shared/dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component'; /** * This component represents the whole mydspace page header @@ -55,7 +58,9 @@ export class MyDSpaceNewSubmissionComponent implements OnDestroy, OnInit { private halService: HALEndpointService, private notificationsService: NotificationsService, private store: Store, - private translate: TranslateService) { + private translate: TranslateService, + private router: Router, + private modalService: NgbModal) { } /** @@ -105,6 +110,14 @@ export class MyDSpaceNewSubmissionComponent implements OnDestroy, OnInit { this.notificationsService.error(null, this.translate.get('mydspace.upload.upload-failed')); } + /** + * Method called on clicking the button "New Submition", It opens a dialog for + * select a collection. + */ + openDialog() { + this.modalService.open(CreateItemParentSelectorComponent); + } + /** * Unsubscribe from the subscription */ diff --git a/src/app/core/breadcrumbs/i18n-breadcrumb.resolver.spec.ts b/src/app/core/breadcrumbs/i18n-breadcrumb.resolver.spec.ts index d34d6d8a9b..a06abdc816 100644 --- a/src/app/core/breadcrumbs/i18n-breadcrumb.resolver.spec.ts +++ b/src/app/core/breadcrumbs/i18n-breadcrumb.resolver.spec.ts @@ -14,7 +14,7 @@ describe('I18nBreadcrumbResolver', () => { }); it('should resolve the breadcrumb config', () => { - const resolvedConfig = resolver.resolve({ data: { breadcrumbKey: i18nKey }, url: [path] } as any, {} as any); + const resolvedConfig = resolver.resolve({ data: { breadcrumbKey: i18nKey }, url: [path], pathFromRoot: [{ url: [path] }] } as any, {} as any); const expectedConfig = { provider: i18nBreadcrumbService, key: i18nKey, url: path }; expect(resolvedConfig).toEqual(expectedConfig); }); diff --git a/src/app/core/breadcrumbs/i18n-breadcrumb.resolver.ts b/src/app/core/breadcrumbs/i18n-breadcrumb.resolver.ts index 1b8c5bcbd1..a6298628c7 100644 --- a/src/app/core/breadcrumbs/i18n-breadcrumb.resolver.ts +++ b/src/app/core/breadcrumbs/i18n-breadcrumb.resolver.ts @@ -25,7 +25,17 @@ export class I18nBreadcrumbResolver implements Resolve> if (hasNoValue(key)) { throw new Error('You provided an i18nBreadcrumbResolver for url \"' + route.url + '\" but no breadcrumbKey in the route\'s data') } - const fullPath = route.url.join(''); + const fullPath = this.getResolvedUrl(route); return { provider: this.breadcrumbService, key: key, url: fullPath }; } + + /** + * Resolve the full URL of an ActivatedRouteSnapshot + * @param route + */ + getResolvedUrl(route: ActivatedRouteSnapshot): string { + return route.pathFromRoot + .map((v) => v.url.map((segment) => segment.toString()).join('/')) + .join('/'); + } } diff --git a/src/app/core/cache/response.models.ts b/src/app/core/cache/response.models.ts index 88125606f7..dc7af65c8d 100644 --- a/src/app/core/cache/response.models.ts +++ b/src/app/core/cache/response.models.ts @@ -6,9 +6,6 @@ import { ConfigObject } from '../config/models/config.model'; import { FacetValue } from '../../shared/search/facet-value.model'; import { SearchFilterConfig } from '../../shared/search/search-filter-config.model'; import { IntegrationModel } from '../integration/models/integration.model'; -import { RegistryMetadataschemasResponse } from '../registry/registry-metadataschemas-response.model'; -import { RegistryMetadatafieldsResponse } from '../registry/registry-metadatafields-response.model'; -import { RegistryBitstreamformatsResponse } from '../registry/registry-bitstreamformats-response.model'; import { PaginatedList } from '../data/paginated-list'; import { SubmissionObject } from '../submission/models/submission-object.model'; import { DSpaceObject } from '../shared/dspace-object.model'; @@ -41,48 +38,6 @@ export class DSOSuccessResponse extends RestResponse { } } -/** - * A successful response containing a list of MetadataSchemas wrapped in a RegistryMetadataschemasResponse - */ -export class RegistryMetadataschemasSuccessResponse extends RestResponse { - constructor( - public metadataschemasResponse: RegistryMetadataschemasResponse, - public statusCode: number, - public statusText: string, - public pageInfo?: PageInfo - ) { - super(true, statusCode, statusText); - } -} - -/** - * A successful response containing a list of MetadataFields wrapped in a RegistryMetadatafieldsResponse - */ -export class RegistryMetadatafieldsSuccessResponse extends RestResponse { - constructor( - public metadatafieldsResponse: RegistryMetadatafieldsResponse, - public statusCode: number, - public statusText: string, - public pageInfo?: PageInfo - ) { - super(true, statusCode, statusText); - } -} - -/** - * A successful response containing a list of BitstreamFormats wrapped in a RegistryBitstreamformatsResponse - */ -export class RegistryBitstreamformatsSuccessResponse extends RestResponse { - constructor( - public bitstreamformatsResponse: RegistryBitstreamformatsResponse, - public statusCode: number, - public statusText: string, - public pageInfo?: PageInfo - ) { - super(true, statusCode, statusText); - } -} - /** * A successful response containing exactly one MetadataSchema */ diff --git a/src/app/core/core.module.ts b/src/app/core/core.module.ts index c5e16e7b73..300d33fda8 100644 --- a/src/app/core/core.module.ts +++ b/src/app/core/core.module.ts @@ -69,13 +69,8 @@ import { ItemDataService } from './data/item-data.service'; import { LicenseDataService } from './data/license-data.service'; import { LookupRelationService } from './data/lookup-relation.service'; import { MappedCollectionsReponseParsingService } from './data/mapped-collections-reponse-parsing.service'; -import { MetadatafieldParsingService } from './data/metadatafield-parsing.service'; -import { MetadataschemaParsingService } from './data/metadataschema-parsing.service'; import { MyDSpaceResponseParsingService } from './data/mydspace-response-parsing.service'; import { ObjectUpdatesService } from './data/object-updates/object-updates.service'; -import { RegistryBitstreamformatsResponseParsingService } from './data/registry-bitstreamformats-response-parsing.service'; -import { RegistryMetadatafieldsResponseParsingService } from './data/registry-metadatafields-response-parsing.service'; -import { RegistryMetadataschemasResponseParsingService } from './data/registry-metadataschemas-response-parsing.service'; import { RelationshipTypeService } from './data/relationship-type.service'; import { RelationshipService } from './data/relationship.service'; import { ResourcePolicyService } from './resource-policy/resource-policy.service'; @@ -145,8 +140,9 @@ import { Version } from './shared/version.model'; import { VersionHistory } from './shared/version-history.model'; import { WorkflowActionDataService } from './data/workflow-action-data.service'; import { WorkflowAction } from './tasks/models/workflow-action-object.model'; -import { EpersonRegistrationService } from './data/eperson-registration.service'; import { Registration } from './shared/registration.model'; +import { MetadataSchemaDataService } from './data/metadata-schema-data.service'; +import { MetadataFieldDataService } from './data/metadata-field-data.service'; /** * When not in production, endpoint responses can be mocked for testing purposes @@ -203,9 +199,6 @@ const PROVIDERS = [ FacetValueResponseParsingService, FacetValueMapResponseParsingService, FacetConfigResponseParsingService, - RegistryMetadataschemasResponseParsingService, - RegistryMetadatafieldsResponseParsingService, - RegistryBitstreamformatsResponseParsingService, MappedCollectionsReponseParsingService, DebugResponseParsingService, SearchResponseParsingService, @@ -225,8 +218,6 @@ const PROVIDERS = [ JsonPatchOperationsBuilder, AuthorityService, IntegrationResponseParsingService, - MetadataschemaParsingService, - MetadatafieldParsingService, UploaderService, UUIDService, NotificationsService, @@ -266,6 +257,8 @@ const PROVIDERS = [ LicenseDataService, ItemTypeDataService, WorkflowActionDataService, + MetadataSchemaDataService, + MetadataFieldDataService, // register AuthInterceptor as HttpInterceptor { provide: HTTP_INTERCEPTORS, diff --git a/src/app/core/data/bundle-data.service.ts b/src/app/core/data/bundle-data.service.ts index 160ea0ff0d..de0e8a4337 100644 --- a/src/app/core/data/bundle-data.service.ts +++ b/src/app/core/data/bundle-data.service.ts @@ -88,10 +88,12 @@ export class BundleDataService extends DataService { /** * Get the bitstreams endpoint for a bundle * @param bundleId + * @param searchOptions */ - getBitstreamsEndpoint(bundleId: string): Observable { + getBitstreamsEndpoint(bundleId: string, searchOptions?: PaginatedSearchOptions): Observable { return this.getBrowseEndpoint().pipe( - switchMap((href: string) => this.halService.getEndpoint(this.bitstreamsEndpoint, `${href}/${bundleId}`)) + switchMap((href: string) => this.halService.getEndpoint(this.bitstreamsEndpoint, `${href}/${bundleId}`)), + map((href) => searchOptions ? searchOptions.toRestUrl(href) : href) ); } @@ -102,9 +104,8 @@ export class BundleDataService extends DataService { * @param linksToFollow The {@link FollowLinkConfig}s for the request */ getBitstreams(bundleId: string, searchOptions?: PaginatedSearchOptions, ...linksToFollow: Array>): Observable>> { - const hrefObs = this.getBitstreamsEndpoint(bundleId).pipe( - map((href) => searchOptions ? searchOptions.toRestUrl(href) : href) - ); + const hrefObs = this.getBitstreamsEndpoint(bundleId, searchOptions); + hrefObs.pipe( take(1) ).subscribe((href) => { diff --git a/src/app/core/data/collection-data.service.spec.ts b/src/app/core/data/collection-data.service.spec.ts index eb3dabf195..7087655a26 100644 --- a/src/app/core/data/collection-data.service.spec.ts +++ b/src/app/core/data/collection-data.service.spec.ts @@ -13,13 +13,19 @@ import { RequestEntry } from './request.reducer'; import { ErrorResponse, RestResponse } from '../cache/response.models'; import { ObjectCacheService } from '../cache/object-cache.service'; import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; +import { Collection } from '../shared/collection.model'; +import { PageInfo } from '../shared/page-info.model'; +import { PaginatedList } from './paginated-list'; +import { createSuccessfulRemoteDataObject } from 'src/app/shared/remote-data.utils'; +import { hot, getTestScheduler, cold } from 'jasmine-marbles'; +import { TestScheduler } from 'rxjs/testing'; const url = 'fake-url'; const collectionId = 'fake-collection-id'; describe('CollectionDataService', () => { let service: CollectionDataService; - + let scheduler: TestScheduler; let requestService: RequestService; let translate: TranslateService; let notificationsService: any; @@ -27,6 +33,44 @@ describe('CollectionDataService', () => { let objectCache: ObjectCacheService; let halService: any; + const mockCollection1: Collection = Object.assign(new Collection(), { + id: 'test-collection-1-1', + name: 'test-collection-1', + _links: { + self: { + href: 'https://rest.api/collections/test-collection-1-1' + } + } + }); + + const mockCollection2: Collection = Object.assign(new Collection(), { + id: 'test-collection-2-2', + name: 'test-collection-2', + _links: { + self: { + href: 'https://rest.api/collections/test-collection-2-2' + } + } + }); + + const mockCollection3: Collection = Object.assign(new Collection(), { + id: 'test-collection-3-3', + name: 'test-collection-3', + _links: { + self: { + href: 'https://rest.api/collections/test-collection-3-3' + } + } + }); + + const queryString = 'test-string'; + const communityId = '8b3c613a-5a4b-438b-9686-be1d5b4a1c5a'; + + const pageInfo = new PageInfo(); + const array = [mockCollection1, mockCollection2, mockCollection3]; + const paginatedList = new PaginatedList(pageInfo, array); + const paginatedListRD = createSuccessfulRemoteDataObject(paginatedList); + describe('when the requests are successful', () => { beforeEach(() => { createService(); @@ -74,6 +118,43 @@ describe('CollectionDataService', () => { }); }); + describe('when calling getAuthorizedCollection', () => { + beforeEach(() => { + scheduler = getTestScheduler(); + spyOn(service, 'getAuthorizedCollection').and.callThrough(); + spyOn(service, 'getAuthorizedCollectionByCommunity').and.callThrough(); + }); + + it('should proxy the call to getAuthorizedCollection', () => { + scheduler.schedule(() => service.getAuthorizedCollection(queryString)); + scheduler.flush(); + + expect(service.getAuthorizedCollection).toHaveBeenCalledWith(queryString); + }); + + it('should return a RemoteData> for the getAuthorizedCollection', () => { + const result = service.getAuthorizedCollection(queryString) + const expected = cold('a|', { + a: paginatedListRD + }); + expect(result).toBeObservable(expected); + }); + + it('should proxy the call to getAuthorizedCollectionByCommunity', () => { + scheduler.schedule(() => service.getAuthorizedCollectionByCommunity(communityId, queryString)); + scheduler.flush(); + + expect(service.getAuthorizedCollectionByCommunity).toHaveBeenCalledWith(communityId, queryString); + }); + + it('should return a RemoteData> for the getAuthorizedCollectionByCommunity', () => { + const result = service.getAuthorizedCollectionByCommunity(communityId, queryString) + const expected = cold('a|', { + a: paginatedListRD + }); + expect(result).toBeObservable(expected); + }); + }); }); describe('when the requests are unsuccessful', () => { @@ -117,7 +198,9 @@ describe('CollectionDataService', () => { function createService(requestEntry$?) { requestService = getMockRequestService(requestEntry$); rdbService = jasmine.createSpyObj('rdbService', { - buildList: jasmine.createSpy('buildList') + buildList: hot('a|', { + a: paginatedListRD + }) }); objectCache = jasmine.createSpyObj('objectCache', { remove: jasmine.createSpy('remove') diff --git a/src/app/core/data/collection-data.service.ts b/src/app/core/data/collection-data.service.ts index 0639a7d8ca..41f70dd31c 100644 --- a/src/app/core/data/collection-data.service.ts +++ b/src/app/core/data/collection-data.service.ts @@ -72,14 +72,18 @@ export class CollectionDataService extends ComColDataService { /** * Get all collections the user is authorized to submit to * + * @param query limit the returned collection to those with metadata values matching the query terms. * @param options The [[FindListOptions]] object * @return Observable>> * collection list */ - getAuthorizedCollection(options: FindListOptions = {}): Observable>> { - const searchHref = 'findAuthorized'; + getAuthorizedCollection(query: string, options: FindListOptions = {}, ...linksToFollow: Array>): Observable>> { + const searchHref = 'findSubmitAuthorized'; + options = Object.assign({}, options, { + searchParams: [new RequestParam('query', query)] + }); - return this.searchBy(searchHref, options).pipe( + return this.searchBy(searchHref, options, ...linksToFollow).pipe( filter((collections: RemoteData>) => !collections.isResponsePending)); } @@ -87,14 +91,18 @@ export class CollectionDataService extends ComColDataService { * Get all collections the user is authorized to submit to, by community * * @param communityId The community id + * @param query limit the returned collection to those with metadata values matching the query terms. * @param options The [[FindListOptions]] object * @return Observable>> * collection list */ - getAuthorizedCollectionByCommunity(communityId: string, options: FindListOptions = {}): Observable>> { - const searchHref = 'findAuthorizedByCommunity'; + getAuthorizedCollectionByCommunity(communityId: string, query: string, options: FindListOptions = {}): Observable>> { + const searchHref = 'findSubmitAuthorizedByCommunity'; options = Object.assign({}, options, { - searchParams: [new RequestParam('uuid', communityId)] + searchParams: [ + new RequestParam('uuid', communityId), + new RequestParam('query', query) + ] }); return this.searchBy(searchHref, options).pipe( @@ -108,7 +116,7 @@ export class CollectionDataService extends ComColDataService { * true if the user has at least one collection to submit to */ hasAuthorizedCollection(): Observable { - const searchHref = 'findAuthorized'; + const searchHref = 'findSubmitAuthorized'; const options = new FindListOptions(); options.elementsPerPage = 1; diff --git a/src/app/core/data/data.service.ts b/src/app/core/data/data.service.ts index ca59daa5af..7f77d72d3a 100644 --- a/src/app/core/data/data.service.ts +++ b/src/app/core/data/data.service.ts @@ -45,11 +45,12 @@ import { FindListOptions, FindListRequest, GetRequest, - PatchRequest + PatchRequest, PutRequest } from './request.models'; import { RequestEntry } from './request.reducer'; import { RequestService } from './request.service'; import { RestRequestMethod } from './rest-request-method'; +import { GenericConstructor } from '../shared/generic-constructor'; export abstract class DataService { protected abstract requestService: RequestService; @@ -343,7 +344,9 @@ export abstract class DataService { tap((href: string) => { this.requestService.removeByHrefSubstring(href); const request = new FindListRequest(this.requestService.generateRequestId(), href, options); - request.responseMsToLive = 10 * 1000; + if (hasValue(this.responseMsToLive)) { + request.responseMsToLive = this.responseMsToLive; + } this.requestService.configure(request); } @@ -381,6 +384,28 @@ export abstract class DataService { ); } + /** + * Send a PUT request for the specified object + * + * @param object The object to send a put request for. + */ + put(object: T): Observable> { + const requestId = this.requestService.generateRequestId(); + const serializedObject = new DSpaceSerializer(object.constructor as GenericConstructor<{}>).serialize(object); + const request = new PutRequest(requestId, object._links.self.href, serializedObject); + + if (hasValue(this.responseMsToLive)) { + request.responseMsToLive = this.responseMsToLive; + } + + this.requestService.configure(request); + + return this.requestService.getByUUID(requestId).pipe( + find((re: RequestEntry) => hasValue(re) && re.completed), + switchMap(() => this.findByHref(object._links.self.href)) + ); + } + /** * Add a new patch to the object cache * The patch is derived from the differences between the given object and its version in the object cache diff --git a/src/app/core/data/metadata-field-data.service.spec.ts b/src/app/core/data/metadata-field-data.service.spec.ts new file mode 100644 index 0000000000..5c17b56845 --- /dev/null +++ b/src/app/core/data/metadata-field-data.service.spec.ts @@ -0,0 +1,114 @@ +import { RequestService } from './request.service'; +import { HALEndpointService } from '../shared/hal-endpoint.service'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { of as observableOf } from 'rxjs/internal/observable/of'; +import { RestResponse } from '../cache/response.models'; +import { HALEndpointServiceStub } from '../../shared/testing/hal-endpoint-service.stub'; +import { CreateRequest, FindListOptions, PutRequest } from './request.models'; +import { MetadataFieldDataService } from './metadata-field-data.service'; +import { MetadataField } from '../metadata/metadata-field.model'; +import { MetadataSchema } from '../metadata/metadata-schema.model'; +import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; +import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils'; +import { RequestParam } from '../cache/models/request-param.model'; + +describe('MetadataFieldDataService', () => { + let metadataFieldService: MetadataFieldDataService; + let requestService: RequestService; + let halService: HALEndpointService; + let notificationsService: NotificationsService; + let schema: MetadataSchema; + let rdbService: RemoteDataBuildService; + + const endpoint = 'api/metadatafield/endpoint'; + + function init() { + schema = Object.assign(new MetadataSchema(), { + prefix: 'dc', + namespace: 'namespace', + _links: { + self: { href: 'selflink' } + } + }); + requestService = jasmine.createSpyObj('requestService', { + generateRequestId: '34cfed7c-f597-49ef-9cbe-ea351f0023c2', + configure: {}, + getByUUID: observableOf({ response: new RestResponse(true, 200, 'OK') }), + removeByHrefSubstring: {} + }); + halService = Object.assign(new HALEndpointServiceStub(endpoint)); + notificationsService = jasmine.createSpyObj('notificationsService', { + error: {} + }); + rdbService = jasmine.createSpyObj('rdbService', { + buildSingle: createSuccessfulRemoteDataObject$(undefined) + }); + metadataFieldService = new MetadataFieldDataService(requestService, rdbService, undefined, halService, undefined, undefined, undefined, notificationsService); + } + + beforeEach(() => { + init(); + }); + + describe('findBySchema', () => { + beforeEach(() => { + spyOn(metadataFieldService, 'searchBy'); + }); + + it('should call searchBy with the correct arguments', () => { + metadataFieldService.findBySchema(schema); + const expectedOptions = Object.assign(new FindListOptions(), { + searchParams: [new RequestParam('schema', schema.prefix)] + }); + expect(metadataFieldService.searchBy).toHaveBeenCalledWith('bySchema', expectedOptions); + }); + }); + + describe('createOrUpdateMetadataField', () => { + let field: MetadataField; + + beforeEach(() => { + field = Object.assign(new MetadataField(), { + element: 'identifier', + qualifier: undefined, + schema: schema, + _links: { + self: { href: 'selflink' } + } + }); + }); + + describe('called with a new metadata field', () => { + it('should send a CreateRequest', (done) => { + metadataFieldService.createOrUpdateMetadataField(field).subscribe(() => { + expect(requestService.configure).toHaveBeenCalledWith(jasmine.any(CreateRequest)); + done(); + }); + }); + }); + + describe('called with an existing metadata field', () => { + beforeEach(() => { + field = Object.assign(field, { + id: 'id-of-existing-field' + }); + }); + + it('should send a PutRequest', (done) => { + metadataFieldService.createOrUpdateMetadataField(field).subscribe(() => { + expect(requestService.configure).toHaveBeenCalledWith(jasmine.any(PutRequest)); + done(); + }); + }); + }); + }); + + describe('clearRequests', () => { + it('should remove requests on the data service\'s endpoint', (done) => { + metadataFieldService.clearRequests().subscribe(() => { + expect(requestService.removeByHrefSubstring).toHaveBeenCalledWith(`${endpoint}/${(metadataFieldService as any).linkPath}`); + done(); + }); + }); + }); +}); diff --git a/src/app/core/data/metadata-field-data.service.ts b/src/app/core/data/metadata-field-data.service.ts new file mode 100644 index 0000000000..f50be20f13 --- /dev/null +++ b/src/app/core/data/metadata-field-data.service.ts @@ -0,0 +1,89 @@ +import { Injectable } from '@angular/core'; +import { dataService } from '../cache/builders/build-decorators'; +import { DataService } from './data.service'; +import { RequestService } from './request.service'; +import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; +import { Store } from '@ngrx/store'; +import { CoreState } from '../core.reducers'; +import { HALEndpointService } from '../shared/hal-endpoint.service'; +import { ObjectCacheService } from '../cache/object-cache.service'; +import { DefaultChangeAnalyzer } from './default-change-analyzer.service'; +import { HttpClient } from '@angular/common/http'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { METADATA_FIELD } from '../metadata/metadata-field.resource-type'; +import { MetadataField } from '../metadata/metadata-field.model'; +import { MetadataSchema } from '../metadata/metadata-schema.model'; +import { FindListOptions, FindListRequest } from './request.models'; +import { FollowLinkConfig } from '../../shared/utils/follow-link-config.model'; +import { Observable } from 'rxjs/internal/Observable'; +import { hasValue } from '../../shared/empty.util'; +import { find, skipWhile, switchMap, tap } from 'rxjs/operators'; +import { RemoteData } from './remote-data'; +import { RequestParam } from '../cache/models/request-param.model'; +import { PaginatedList } from './paginated-list'; + +/** + * A service responsible for fetching/sending data from/to the REST API on the metadatafields endpoint + */ +@Injectable() +@dataService(METADATA_FIELD) +export class MetadataFieldDataService extends DataService { + protected linkPath = 'metadatafields'; + protected searchBySchemaLinkPath = 'bySchema'; + + constructor( + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected store: Store, + protected halService: HALEndpointService, + protected objectCache: ObjectCacheService, + protected comparator: DefaultChangeAnalyzer, + protected http: HttpClient, + protected notificationsService: NotificationsService) { + super(); + } + + /** + * Find metadata fields belonging to a metadata schema + * @param schema The metadata schema to list fields for + * @param options The options info used to retrieve the fields + * @param linksToFollow List of {@link FollowLinkConfig} that indicate which {@link HALLink}s should be automatically resolved + */ + findBySchema(schema: MetadataSchema, options: FindListOptions = {}, ...linksToFollow: Array>) { + const optionsWithSchema = Object.assign(new FindListOptions(), options, { + searchParams: [new RequestParam('schema', schema.prefix)] + }); + return this.searchBy(this.searchBySchemaLinkPath, optionsWithSchema, ...linksToFollow); + } + + /** + * Create or Update a MetadataField + * If the MetadataField contains an id, it is assumed the field already exists and is updated instead + * Since creating or updating is nearly identical, the only real difference is the request (and slight difference in endpoint): + * - On creation, a CreateRequest is used + * - On update, a PutRequest is used + * @param field The MetadataField to create or update + */ + createOrUpdateMetadataField(field: MetadataField): Observable> { + const isUpdate = hasValue(field.id); + + if (isUpdate) { + return this.put(field); + } else { + return this.create(field, new RequestParam('schemaId', field.schema.id)); + } + } + + /** + * Clear all metadata field requests + * Used for refreshing lists after adding/updating/removing a metadata field from a metadata schema + */ + clearRequests(): Observable { + return this.getBrowseEndpoint().pipe( + tap((href: string) => { + this.requestService.removeByHrefSubstring(href); + }) + ); + } + +} diff --git a/src/app/core/data/metadata-schema-data.service.spec.ts b/src/app/core/data/metadata-schema-data.service.spec.ts new file mode 100644 index 0000000000..bf73deecb7 --- /dev/null +++ b/src/app/core/data/metadata-schema-data.service.spec.ts @@ -0,0 +1,89 @@ +import { RequestService } from './request.service'; +import { HALEndpointService } from '../shared/hal-endpoint.service'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { MetadataSchemaDataService } from './metadata-schema-data.service'; +import { of as observableOf } from 'rxjs'; +import { RestResponse } from '../cache/response.models'; +import { HALEndpointServiceStub } from '../../shared/testing/hal-endpoint-service.stub'; +import { MetadataSchema } from '../metadata/metadata-schema.model'; +import { CreateRequest, PutRequest } from './request.models'; +import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; +import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils'; + +describe('MetadataSchemaDataService', () => { + let metadataSchemaService: MetadataSchemaDataService; + let requestService: RequestService; + let halService: HALEndpointService; + let notificationsService: NotificationsService; + let rdbService: RemoteDataBuildService; + + const endpoint = 'api/metadataschema/endpoint'; + + function init() { + requestService = jasmine.createSpyObj('requestService', { + generateRequestId: '34cfed7c-f597-49ef-9cbe-ea351f0023c2', + configure: {}, + getByUUID: observableOf({ response: new RestResponse(true, 200, 'OK') }), + removeByHrefSubstring: {} + }); + halService = Object.assign(new HALEndpointServiceStub(endpoint)); + notificationsService = jasmine.createSpyObj('notificationsService', { + error: {} + }); + rdbService = jasmine.createSpyObj('rdbService', { + buildSingle: createSuccessfulRemoteDataObject$(undefined) + }); + metadataSchemaService = new MetadataSchemaDataService(requestService, rdbService, undefined, halService, undefined, undefined, undefined, notificationsService); + } + + beforeEach(() => { + init(); + }); + + describe('createOrUpdateMetadataSchema', () => { + let schema: MetadataSchema; + + beforeEach(() => { + schema = Object.assign(new MetadataSchema(), { + prefix: 'dc', + namespace: 'namespace', + _links: { + self: { href: 'selflink' } + } + }); + }); + + describe('called with a new metadata schema', () => { + it('should send a CreateRequest', (done) => { + metadataSchemaService.createOrUpdateMetadataSchema(schema).subscribe(() => { + expect(requestService.configure).toHaveBeenCalledWith(jasmine.any(CreateRequest)); + done(); + }); + }); + }); + + describe('called with an existing metadata schema', () => { + beforeEach(() => { + schema = Object.assign(schema, { + id: 'id-of-existing-schema' + }); + }); + + it('should send a PutRequest', (done) => { + metadataSchemaService.createOrUpdateMetadataSchema(schema).subscribe(() => { + expect(requestService.configure).toHaveBeenCalledWith(jasmine.any(PutRequest)); + done(); + }); + }); + }); + }); + + describe('clearRequests', () => { + it('should remove requests on the data service\'s endpoint', (done) => { + metadataSchemaService.clearRequests().subscribe(() => { + expect(requestService.removeByHrefSubstring).toHaveBeenCalledWith(`${endpoint}/${(metadataSchemaService as any).linkPath}`); + done(); + }); + }); + }); +}); diff --git a/src/app/core/data/metadata-schema-data.service.ts b/src/app/core/data/metadata-schema-data.service.ts index 915f588379..99a3f98b8e 100644 --- a/src/app/core/data/metadata-schema-data.service.ts +++ b/src/app/core/data/metadata-schema-data.service.ts @@ -9,37 +9,21 @@ import { CoreState } from '../core.reducers'; import { MetadataSchema } from '../metadata/metadata-schema.model'; import { METADATA_SCHEMA } from '../metadata/metadata-schema.resource-type'; import { HALEndpointService } from '../shared/hal-endpoint.service'; -import { ChangeAnalyzer } from './change-analyzer'; - import { DataService } from './data.service'; import { DefaultChangeAnalyzer } from './default-change-analyzer.service'; import { RequestService } from './request.service'; - -/* tslint:disable:max-classes-per-file */ -class DataServiceImpl extends DataService { - protected linkPath = 'metadataschemas'; - - constructor( - protected requestService: RequestService, - protected rdbService: RemoteDataBuildService, - protected store: Store, - protected objectCache: ObjectCacheService, - protected halService: HALEndpointService, - protected notificationsService: NotificationsService, - protected http: HttpClient, - protected comparator: ChangeAnalyzer) { - super(); - } - -} +import { Observable } from 'rxjs/internal/Observable'; +import { hasValue } from '../../shared/empty.util'; +import { tap } from 'rxjs/operators'; +import { RemoteData } from './remote-data'; /** * A service responsible for fetching/sending data from/to the REST API on the metadataschemas endpoint */ @Injectable() @dataService(METADATA_SCHEMA) -export class MetadataSchemaDataService { - private dataService: DataServiceImpl; +export class MetadataSchemaDataService extends DataService { + protected linkPath = 'metadataschemas'; constructor( protected requestService: RequestService, @@ -50,6 +34,35 @@ export class MetadataSchemaDataService { protected comparator: DefaultChangeAnalyzer, protected http: HttpClient, protected notificationsService: NotificationsService) { - this.dataService = new DataServiceImpl(requestService, rdbService, null, objectCache, halService, notificationsService, http, comparator); + super(); } + + /** + * Create or Update a MetadataSchema + * If the MetadataSchema contains an id, it is assumed the schema already exists and is updated instead + * Since creating or updating is nearly identical, the only real difference is the request (and slight difference in endpoint): + * - On creation, a CreateRequest is used + * - On update, a PutRequest is used + * @param schema The MetadataSchema to create or update + */ + createOrUpdateMetadataSchema(schema: MetadataSchema): Observable> { + const isUpdate = hasValue(schema.id); + + if (isUpdate) { + return this.put(schema); + } else { + return this.create(schema); + } + } + + /** + * Clear all metadata schema requests + * Used for refreshing lists after adding/updating/removing a metadata schema in the registry + */ + clearRequests(): Observable { + return this.getBrowseEndpoint().pipe( + tap((href: string) => this.requestService.removeByHrefSubstring(href)) + ); + } + } diff --git a/src/app/core/data/metadatafield-parsing.service.ts b/src/app/core/data/metadatafield-parsing.service.ts deleted file mode 100644 index 08f7892ac7..0000000000 --- a/src/app/core/data/metadatafield-parsing.service.ts +++ /dev/null @@ -1,22 +0,0 @@ -import { Injectable } from '@angular/core'; -import { MetadatafieldSuccessResponse, RestResponse } from '../cache/response.models'; -import { DSpaceRESTV2Response } from '../dspace-rest-v2/dspace-rest-v2-response.model'; -import { DSpaceSerializer } from '../dspace-rest-v2/dspace.serializer'; -import { MetadataField } from '../metadata/metadata-field.model'; -import { ResponseParsingService } from './parsing.service'; -import { RestRequest } from './request.models'; - -/** - * A service responsible for parsing DSpaceRESTV2Response data related to a single MetadataField to a valid RestResponse - */ -@Injectable() -export class MetadatafieldParsingService implements ResponseParsingService { - - parse(request: RestRequest, data: DSpaceRESTV2Response): RestResponse { - const payload = data.payload; - - const deserialized = new DSpaceSerializer(MetadataField).deserialize(payload); - return new MetadatafieldSuccessResponse(deserialized, data.statusCode, data.statusText); - } - -} diff --git a/src/app/core/data/metadataschema-parsing.service.ts b/src/app/core/data/metadataschema-parsing.service.ts deleted file mode 100644 index f4b90e5dcd..0000000000 --- a/src/app/core/data/metadataschema-parsing.service.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { Injectable } from '@angular/core'; -import { MetadataschemaSuccessResponse, RestResponse } from '../cache/response.models'; -import { DSpaceRESTV2Response } from '../dspace-rest-v2/dspace-rest-v2-response.model'; -import { DSpaceSerializer } from '../dspace-rest-v2/dspace.serializer'; -import { MetadataSchema } from '../metadata/metadata-schema.model'; -import { ResponseParsingService } from './parsing.service'; -import { RestRequest } from './request.models'; - -@Injectable() -export class MetadataschemaParsingService implements ResponseParsingService { - - parse(request: RestRequest, data: DSpaceRESTV2Response): RestResponse { - const payload = data.payload; - - const deserialized = new DSpaceSerializer(MetadataSchema).deserialize(payload); - return new MetadataschemaSuccessResponse(deserialized, data.statusCode, data.statusText); - } - -} diff --git a/src/app/core/data/object-updates/object-updates.actions.ts b/src/app/core/data/object-updates/object-updates.actions.ts index 94918157ee..f26be768b1 100644 --- a/src/app/core/data/object-updates/object-updates.actions.ts +++ b/src/app/core/data/object-updates/object-updates.actions.ts @@ -8,7 +8,6 @@ import {INotification} from '../../../shared/notifications/models/notification.m */ export const ObjectUpdatesActionTypes = { INITIALIZE_FIELDS: type('dspace/core/cache/object-updates/INITIALIZE_FIELDS'), - ADD_PAGE_TO_CUSTOM_ORDER: type('dspace/core/cache/object-updates/ADD_PAGE_TO_CUSTOM_ORDER'), SET_EDITABLE_FIELD: type('dspace/core/cache/object-updates/SET_EDITABLE_FIELD'), SET_VALID_FIELD: type('dspace/core/cache/object-updates/SET_VALID_FIELD'), ADD_FIELD: type('dspace/core/cache/object-updates/ADD_FIELD'), @@ -17,8 +16,7 @@ export const ObjectUpdatesActionTypes = { REINSTATE: type('dspace/core/cache/object-updates/REINSTATE'), REMOVE: type('dspace/core/cache/object-updates/REMOVE'), REMOVE_ALL: type('dspace/core/cache/object-updates/REMOVE_ALL'), - REMOVE_FIELD: type('dspace/core/cache/object-updates/REMOVE_FIELD'), - MOVE: type('dspace/core/cache/object-updates/MOVE'), + REMOVE_FIELD: type('dspace/core/cache/object-updates/REMOVE_FIELD') }; /* tslint:disable:max-classes-per-file */ @@ -29,8 +27,7 @@ export const ObjectUpdatesActionTypes = { export enum FieldChangeType { UPDATE = 0, ADD = 1, - REMOVE = 2, - MOVE = 3 + REMOVE = 2 } /** @@ -41,10 +38,7 @@ export class InitializeFieldsAction implements Action { payload: { url: string, fields: Identifiable[], - lastModified: Date, - order: string[], - pageSize: number, - page: number + lastModified: Date }; /** @@ -61,42 +55,9 @@ export class InitializeFieldsAction implements Action { constructor( url: string, fields: Identifiable[], - lastModified: Date, - order: string[] = [], - pageSize: number = 9999, - page: number = 0 + lastModified: Date ) { - this.payload = { url, fields, lastModified, order, pageSize, page }; - } -} - -/** - * An ngrx action to initialize a new page's fields in the ObjectUpdates state - */ -export class AddPageToCustomOrderAction implements Action { - type = ObjectUpdatesActionTypes.ADD_PAGE_TO_CUSTOM_ORDER; - payload: { - url: string, - fields: Identifiable[], - order: string[], - page: number - }; - - /** - * Create a new AddPageToCustomOrderAction - * - * @param url The unique url of the page for which the fields are being added - * @param fields The identifiable fields of which the updates are kept track of - * @param order A custom order to keep track of objects moving around - * @param page The page to populate in the custom order - */ - constructor( - url: string, - fields: Identifiable[], - order: string[] = [], - page: number = 0 - ) { - this.payload = { url, fields, order, page }; + this.payload = { url, fields, lastModified }; } } @@ -320,43 +281,6 @@ export class RemoveFieldUpdateAction implements Action { } } -/** - * An ngrx action to remove a single field update in the ObjectUpdates state for a certain page url and field uuid - */ -export class MoveFieldUpdateAction implements Action { - type = ObjectUpdatesActionTypes.MOVE; - payload: { - url: string, - from: number, - to: number, - fromPage: number, - toPage: number, - field?: Identifiable - }; - - /** - * Create a new RemoveObjectUpdatesAction - * - * @param url - * the unique url of the page for which a field's change should be removed - * @param from The index of the object to move - * @param to The index to move the object to - * @param fromPage The page to move the object from - * @param toPage The page to move the object to - * @param field Optional field to add to the fieldUpdates list (useful when we want to track updates across multiple pages) - */ - constructor( - url: string, - from: number, - to: number, - fromPage: number, - toPage: number, - field?: Identifiable - ) { - this.payload = { url, from, to, fromPage, toPage, field }; - } -} - /* tslint:enable:max-classes-per-file */ /** @@ -369,8 +293,6 @@ export type ObjectUpdatesAction | ReinstateObjectUpdatesAction | RemoveObjectUpdatesAction | RemoveFieldUpdateAction - | MoveFieldUpdateAction - | AddPageToCustomOrderAction | RemoveAllObjectUpdatesAction | SelectVirtualMetadataAction | SetEditableFieldUpdateAction diff --git a/src/app/core/data/object-updates/object-updates.reducer.spec.ts b/src/app/core/data/object-updates/object-updates.reducer.spec.ts index bdf202049e..cb7f44039c 100644 --- a/src/app/core/data/object-updates/object-updates.reducer.spec.ts +++ b/src/app/core/data/object-updates/object-updates.reducer.spec.ts @@ -1,9 +1,9 @@ import * as deepFreeze from 'deep-freeze'; import { - AddFieldUpdateAction, AddPageToCustomOrderAction, + AddFieldUpdateAction, DiscardObjectUpdatesAction, FieldChangeType, - InitializeFieldsAction, MoveFieldUpdateAction, + InitializeFieldsAction, ReinstateObjectUpdatesAction, RemoveAllObjectUpdatesAction, RemoveFieldUpdateAction, RemoveObjectUpdatesAction, SelectVirtualMetadataAction, SetEditableFieldUpdateAction, SetValidFieldUpdateAction @@ -85,16 +85,6 @@ describe('objectUpdatesReducer', () => { virtualMetadataSources: { [relationship.uuid]: {[identifiable1.uuid]: true} }, - customOrder: { - initialOrderPages: [ - { order: [identifiable1.uuid, identifiable2.uuid, identifiable3.uuid] } - ], - newOrderPages: [ - { order: [identifiable1.uuid, identifiable2.uuid, identifiable3.uuid] } - ], - pageSize: 10, - changed: false - } } }; @@ -121,16 +111,6 @@ describe('objectUpdatesReducer', () => { virtualMetadataSources: { [relationship.uuid]: {[identifiable1.uuid]: true} }, - customOrder: { - initialOrderPages: [ - { order: [identifiable1.uuid, identifiable2.uuid, identifiable3.uuid] } - ], - newOrderPages: [ - { order: [identifiable1.uuid, identifiable2.uuid, identifiable3.uuid] } - ], - pageSize: 10, - changed: false - } }, [url + OBJECT_UPDATES_TRASH_PATH]: { fieldStates: { @@ -165,16 +145,6 @@ describe('objectUpdatesReducer', () => { virtualMetadataSources: { [relationship.uuid]: {[identifiable1.uuid]: true} }, - customOrder: { - initialOrderPages: [ - { order: [identifiable1.uuid, identifiable2.uuid, identifiable3.uuid] } - ], - newOrderPages: [ - { order: [identifiable1.uuid, identifiable2.uuid, identifiable3.uuid] } - ], - pageSize: 10, - changed: false - } } }; @@ -243,7 +213,7 @@ describe('objectUpdatesReducer', () => { }); it('should initialize all fields when the INITIALIZE action is dispatched, based on the payload', () => { - const action = new InitializeFieldsAction(url, [identifiable1, identifiable3], modDate, [identifiable1.uuid, identifiable3.uuid], 10, 0); + const action = new InitializeFieldsAction(url, [identifiable1, identifiable3], modDate); const expectedState = { [url]: { @@ -261,17 +231,7 @@ describe('objectUpdatesReducer', () => { }, fieldUpdates: {}, virtualMetadataSources: {}, - lastModified: modDate, - customOrder: { - initialOrderPages: [ - { order: [identifiable1.uuid, identifiable3.uuid] } - ], - newOrderPages: [ - { order: [identifiable1.uuid, identifiable3.uuid] } - ], - pageSize: 10, - changed: false - } + lastModified: modDate } }; const newState = objectUpdatesReducer(testState, action); @@ -337,30 +297,4 @@ describe('objectUpdatesReducer', () => { const newState = objectUpdatesReducer(testState, action); expect(newState[url].fieldUpdates[uuid]).toBeUndefined(); }); - - it('should move the custom order from the state when the MOVE action is dispatched', () => { - const action = new MoveFieldUpdateAction(url, 0, 1, 0, 0); - - const newState = objectUpdatesReducer(testState, action); - expect(newState[url].customOrder.newOrderPages[0].order[0]).toEqual(testState[url].customOrder.newOrderPages[0].order[1]); - expect(newState[url].customOrder.newOrderPages[0].order[1]).toEqual(testState[url].customOrder.newOrderPages[0].order[0]); - expect(newState[url].customOrder.changed).toEqual(true); - }); - - it('should add a new page to the custom order and add empty pages in between when the ADD_PAGE_TO_CUSTOM_ORDER action is dispatched', () => { - const identifiable4 = { - uuid: 'a23eae5a-7857-4ef9-8e52-989436ad2955', - key: 'dc.description.abstract', - language: null, - value: 'Extra value' - }; - const action = new AddPageToCustomOrderAction(url, [identifiable4], [identifiable4.uuid], 2); - - const newState = objectUpdatesReducer(testState, action); - // Confirm the page in between the two pages (index 1) has been filled with 10 (page size) undefined values - expect(newState[url].customOrder.newOrderPages[1].order.length).toEqual(10); - expect(newState[url].customOrder.newOrderPages[1].order[0]).toBeUndefined(); - // Verify the new page is correct - expect(newState[url].customOrder.newOrderPages[2].order[0]).toEqual(identifiable4.uuid); - }); }); diff --git a/src/app/core/data/object-updates/object-updates.reducer.ts b/src/app/core/data/object-updates/object-updates.reducer.ts index 759a9f5c87..b1626a5ff5 100644 --- a/src/app/core/data/object-updates/object-updates.reducer.ts +++ b/src/app/core/data/object-updates/object-updates.reducer.ts @@ -1,8 +1,8 @@ import { - AddFieldUpdateAction, AddPageToCustomOrderAction, + AddFieldUpdateAction, DiscardObjectUpdatesAction, FieldChangeType, - InitializeFieldsAction, MoveFieldUpdateAction, + InitializeFieldsAction, ObjectUpdatesAction, ObjectUpdatesActionTypes, ReinstateObjectUpdatesAction, @@ -12,9 +12,7 @@ import { SetValidFieldUpdateAction, SelectVirtualMetadataAction, } from './object-updates.actions'; -import { hasNoValue, hasValue, isEmpty, isNotEmpty } from '../../../shared/empty.util'; -import { moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop'; -import { from } from 'rxjs/internal/observable/from'; +import { hasNoValue, hasValue } from '../../../shared/empty.util'; import {Relationship} from '../../shared/item-relationships/relationship.model'; /** @@ -83,20 +81,6 @@ export interface DeleteRelationship extends Relationship { keepRightVirtualMetadata: boolean, } -/** - * A custom order given to the list of objects - */ -export interface CustomOrder { - initialOrderPages: OrderPage[], - newOrderPages: OrderPage[], - pageSize: number; - changed: boolean -} - -export interface OrderPage { - order: string[] -} - /** * The updated state of a single page */ @@ -105,7 +89,6 @@ export interface ObjectUpdatesEntry { fieldUpdates: FieldUpdates; virtualMetadataSources: VirtualMetadataSources; lastModified: Date; - customOrder: CustomOrder } /** @@ -138,9 +121,6 @@ export function objectUpdatesReducer(state = initialState, action: ObjectUpdates case ObjectUpdatesActionTypes.INITIALIZE_FIELDS: { return initializeFieldsUpdate(state, action as InitializeFieldsAction); } - case ObjectUpdatesActionTypes.ADD_PAGE_TO_CUSTOM_ORDER: { - return addPageToCustomOrder(state, action as AddPageToCustomOrderAction); - } case ObjectUpdatesActionTypes.ADD_FIELD: { return addFieldUpdate(state, action as AddFieldUpdateAction); } @@ -168,9 +148,6 @@ export function objectUpdatesReducer(state = initialState, action: ObjectUpdates case ObjectUpdatesActionTypes.SET_VALID_FIELD: { return setValidFieldUpdate(state, action as SetValidFieldUpdateAction); } - case ObjectUpdatesActionTypes.MOVE: { - return moveFieldUpdate(state, action as MoveFieldUpdateAction); - } default: { return state; } @@ -186,50 +163,18 @@ function initializeFieldsUpdate(state: any, action: InitializeFieldsAction) { const url: string = action.payload.url; const fields: Identifiable[] = action.payload.fields; const lastModifiedServer: Date = action.payload.lastModified; - const order = action.payload.order; - const pageSize = action.payload.pageSize; - const page = action.payload.page; const fieldStates = createInitialFieldStates(fields); - const initialOrderPages = addOrderToPages([], order, pageSize, page); const newPageState = Object.assign( {}, state[url], { fieldStates: fieldStates }, { fieldUpdates: {} }, { virtualMetadataSources: {} }, - { lastModified: lastModifiedServer }, - { customOrder: { - initialOrderPages: initialOrderPages, - newOrderPages: initialOrderPages, - pageSize: pageSize, - changed: false } - } + { lastModified: lastModifiedServer } ); return Object.assign({}, state, { [url]: newPageState }); } -/** - * Add a page of objects to the state of a specific url and update a specific page of the custom order - * @param state The current state - * @param action The action to perform on the current state - */ -function addPageToCustomOrder(state: any, action: AddPageToCustomOrderAction) { - const url: string = action.payload.url; - const fields: Identifiable[] = action.payload.fields; - const fieldStates = createInitialFieldStates(fields); - const order = action.payload.order; - const page = action.payload.page; - const pageState: ObjectUpdatesEntry = state[url] || {}; - const newPageState = Object.assign({}, pageState, { - fieldStates: Object.assign({}, pageState.fieldStates, fieldStates), - customOrder: Object.assign({}, pageState.customOrder, { - newOrderPages: addOrderToPages(pageState.customOrder.newOrderPages, order, pageState.customOrder.pageSize, page), - initialOrderPages: addOrderToPages(pageState.customOrder.initialOrderPages, order, pageState.customOrder.pageSize, page) - }) - }); - return Object.assign({}, state, { [url]: newPageState }); -} - /** * Add a new update for a specific field to the store * @param state The current state @@ -338,19 +283,9 @@ function discardObjectUpdatesFor(url: string, state: any) { } }); - const newCustomOrder = Object.assign({}, pageState.customOrder); - if (pageState.customOrder.changed) { - const initialOrder = pageState.customOrder.initialOrderPages; - if (isNotEmpty(initialOrder)) { - newCustomOrder.newOrderPages = initialOrder; - newCustomOrder.changed = false; - } - } - const discardedPageState = Object.assign({}, pageState, { fieldUpdates: {}, - fieldStates: newFieldStates, - customOrder: newCustomOrder + fieldStates: newFieldStates }); return Object.assign({}, state, { [url]: discardedPageState }, { [url + OBJECT_UPDATES_TRASH_PATH]: pageState }); } @@ -504,121 +439,3 @@ function createInitialFieldStates(fields: Identifiable[]) { uuids.forEach((uuid: string) => fieldStates[uuid] = initialFieldState); return fieldStates; } - -/** - * Method to add a list of objects to an existing FieldStates object - * @param fieldStates FieldStates to add states to - * @param fields Identifiable objects The list of objects to add to the FieldStates - */ -function addFieldStates(fieldStates: FieldStates, fields: Identifiable[]) { - const uuids = fields.map((field: Identifiable) => field.uuid); - uuids.forEach((uuid: string) => fieldStates[uuid] = initialFieldState); - return fieldStates; -} - -/** - * Move an object within the custom order of a page state - * @param state The current state - * @param action The move action to perform - */ -function moveFieldUpdate(state: any, action: MoveFieldUpdateAction) { - const url = action.payload.url; - const fromIndex = action.payload.from; - const toIndex = action.payload.to; - const fromPage = action.payload.fromPage; - const toPage = action.payload.toPage; - const field = action.payload.field; - - const pageState: ObjectUpdatesEntry = state[url]; - const initialOrderPages = pageState.customOrder.initialOrderPages; - const customOrderPages = [...pageState.customOrder.newOrderPages]; - - // Create a copy of the custom orders for the from- and to-pages - const fromPageOrder = [...customOrderPages[fromPage].order]; - const toPageOrder = [...customOrderPages[toPage].order]; - if (fromPage === toPage) { - if (isNotEmpty(customOrderPages[fromPage]) && isNotEmpty(customOrderPages[fromPage].order[fromIndex]) && isNotEmpty(customOrderPages[fromPage].order[toIndex])) { - // Move an item from one index to another within the same page - moveItemInArray(fromPageOrder, fromIndex, toIndex); - // Update the custom order for this page - customOrderPages[fromPage] = { order: fromPageOrder }; - } - } else { - if (isNotEmpty(customOrderPages[fromPage]) && hasValue(customOrderPages[toPage]) && isNotEmpty(customOrderPages[fromPage].order[fromIndex])) { - // Move an item from one index of one page to an index in another page - transferArrayItem(fromPageOrder, toPageOrder, fromIndex, toIndex); - // Update the custom order for both pages - customOrderPages[fromPage] = { order: fromPageOrder }; - customOrderPages[toPage] = { order: toPageOrder }; - } - } - - // Create a field update if it doesn't exist for this field yet - let fieldUpdate = {}; - if (hasValue(field)) { - fieldUpdate = pageState.fieldUpdates[field.uuid]; - if (hasNoValue(fieldUpdate)) { - fieldUpdate = { field: field, changeType: undefined } - } - } - - // Update the store's state with new values and return - return Object.assign({}, state, { [url]: Object.assign({}, pageState, { - fieldUpdates: Object.assign({}, pageState.fieldUpdates, hasValue(field) ? { [field.uuid]: fieldUpdate } : {}), - customOrder: Object.assign({}, pageState.customOrder, { newOrderPages: customOrderPages, changed: checkForOrderChanges(initialOrderPages, customOrderPages) }) - })}) -} - -/** - * Compare two lists of OrderPage objects and return whether there's at least one change in the order of objects within - * @param initialOrderPages The initial list of OrderPages - * @param customOrderPages The changed list of OrderPages - */ -function checkForOrderChanges(initialOrderPages: OrderPage[], customOrderPages: OrderPage[]) { - let changed = false; - initialOrderPages.forEach((orderPage: OrderPage, page: number) => { - if (isNotEmpty(orderPage) && isNotEmpty(orderPage.order) && isNotEmpty(customOrderPages[page]) && isNotEmpty(customOrderPages[page].order)) { - orderPage.order.forEach((id: string, index: number) => { - if (id !== customOrderPages[page].order[index]) { - changed = true; - return; - } - }); - if (changed) { - return; - } - } - }); - return changed; -} - -/** - * Initialize a custom order page by providing the list of all pages, a list of UUIDs, pageSize and the page to populate - * @param initialPages The initial list of OrderPage objects - * @param order The list of UUIDs to create a page for - * @param pageSize The pageSize used to populate empty spacer pages - * @param page The index of the page to add - */ -function addOrderToPages(initialPages: OrderPage[], order: string[], pageSize: number, page: number): OrderPage[] { - const result = [...initialPages]; - const orderPage: OrderPage = { order: order }; - if (page < result.length) { - // The page we're trying to add already exists in the list. Overwrite it. - result[page] = orderPage; - } else if (page === result.length) { - // The page we're trying to add is the next page in the list, add it. - result.push(orderPage); - } else { - // The page we're trying to add is at least one page ahead of the list, fill the list with empty pages before adding the page. - const emptyOrder = []; - for (let i = 0; i < pageSize; i++) { - emptyOrder.push(undefined); - } - const emptyOrderPage: OrderPage = { order: emptyOrder }; - for (let i = result.length; i < page; i++) { - result.push(emptyOrderPage); - } - result.push(orderPage); - } - return result; -} diff --git a/src/app/core/data/object-updates/object-updates.service.spec.ts b/src/app/core/data/object-updates/object-updates.service.spec.ts index 780a402a84..04018b8de2 100644 --- a/src/app/core/data/object-updates/object-updates.service.spec.ts +++ b/src/app/core/data/object-updates/object-updates.service.spec.ts @@ -2,7 +2,6 @@ import { Store } from '@ngrx/store'; import { CoreState } from '../../core.reducers'; import { ObjectUpdatesService } from './object-updates.service'; import { - AddPageToCustomOrderAction, DiscardObjectUpdatesAction, FieldChangeType, InitializeFieldsAction, ReinstateObjectUpdatesAction, RemoveFieldUpdateAction, SelectVirtualMetadataAction, @@ -13,8 +12,6 @@ import { Notification } from '../../../shared/notifications/models/notification. import { NotificationType } from '../../../shared/notifications/models/notification-type'; import { OBJECT_UPDATES_TRASH_PATH } from './object-updates.reducer'; import {Relationship} from '../../shared/item-relationships/relationship.model'; -import { MoveOperation } from 'fast-json-patch/lib/core'; -import { ArrayMoveChangeAnalyzer } from '../array-move-change-analyzer.service'; describe('ObjectUpdatesService', () => { let service: ObjectUpdatesService; @@ -47,7 +44,7 @@ describe('ObjectUpdatesService', () => { }; store = new Store(undefined, undefined, undefined); spyOn(store, 'dispatch'); - service = new ObjectUpdatesService(store, new ArrayMoveChangeAnalyzer()); + service = new ObjectUpdatesService(store); spyOn(service as any, 'getObjectEntry').and.returnValue(observableOf(objectEntry)); spyOn(service as any, 'getFieldState').and.callFake((uuid) => { @@ -63,25 +60,6 @@ describe('ObjectUpdatesService', () => { }); }); - describe('initializeWithCustomOrder', () => { - const pageSize = 20; - const page = 0; - - it('should dispatch an INITIALIZE action with the correct URL, initial identifiables, last modified , custom order, page size and page', () => { - service.initializeWithCustomOrder(url, identifiables, modDate, pageSize, page); - expect(store.dispatch).toHaveBeenCalledWith(new InitializeFieldsAction(url, identifiables, modDate, identifiables.map((identifiable) => identifiable.uuid), pageSize, page)); - }); - }); - - describe('addPageToCustomOrder', () => { - const page = 2; - - it('should dispatch an ADD_PAGE_TO_CUSTOM_ORDER action with the correct URL, identifiables, custom order and page number to add', () => { - service.addPageToCustomOrder(url, identifiables, page); - expect(store.dispatch).toHaveBeenCalledWith(new AddPageToCustomOrderAction(url, identifiables, identifiables.map((identifiable) => identifiable.uuid), page)); - }); - }); - describe('getFieldUpdates', () => { it('should return the list of all fields, including their update if there is one', () => { const result$ = service.getFieldUpdates(url, identifiables); @@ -116,49 +94,6 @@ describe('ObjectUpdatesService', () => { }); }); - describe('getFieldUpdatesByCustomOrder', () => { - beforeEach(() => { - const fieldStates = { - [identifiable1.uuid]: { editable: false, isNew: false, isValid: true }, - [identifiable2.uuid]: { editable: true, isNew: false, isValid: false }, - [identifiable3.uuid]: { editable: true, isNew: true, isValid: true }, - }; - - const customOrder = { - initialOrderPages: [{ - order: [identifiable1.uuid, identifiable2.uuid, identifiable3.uuid] - }], - newOrderPages: [{ - order: [identifiable2.uuid, identifiable3.uuid, identifiable1.uuid] - }], - pageSize: 20, - changed: true - }; - - const objectEntry = { - fieldStates, fieldUpdates, lastModified: modDate, virtualMetadataSources: {}, customOrder - }; - - (service as any).getObjectEntry.and.returnValue(observableOf(objectEntry)) - }); - - it('should return the list of all fields, including their update if there is one, ordered by their custom order', (done) => { - const result$ = service.getFieldUpdatesByCustomOrder(url, identifiables); - expect((service as any).getObjectEntry).toHaveBeenCalledWith(url); - - const expectedResult = { - [identifiable2.uuid]: { field: identifiable2, changeType: undefined }, - [identifiable3.uuid]: { field: identifiable3, changeType: FieldChangeType.ADD }, - [identifiable1.uuid]: { field: identifiable1Updated, changeType: FieldChangeType.UPDATE } - }; - - result$.subscribe((result) => { - expect(result).toEqual(expectedResult); - done(); - }); - }); - }); - describe('isEditable', () => { it('should return false if this identifiable is currently not editable in the store', () => { const result$ = service.isEditable(url, identifiable1.uuid); @@ -274,11 +209,7 @@ describe('ObjectUpdatesService', () => { }); describe('when updates are emtpy', () => { beforeEach(() => { - (service as any).getObjectEntry.and.returnValue(observableOf({ - customOrder: { - changed: false - } - })) + (service as any).getObjectEntry.and.returnValue(observableOf({})) }); it('should return false when there are no updates', () => { @@ -346,44 +277,4 @@ describe('ObjectUpdatesService', () => { }); }); - describe('getMoveOperations', () => { - beforeEach(() => { - const fieldStates = { - [identifiable1.uuid]: { editable: false, isNew: false, isValid: true }, - [identifiable2.uuid]: { editable: true, isNew: false, isValid: false }, - [identifiable3.uuid]: { editable: true, isNew: true, isValid: true }, - }; - - const customOrder = { - initialOrderPages: [{ - order: [identifiable1.uuid, identifiable2.uuid, identifiable3.uuid] - }], - newOrderPages: [{ - order: [identifiable2.uuid, identifiable3.uuid, identifiable1.uuid] - }], - pageSize: 20, - changed: true - }; - - const objectEntry = { - fieldStates, fieldUpdates, lastModified: modDate, virtualMetadataSources: {}, customOrder - }; - - (service as any).getObjectEntry.and.returnValue(observableOf(objectEntry)) - }); - - it('should return the expected move operations', (done) => { - const result$ = service.getMoveOperations(url); - - const expectedResult = [ - { op: 'move', from: '/0', path: '/2' } - ] as MoveOperation[]; - - result$.subscribe((result) => { - expect(result).toEqual(expectedResult); - done(); - }); - }); - }); - }); diff --git a/src/app/core/data/object-updates/object-updates.service.ts b/src/app/core/data/object-updates/object-updates.service.ts index c9a7f47e81..84f0f06035 100644 --- a/src/app/core/data/object-updates/object-updates.service.ts +++ b/src/app/core/data/object-updates/object-updates.service.ts @@ -8,16 +8,15 @@ import { Identifiable, OBJECT_UPDATES_TRASH_PATH, ObjectUpdatesEntry, - ObjectUpdatesState, OrderPage, + ObjectUpdatesState, VirtualMetadataSource } from './object-updates.reducer'; import { Observable } from 'rxjs'; import { - AddFieldUpdateAction, AddPageToCustomOrderAction, + AddFieldUpdateAction, DiscardObjectUpdatesAction, FieldChangeType, InitializeFieldsAction, - MoveFieldUpdateAction, ReinstateObjectUpdatesAction, RemoveFieldUpdateAction, SelectVirtualMetadataAction, @@ -25,11 +24,8 @@ import { SetValidFieldUpdateAction } from './object-updates.actions'; import { distinctUntilChanged, filter, map, switchMap } from 'rxjs/operators'; -import { hasNoValue, hasValue, isEmpty, isNotEmpty } from '../../../shared/empty.util'; +import { hasNoValue, hasValue, isEmpty, isNotEmpty, isNotEmptyOperator } from '../../../shared/empty.util'; import { INotification } from '../../../shared/notifications/models/notification.model'; -import { ArrayMoveChangeAnalyzer } from '../array-move-change-analyzer.service'; -import { MoveOperation } from 'fast-json-patch/lib/core'; -import { flatten } from '@angular/compiler'; function objectUpdatesStateSelector(): MemoizedSelector { return createSelector(coreSelector, (state: CoreState) => state['cache/object-updates']); @@ -52,9 +48,7 @@ function virtualMetadataSourceSelector(url: string, source: string): MemoizedSel */ @Injectable() export class ObjectUpdatesService { - constructor(private store: Store, - private comparator: ArrayMoveChangeAnalyzer) { - + constructor(private store: Store) { } /** @@ -67,28 +61,6 @@ export class ObjectUpdatesService { this.store.dispatch(new InitializeFieldsAction(url, fields, lastModified)); } - /** - * Method to dispatch an InitializeFieldsAction to the store and keeping track of the order objects are stored - * @param url The page's URL for which the changes are being mapped - * @param fields The initial fields for the page's object - * @param lastModified The date the object was last modified - * @param pageSize The page size to use for adding pages to the custom order - * @param page The first page to populate the custom order with - */ - initializeWithCustomOrder(url, fields: Identifiable[], lastModified: Date, pageSize = 9999, page = 0): void { - this.store.dispatch(new InitializeFieldsAction(url, fields, lastModified, fields.map((field) => field.uuid), pageSize, page)); - } - - /** - * Method to dispatch an AddPageToCustomOrderAction, adding a new page to an already existing custom order tracking - * @param url The URL for which the changes are being mapped - * @param fields The fields to add a new page for - * @param page The page number (starting from index 0) - */ - addPageToCustomOrder(url, fields: Identifiable[], page: number): void { - this.store.dispatch(new AddPageToCustomOrderAction(url, fields, fields.map((field) => field.uuid), page)); - } - /** * Method to dispatch an AddFieldUpdateAction to the store * @param url The page's URL for which the changes are saved @@ -153,7 +125,7 @@ export class ObjectUpdatesService { */ getFieldUpdatesExclusive(url: string, initialFields: Identifiable[]): Observable { const objectUpdates = this.getObjectEntry(url); - return objectUpdates.pipe(map((objectEntry) => { + return objectUpdates.pipe(isNotEmptyOperator(), map((objectEntry) => { const fieldUpdates: FieldUpdates = {}; for (const object of initialFields) { let fieldUpdate = objectEntry.fieldUpdates[object.uuid]; @@ -166,31 +138,6 @@ export class ObjectUpdatesService { })) } - /** - * Method that combines the state's updates with the initial values (when there's no update), - * sorted by their custom order to create a FieldUpdates object - * @param url The URL of the page for which the FieldUpdates should be requested - * @param initialFields The initial values of the fields - * @param page The page to retrieve - */ - getFieldUpdatesByCustomOrder(url: string, initialFields: Identifiable[], page = 0): Observable { - const objectUpdates = this.getObjectEntry(url); - return objectUpdates.pipe(map((objectEntry) => { - const fieldUpdates: FieldUpdates = {}; - if (hasValue(objectEntry) && hasValue(objectEntry.customOrder) && isNotEmpty(objectEntry.customOrder.newOrderPages) && page < objectEntry.customOrder.newOrderPages.length) { - for (const uuid of objectEntry.customOrder.newOrderPages[page].order) { - let fieldUpdate = objectEntry.fieldUpdates[uuid]; - if (isEmpty(fieldUpdate)) { - const identifiable = initialFields.find((object: Identifiable) => object.uuid === uuid); - fieldUpdate = {field: identifiable, changeType: undefined}; - } - fieldUpdates[uuid] = fieldUpdate; - } - } - return fieldUpdates; - })) - } - /** * Method to check if a specific field is currently editable in the store * @param url The URL of the page on which the field resides @@ -260,19 +207,6 @@ export class ObjectUpdatesService { this.saveFieldUpdate(url, field, FieldChangeType.UPDATE); } - /** - * Dispatches a MoveFieldUpdateAction - * @param url The page's URL for which the changes are saved - * @param from The index of the object to move - * @param to The index to move the object to - * @param fromPage The page to move the object from - * @param toPage The page to move the object to - * @param field Optional field to add to the fieldUpdates list (useful if we want to track updates across multiple pages) - */ - saveMoveFieldUpdate(url: string, from: number, to: number, fromPage = 0, toPage = 0, field?: Identifiable) { - this.store.dispatch(new MoveFieldUpdateAction(url, from, to, fromPage, toPage, field)); - } - /** * Check whether the virtual metadata of a given item is selected to be saved as real metadata * @param url The URL of the page on which the field resides @@ -387,7 +321,7 @@ export class ObjectUpdatesService { * @param url The page's url to check for in the store */ hasUpdates(url: string): Observable { - return this.getObjectEntry(url).pipe(map((objectEntry) => hasValue(objectEntry) && (isNotEmpty(objectEntry.fieldUpdates) || objectEntry.customOrder.changed))); + return this.getObjectEntry(url).pipe(map((objectEntry) => hasValue(objectEntry) && isNotEmpty(objectEntry.fieldUpdates))); } /** @@ -405,19 +339,4 @@ export class ObjectUpdatesService { getLastModified(url: string): Observable { return this.getObjectEntry(url).pipe(map((entry: ObjectUpdatesEntry) => entry.lastModified)); } - - /** - * Get move operations based on the custom order - * @param url The page's url - */ - getMoveOperations(url: string): Observable { - return this.getObjectEntry(url).pipe( - map((objectEntry) => objectEntry.customOrder), - map((customOrder) => this.comparator.diff( - flatten(customOrder.initialOrderPages.map((orderPage: OrderPage) => orderPage.order)), - flatten(customOrder.newOrderPages.map((orderPage: OrderPage) => orderPage.order))) - ) - ); - } - } diff --git a/src/app/core/data/registry-bitstreamformats-response-parsing.service.spec.ts b/src/app/core/data/registry-bitstreamformats-response-parsing.service.spec.ts deleted file mode 100644 index 6cc031f3c9..0000000000 --- a/src/app/core/data/registry-bitstreamformats-response-parsing.service.spec.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { PageInfo } from '../shared/page-info.model'; -import { DSOResponseParsingService } from './dso-response-parsing.service'; -import { DSpaceRESTV2Response } from '../dspace-rest-v2/dspace-rest-v2-response.model'; -import { - RegistryBitstreamformatsSuccessResponse -} from '../cache/response.models'; -import { RegistryBitstreamformatsResponseParsingService } from './registry-bitstreamformats-response-parsing.service'; - -describe('RegistryBitstreamformatsResponseParsingService', () => { - let service: RegistryBitstreamformatsResponseParsingService; - - const mockDSOParser = Object.assign({ - processPageInfo: () => new PageInfo() - }) as DSOResponseParsingService; - - const data = Object.assign({ - payload: { - _embedded: { - bitstreamformats: [ - { - uuid: 'uuid-1', - description: 'a description' - }, - { - uuid: 'uuid-2', - description: 'another description' - }, - ] - } - } - }) as DSpaceRESTV2Response; - - beforeEach(() => { - service = new RegistryBitstreamformatsResponseParsingService(mockDSOParser); - }); - - it('should parse the data correctly', () => { - const response = service.parse(null, data); - expect(response.constructor).toBe(RegistryBitstreamformatsSuccessResponse); - }); -}); diff --git a/src/app/core/data/registry-bitstreamformats-response-parsing.service.ts b/src/app/core/data/registry-bitstreamformats-response-parsing.service.ts deleted file mode 100644 index 1cbcf358e3..0000000000 --- a/src/app/core/data/registry-bitstreamformats-response-parsing.service.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { Injectable } from '@angular/core'; -import { RegistryBitstreamformatsSuccessResponse, RestResponse } from '../cache/response.models'; -import { DSpaceRESTV2Response } from '../dspace-rest-v2/dspace-rest-v2-response.model'; -import { DSpaceSerializer } from '../dspace-rest-v2/dspace.serializer'; -import { RegistryBitstreamformatsResponse } from '../registry/registry-bitstreamformats-response.model'; -import { DSOResponseParsingService } from './dso-response-parsing.service'; -import { ResponseParsingService } from './parsing.service'; -import { RestRequest } from './request.models'; - -@Injectable() -export class RegistryBitstreamformatsResponseParsingService implements ResponseParsingService { - constructor(private dsoParser: DSOResponseParsingService) { - } - - parse(request: RestRequest, data: DSpaceRESTV2Response): RestResponse { - const payload = data.payload; - - const bitstreamformats = payload._embedded.bitstreamformats; - payload.bitstreamformats = bitstreamformats; - - const deserialized = new DSpaceSerializer(RegistryBitstreamformatsResponse).deserialize(payload); - return new RegistryBitstreamformatsSuccessResponse(deserialized, data.statusCode, data.statusText, this.dsoParser.processPageInfo(data.payload.page)); - } - -} diff --git a/src/app/core/data/registry-metadatafields-response-parsing.service.spec.ts b/src/app/core/data/registry-metadatafields-response-parsing.service.spec.ts deleted file mode 100644 index 5ede21954a..0000000000 --- a/src/app/core/data/registry-metadatafields-response-parsing.service.spec.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { PageInfo } from '../shared/page-info.model'; -import { DSOResponseParsingService } from './dso-response-parsing.service'; -import { DSpaceRESTV2Response } from '../dspace-rest-v2/dspace-rest-v2-response.model'; -import { - RegistryMetadatafieldsSuccessResponse -} from '../cache/response.models'; -import { RegistryMetadatafieldsResponseParsingService } from './registry-metadatafields-response-parsing.service'; - -describe('RegistryMetadatafieldsResponseParsingService', () => { - let service: RegistryMetadatafieldsResponseParsingService; - - const mockDSOParser = Object.assign({ - processPageInfo: () => new PageInfo() - }) as DSOResponseParsingService; - - const data = Object.assign({ - payload: { - _embedded: { - metadatafields: [ - { - id: 1, - element: 'element', - qualifier: 'qualifier', - scopeNote: 'a scope note', - _embedded: { - schema: { - id: 1, - prefix: 'test', - namespace: 'test namespace' - } - } - }, - { - id: 2, - element: 'secondelement', - qualifier: 'secondqualifier', - scopeNote: 'a second scope note', - _embedded: { - schema: { - id: 1, - prefix: 'test', - namespace: 'test namespace' - } - } - }, - ] - } - } - }) as DSpaceRESTV2Response; - - const emptyData = Object.assign({ - payload: {} - }) as DSpaceRESTV2Response; - - beforeEach(() => { - service = new RegistryMetadatafieldsResponseParsingService(mockDSOParser); - }); - - it('should parse the data correctly', () => { - const response = service.parse(null, data); - expect(response.constructor).toBe(RegistryMetadatafieldsSuccessResponse); - }); - - it('should not produce an error and parse the data correctly when the data is empty', () => { - const response = service.parse(null, emptyData); - expect(response.constructor).toBe(RegistryMetadatafieldsSuccessResponse); - }); -}); diff --git a/src/app/core/data/registry-metadatafields-response-parsing.service.ts b/src/app/core/data/registry-metadatafields-response-parsing.service.ts deleted file mode 100644 index cf9484c4c4..0000000000 --- a/src/app/core/data/registry-metadatafields-response-parsing.service.ts +++ /dev/null @@ -1,34 +0,0 @@ -import { Injectable } from '@angular/core'; -import { hasValue } from '../../shared/empty.util'; -import { RegistryMetadatafieldsSuccessResponse, RestResponse } from '../cache/response.models'; -import { DSpaceRESTV2Response } from '../dspace-rest-v2/dspace-rest-v2-response.model'; -import { DSpaceSerializer } from '../dspace-rest-v2/dspace.serializer'; -import { RegistryMetadatafieldsResponse } from '../registry/registry-metadatafields-response.model'; -import { DSOResponseParsingService } from './dso-response-parsing.service'; -import { ResponseParsingService } from './parsing.service'; -import { RestRequest } from './request.models'; - -@Injectable() -export class RegistryMetadatafieldsResponseParsingService implements ResponseParsingService { - constructor(private dsoParser: DSOResponseParsingService) { - } - - parse(request: RestRequest, data: DSpaceRESTV2Response): RestResponse { - const payload = data.payload; - - let metadatafields = []; - - if (hasValue(payload._embedded)) { - metadatafields = payload._embedded.metadatafields; - metadatafields.forEach((field) => { - field.schema = field._embedded.schema; - }); - } - - payload.metadatafields = metadatafields; - - const deserialized = new DSpaceSerializer(RegistryMetadatafieldsResponse).deserialize(payload); - return new RegistryMetadatafieldsSuccessResponse(deserialized, data.statusCode, data.statusText, this.dsoParser.processPageInfo(data.payload)); - } - -} diff --git a/src/app/core/data/registry-metadataschemas-response-parsing.service.spec.ts b/src/app/core/data/registry-metadataschemas-response-parsing.service.spec.ts deleted file mode 100644 index e49305d06a..0000000000 --- a/src/app/core/data/registry-metadataschemas-response-parsing.service.spec.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { RegistryMetadataschemasResponseParsingService } from './registry-metadataschemas-response-parsing.service'; -import { PageInfo } from '../shared/page-info.model'; -import { DSOResponseParsingService } from './dso-response-parsing.service'; -import { DSpaceRESTV2Response } from '../dspace-rest-v2/dspace-rest-v2-response.model'; -import { RegistryMetadataschemasSuccessResponse } from '../cache/response.models'; - -describe('RegistryMetadataschemasResponseParsingService', () => { - let service: RegistryMetadataschemasResponseParsingService; - - const mockDSOParser = Object.assign({ - processPageInfo: () => new PageInfo() - }) as DSOResponseParsingService; - - const data = Object.assign({ - payload: { - _embedded: { - metadataschemas: [ - { - id: 1, - prefix: 'test', - namespace: 'test namespace' - }, - { - id: 2, - prefix: 'second', - namespace: 'second test namespace' - } - ] - } - } - }) as DSpaceRESTV2Response; - - const emptyData = Object.assign({ - payload: {} - }) as DSpaceRESTV2Response; - - beforeEach(() => { - service = new RegistryMetadataschemasResponseParsingService(mockDSOParser); - }); - - it('should parse the data correctly', () => { - const response = service.parse(null, data); - expect(response.constructor).toBe(RegistryMetadataschemasSuccessResponse); - }); - - it('should not produce an error and parse the data correctly when the data is empty', () => { - const response = service.parse(null, emptyData); - expect(response.constructor).toBe(RegistryMetadataschemasSuccessResponse); - }); -}); diff --git a/src/app/core/data/registry-metadataschemas-response-parsing.service.ts b/src/app/core/data/registry-metadataschemas-response-parsing.service.ts deleted file mode 100644 index 416ed19dc2..0000000000 --- a/src/app/core/data/registry-metadataschemas-response-parsing.service.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Injectable } from '@angular/core'; -import { hasValue } from '../../shared/empty.util'; -import { RegistryMetadataschemasSuccessResponse, RestResponse } from '../cache/response.models'; -import { DSpaceRESTV2Response } from '../dspace-rest-v2/dspace-rest-v2-response.model'; -import { DSpaceSerializer } from '../dspace-rest-v2/dspace.serializer'; -import { RegistryMetadataschemasResponse } from '../registry/registry-metadataschemas-response.model'; -import { DSOResponseParsingService } from './dso-response-parsing.service'; -import { ResponseParsingService } from './parsing.service'; -import { RestRequest } from './request.models'; - -@Injectable() -export class RegistryMetadataschemasResponseParsingService implements ResponseParsingService { - constructor(private dsoParser: DSOResponseParsingService) { - } - - parse(request: RestRequest, data: DSpaceRESTV2Response): RestResponse { - const payload = data.payload; - - let metadataschemas = []; - if (hasValue(payload._embedded)) { - metadataschemas = payload._embedded.metadataschemas; - } - payload.metadataschemas = metadataschemas; - - const deserialized = new DSpaceSerializer(RegistryMetadataschemasResponse).deserialize(payload); - return new RegistryMetadataschemasSuccessResponse(deserialized, data.statusCode, data.statusText, this.dsoParser.processPageInfo(data.payload)); - } - -} diff --git a/src/app/core/data/request.models.ts b/src/app/core/data/request.models.ts index 5866cce797..b484a2ba4e 100644 --- a/src/app/core/data/request.models.ts +++ b/src/app/core/data/request.models.ts @@ -14,8 +14,6 @@ import { RestRequestMethod } from './rest-request-method'; import { RequestParam } from '../cache/models/request-param.model'; import { EpersonResponseParsingService } from '../eperson/eperson-response-parsing.service'; import { BrowseItemsResponseParsingService } from './browse-items-response-parsing-service'; -import { MetadataschemaParsingService } from './metadataschema-parsing.service'; -import { MetadatafieldParsingService } from './metadatafield-parsing.service'; import { URLCombiner } from '../url-combiner/url-combiner'; import { TaskResponseParsingService } from '../tasks/task-response-parsing.service'; import { ContentSourceResponseParsingService } from './content-source-response-parsing.service'; @@ -251,58 +249,6 @@ export class IntegrationRequest extends GetRequest { } } -/** - * Request to create a MetadataSchema - */ -export class CreateMetadataSchemaRequest extends PostRequest { - constructor(uuid: string, href: string, public body?: any, public options?: HttpOptions) { - super(uuid, href, body, options); - } - - getResponseParser(): GenericConstructor { - return MetadataschemaParsingService; - } -} - -/** - * Request to update a MetadataSchema - */ -export class UpdateMetadataSchemaRequest extends PutRequest { - constructor(uuid: string, href: string, public body?: any, public options?: HttpOptions) { - super(uuid, href, body, options); - } - - getResponseParser(): GenericConstructor { - return MetadataschemaParsingService; - } -} - -/** - * Request to create a MetadataField - */ -export class CreateMetadataFieldRequest extends PostRequest { - constructor(uuid: string, href: string, public body?: any, public options?: HttpOptions) { - super(uuid, href, body, options); - } - - getResponseParser(): GenericConstructor { - return MetadatafieldParsingService; - } -} - -/** - * Request to update a MetadataField - */ -export class UpdateMetadataFieldRequest extends PutRequest { - constructor(uuid: string, href: string, public body?: any, public options?: HttpOptions) { - super(uuid, href, body, options); - } - - getResponseParser(): GenericConstructor { - return MetadatafieldParsingService; - } -} - /** * Class representing a submission HTTP GET request object */ diff --git a/src/app/core/data/request.service.ts b/src/app/core/data/request.service.ts index 105d84cf4a..9a2c565301 100644 --- a/src/app/core/data/request.service.ts +++ b/src/app/core/data/request.service.ts @@ -201,8 +201,9 @@ export class RequestService { * Remove all request cache providing (part of) the href * This also includes href-to-uuid index cache * @param href A substring of the request(s) href + * @return Returns an observable emitting whether or not the cache is removed */ - removeByHrefSubstring(href: string) { + removeByHrefSubstring(href: string): Observable { this.store.pipe( select(uuidsFromHrefSubstringSelector(requestIndexSelector, href)), take(1) @@ -213,6 +214,11 @@ export class RequestService { }); this.requestsOnTheirWayToTheStore = this.requestsOnTheirWayToTheStore.filter((reqHref: string) => reqHref.indexOf(href) < 0); this.indexStore.dispatch(new RemoveFromIndexBySubstringAction(IndexName.REQUEST, href)); + + return this.store.pipe( + select(uuidsFromHrefSubstringSelector(requestIndexSelector, href)), + map((uuids) => isEmpty(uuids)) + ); } /** diff --git a/src/app/core/registry/registry-bitstreamformats-response.model.ts b/src/app/core/registry/registry-bitstreamformats-response.model.ts deleted file mode 100644 index 4da30b4ffc..0000000000 --- a/src/app/core/registry/registry-bitstreamformats-response.model.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { autoserialize, deserialize } from 'cerialize'; -import { BITSTREAM_FORMAT } from '../shared/bitstream-format.resource-type'; -import { HALLink } from '../shared/hal-link.model'; -import { PageInfo } from '../shared/page-info.model'; -import { BitstreamFormat } from '../shared/bitstream-format.model'; -import { link } from '../cache/builders/build-decorators'; - -export class RegistryBitstreamformatsResponse { - @autoserialize - page: PageInfo; - - /** - * The {@link HALLink}s for this RegistryBitstreamformatsResponse - */ - @deserialize - _links: { - self: HALLink; - bitstreamformats: HALLink; - }; - - @link(BITSTREAM_FORMAT) - bitstreamformats?: BitstreamFormat[]; - -} diff --git a/src/app/core/registry/registry-metadatafields-response.model.ts b/src/app/core/registry/registry-metadatafields-response.model.ts deleted file mode 100644 index 5dc492ab0f..0000000000 --- a/src/app/core/registry/registry-metadatafields-response.model.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { autoserialize, deserialize } from 'cerialize'; -import { typedObject } from '../cache/builders/build-decorators'; -import { MetadataField } from '../metadata/metadata-field.model'; -import { METADATA_FIELD } from '../metadata/metadata-field.resource-type'; -import { HALLink } from '../shared/hal-link.model'; -import { PageInfo } from '../shared/page-info.model'; -import { ResourceType } from '../shared/resource-type'; -import { excludeFromEquals } from '../utilities/equals.decorators'; - -/** - * Class that represents a response with a registry's metadata fields - */ -@typedObject -export class RegistryMetadatafieldsResponse { - static type = METADATA_FIELD; - - /** - * The object type - */ - @excludeFromEquals - @autoserialize - type: ResourceType; - - /** - * List of metadata fields in the response - */ - @deserialize - metadatafields: MetadataField[]; - - /** - * Page info of this response - */ - @autoserialize - page: PageInfo; - - /** - * The REST link to this response - */ - @autoserialize - self: string; - - @deserialize - _links: { - self: HALLink, - } -} diff --git a/src/app/core/registry/registry-metadataschemas-response.model.ts b/src/app/core/registry/registry-metadataschemas-response.model.ts deleted file mode 100644 index 7a485d8849..0000000000 --- a/src/app/core/registry/registry-metadataschemas-response.model.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { PageInfo } from '../shared/page-info.model'; -import { autoserialize, deserialize } from 'cerialize'; -import { MetadataSchema } from '../metadata/metadata-schema.model'; - -export class RegistryMetadataschemasResponse { - @deserialize - metadataschemas: MetadataSchema[]; - - @autoserialize - page: PageInfo; - - @autoserialize - self: string; -} diff --git a/src/app/core/registry/registry.service.spec.ts b/src/app/core/registry/registry.service.spec.ts index d1d817ff36..203e58136c 100644 --- a/src/app/core/registry/registry.service.spec.ts +++ b/src/app/core/registry/registry.service.spec.ts @@ -3,8 +3,7 @@ import { Component } from '@angular/core'; import { TestBed } from '@angular/core/testing'; import { Store, StoreModule } from '@ngrx/store'; import { TranslateModule } from '@ngx-translate/core'; -import { combineLatest as observableCombineLatest, Observable, of as observableOf } from 'rxjs'; -import { map } from 'rxjs/operators'; +import { Observable, of as observableOf } from 'rxjs'; import { MetadataRegistryCancelFieldAction, MetadataRegistryCancelSchemaAction, @@ -17,30 +16,20 @@ import { MetadataRegistrySelectFieldAction, MetadataRegistrySelectSchemaAction } from '../../+admin/admin-registries/metadata-registry/metadata-registry.actions'; -import { getMockRequestService } from '../../shared/mocks/request.service.mock'; import { NotificationsService } from '../../shared/notifications/notifications.service'; -import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model'; import { StoreMock } from '../../shared/testing/store.mock'; import { NotificationsServiceStub } from '../../shared/testing/notifications-service.stub'; -import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils'; -import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; -import { - RegistryMetadatafieldsSuccessResponse, - RegistryMetadataschemasSuccessResponse, - RestResponse -} from '../cache/response.models'; -import { RemoteData } from '../data/remote-data'; -import { RequestEntry } from '../data/request.reducer'; -import { RequestService } from '../data/request.service'; +import { RestResponse } from '../cache/response.models'; import { MetadataField } from '../metadata/metadata-field.model'; import { MetadataSchema } from '../metadata/metadata-schema.model'; -import { HALEndpointService } from '../shared/hal-endpoint.service'; -import { PageInfo } from '../shared/page-info.model'; -import { RegistryMetadatafieldsResponse } from './registry-metadatafields-response.model'; -import { RegistryMetadataschemasResponse } from './registry-metadataschemas-response.model'; import { RegistryService } from './registry.service'; import { storeModuleConfig } from '../../app.reducer'; +import { FindListOptions } from '../data/request.models'; +import { MetadataSchemaDataService } from '../data/metadata-schema-data.service'; +import { MetadataFieldDataService } from '../data/metadata-field-data.service'; +import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils'; +import { createPaginatedList } from '../../shared/testing/utils.test'; @Component({ template: '' }) class DummyComponent { @@ -49,211 +38,169 @@ class DummyComponent { describe('RegistryService', () => { let registryService: RegistryService; let mockStore; - const pagination: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), { - id: 'registry-service-spec-pagination', - pageSize: 20 - }); + let metadataSchemaService: MetadataSchemaDataService; + let metadataFieldService: MetadataFieldDataService; - const mockSchemasList = [ - Object.assign(new MetadataSchema(), { - id: 1, - _links: { - self: { href: 'https://dspace7.4science.it/dspace-spring-rest/api/core/metadataschemas/1' } - }, - prefix: 'dc', - namespace: 'http://dublincore.org/documents/dcmi-terms/', - type: MetadataSchema.type - }), - Object.assign(new MetadataSchema(), { - id: 2, - _links: { - self: { href: 'https://dspace7.4science.it/dspace-spring-rest/api/core/metadataschemas/2' } - }, - prefix: 'mock', - namespace: 'http://dspace.org/mockschema', - type: MetadataSchema.type - }) - ]; - const mockFieldsList = [ - Object.assign(new MetadataField(), - { + let options: FindListOptions; + let mockSchemasList: MetadataSchema[]; + let mockFieldsList: MetadataField[]; + + function init() { + options = Object.assign(new FindListOptions(), { + currentPage: 1, + elementsPerPage: 20 + }); + + mockSchemasList = [ + Object.assign(new MetadataSchema(), { id: 1, _links: { - self: { href: 'https://dspace7.4science.it/dspace-spring-rest/api/core/metadatafields/8' } + self: { href: 'https://dspace7.4science.it/dspace-spring-rest/api/core/metadataschemas/1' } }, - element: 'contributor', - qualifier: 'advisor', - scopeNote: null, - schema: mockSchemasList[0], - type: MetadataField.type + prefix: 'dc', + namespace: 'http://dublincore.org/documents/dcmi-terms/', + type: MetadataSchema.type }), - Object.assign(new MetadataField(), - { + Object.assign(new MetadataSchema(), { id: 2, _links: { - self: { href: 'https://dspace7.4science.it/dspace-spring-rest/api/core/metadatafields/9' } + self: { href: 'https://dspace7.4science.it/dspace-spring-rest/api/core/metadataschemas/2' } }, - element: 'contributor', - qualifier: 'author', - scopeNote: null, - schema: mockSchemasList[0], - type: MetadataField.type - }), - Object.assign(new MetadataField(), - { - id: 3, - _links: { - self: { href: 'https://dspace7.4science.it/dspace-spring-rest/api/core/metadatafields/10' } - }, - element: 'contributor', - qualifier: 'editor', - scopeNote: 'test scope note', - schema: mockSchemasList[1], - type: MetadataField.type - }), - Object.assign(new MetadataField(), - { - id: 4, - _links: { - self: { href: 'https://dspace7.4science.it/dspace-spring-rest/api/core/metadatafields/11' } - }, - element: 'contributor', - qualifier: 'illustrator', - scopeNote: null, - schema: mockSchemasList[1], - type: MetadataField.type + prefix: 'mock', + namespace: 'http://dspace.org/mockschema', + type: MetadataSchema.type }) - ]; + ]; - const pageInfo = new PageInfo(); - pageInfo.elementsPerPage = 20; - pageInfo.currentPage = 1; - - const endpoint = 'path'; - const endpointWithParams = `${endpoint}?size=${pageInfo.elementsPerPage}&page=${pageInfo.currentPage - 1}`; - const fieldEndpointWithParams = `${endpoint}?schema=${mockSchemasList[0].prefix}&size=${pageInfo.elementsPerPage}&page=${pageInfo.currentPage - 1}`; - - const halServiceStub = { - getEndpoint: (link: string) => observableOf(endpoint) - }; - - const rdbStub = { - toRemoteDataObservable: (requestEntryObs: Observable, payloadObs: Observable) => { - return observableCombineLatest(requestEntryObs, - payloadObs).pipe(map(([req, pay]) => { - return { req, pay }; + mockFieldsList = [ + Object.assign(new MetadataField(), + { + id: 1, + _links: { + self: { href: 'https://dspace7.4science.it/dspace-spring-rest/api/core/metadatafields/8' } + }, + element: 'contributor', + qualifier: 'advisor', + scopeNote: null, + schema: mockSchemasList[0], + type: MetadataField.type + }), + Object.assign(new MetadataField(), + { + id: 2, + _links: { + self: { href: 'https://dspace7.4science.it/dspace-spring-rest/api/core/metadatafields/9' } + }, + element: 'contributor', + qualifier: 'author', + scopeNote: null, + schema: mockSchemasList[0], + type: MetadataField.type + }), + Object.assign(new MetadataField(), + { + id: 3, + _links: { + self: { href: 'https://dspace7.4science.it/dspace-spring-rest/api/core/metadatafields/10' } + }, + element: 'contributor', + qualifier: 'editor', + scopeNote: 'test scope note', + schema: mockSchemasList[1], + type: MetadataField.type + }), + Object.assign(new MetadataField(), + { + id: 4, + _links: { + self: { href: 'https://dspace7.4science.it/dspace-spring-rest/api/core/metadatafields/11' } + }, + element: 'contributor', + qualifier: 'illustrator', + scopeNote: null, + schema: mockSchemasList[1], + type: MetadataField.type }) - ); - }, - aggregate: (input: Array>>): Observable> => { - return createSuccessfulRemoteDataObject$([]); - } - }; + ]; + + metadataSchemaService = jasmine.createSpyObj('metadataSchemaService', { + findAll: createSuccessfulRemoteDataObject$(createPaginatedList(mockSchemasList)), + findById: createSuccessfulRemoteDataObject$(mockSchemasList[0]), + createOrUpdateMetadataSchema: createSuccessfulRemoteDataObject$(mockSchemasList[0]), + deleteAndReturnResponse: observableOf(new RestResponse(true, 200, 'OK')), + clearRequests: observableOf('href') + }); + + metadataFieldService = jasmine.createSpyObj('metadataFieldService', { + findAll: createSuccessfulRemoteDataObject$(createPaginatedList(mockFieldsList)), + findById: createSuccessfulRemoteDataObject$(mockFieldsList[0]), + createOrUpdateMetadataField: createSuccessfulRemoteDataObject$(mockFieldsList[0]), + deleteAndReturnResponse: observableOf(new RestResponse(true, 200, 'OK')), + clearRequests: observableOf('href') + }); + } beforeEach(() => { + init(); TestBed.configureTestingModule({ imports: [CommonModule, StoreModule.forRoot({}, storeModuleConfig), TranslateModule.forRoot()], declarations: [ DummyComponent ], providers: [ - { provide: RequestService, useValue: getMockRequestService() }, - { provide: RemoteDataBuildService, useValue: rdbStub }, - { provide: HALEndpointService, useValue: halServiceStub }, { provide: Store, useClass: StoreMock }, { provide: NotificationsService, useValue: new NotificationsServiceStub() }, + { provide: MetadataSchemaDataService, useValue: metadataSchemaService }, + { provide: MetadataFieldDataService, useValue: metadataFieldService }, RegistryService ] }); registryService = TestBed.get(RegistryService); mockStore = TestBed.get(Store); - spyOn((registryService as any).halService, 'getEndpoint').and.returnValue(observableOf(endpoint)); }); describe('when requesting metadataschemas', () => { - const queryResponse = Object.assign(new RegistryMetadataschemasResponse(), { - metadataschemas: mockSchemasList, - page: pageInfo - }); - const response = new RegistryMetadataschemasSuccessResponse(queryResponse, 200, 'OK', pageInfo); - const responseEntry = Object.assign(new RequestEntry(), { response: response }); + let result; beforeEach(() => { - (registryService as any).requestService.getByHref.and.returnValue(observableOf(responseEntry)); - /* tslint:disable:no-empty */ - registryService.getMetadataSchemas(pagination).subscribe((value) => { + result = registryService.getMetadataSchemas(options); + }); + + it('should call metadataSchemaService.findAll', (done) => { + result.subscribe(() => { + expect(metadataSchemaService.findAll).toHaveBeenCalled(); + done(); }); - /* tslint:enable:no-empty */ - }); - - it('should call getEndpoint on the halService', () => { - expect((registryService as any).halService.getEndpoint).toHaveBeenCalled(); - }); - - it('should send out the request on the request service', () => { - expect((registryService as any).requestService.configure).toHaveBeenCalled(); - }); - - it('should call getByHref on the request service with the correct request url', () => { - expect((registryService as any).requestService.getByHref).toHaveBeenCalledWith(endpointWithParams); }); }); describe('when requesting metadataschema by name', () => { - const queryResponse = Object.assign(new RegistryMetadataschemasResponse(), { - metadataschemas: mockSchemasList, - page: pageInfo - }); - const response = new RegistryMetadataschemasSuccessResponse(queryResponse, 200, 'OK', pageInfo); - const responseEntry = Object.assign(new RequestEntry(), { response: response }); + let result; beforeEach(() => { - (registryService as any).requestService.getByHref.and.returnValue(observableOf(responseEntry)); - /* tslint:disable:no-empty */ - registryService.getMetadataSchemaByName(mockSchemasList[0].prefix).subscribe((value) => { + result = registryService.getMetadataSchemaByName(mockSchemasList[0].prefix); + }); + + it('should call metadataSchemaService.findById with the correct ID', (done) => { + result.subscribe(() => { + expect(metadataSchemaService.findById).toHaveBeenCalledWith(`${mockSchemasList[0].id}`); + done(); }); - /* tslint:enable:no-empty */ - }); - - it('should call getEndpoint on the halService', () => { - expect((registryService as any).halService.getEndpoint).toHaveBeenCalled(); - }); - - it('should send out the request on the request service', () => { - expect((registryService as any).requestService.configure).toHaveBeenCalled(); - }); - - it('should call getByHref on the request service with the correct request url', () => { - expect((registryService as any).requestService.getByHref.calls.argsFor(0)[0]).toContain(endpoint); }); }); describe('when requesting metadatafields', () => { - const queryResponse = Object.assign(new RegistryMetadatafieldsResponse(), { - metadatafields: mockFieldsList, - page: pageInfo - }); - const response = new RegistryMetadatafieldsSuccessResponse(queryResponse, 200, 'OK', pageInfo); - const responseEntry = Object.assign(new RequestEntry(), { response: response }); + let result; beforeEach(() => { - (registryService as any).requestService.getByHref.and.returnValue(observableOf(responseEntry)); - /* tslint:disable:no-empty */ - registryService.getMetadataFieldsBySchema(mockSchemasList[0], pagination).subscribe((value) => { + result = registryService.getAllMetadataFields(); + }); + + it('should call metadataFieldService.findAll', (done) => { + result.subscribe(() => { + expect(metadataFieldService.findAll).toHaveBeenCalled(); + done(); }); - /* tslint:enable:no-empty */ - }); - - it('should call getEndpoint on the halService', () => { - expect((registryService as any).halService.getEndpoint).toHaveBeenCalled(); - }); - - it('should send out the request on the request service', () => { - expect((registryService as any).requestService.configure).toHaveBeenCalled(); - }); - - it('should call getByHref on the request service with the correct request url', () => { - expect((registryService as any).requestService.getByHref).toHaveBeenCalledWith(fieldEndpointWithParams); }); }); @@ -370,9 +317,10 @@ describe('RegistryService', () => { result = registryService.createOrUpdateMetadataSchema(mockSchemasList[0]); }); - it('should return the created/updated metadata schema', () => { + it('should return the created/updated metadata schema', (done) => { result.subscribe((schema: MetadataSchema) => { expect(schema).toEqual(mockSchemasList[0]); + done(); }); }); }); @@ -384,9 +332,10 @@ describe('RegistryService', () => { result = registryService.createOrUpdateMetadataField(mockFieldsList[0]); }); - it('should return the created/updated metadata field', () => { + it('should return the created/updated metadata field', (done) => { result.subscribe((field: MetadataField) => { expect(field).toEqual(mockFieldsList[0]); + done(); }); }); }); @@ -425,7 +374,7 @@ describe('RegistryService', () => { }); it('should remove the requests related to metadata schemas from cache', () => { - expect((registryService as any).requestService.removeByHrefSubstring).toHaveBeenCalled(); + expect(metadataSchemaService.clearRequests).toHaveBeenCalled(); }); }); @@ -435,7 +384,7 @@ describe('RegistryService', () => { }); it('should remove the requests related to metadata fields from cache', () => { - expect((registryService as any).requestService.removeByHrefSubstring).toHaveBeenCalled(); + expect(metadataFieldService.clearRequests).toHaveBeenCalled(); }); }); }); diff --git a/src/app/core/registry/registry.service.ts b/src/app/core/registry/registry.service.ts index fbc42b26f4..79b982da8a 100644 --- a/src/app/core/registry/registry.service.ts +++ b/src/app/core/registry/registry.service.ts @@ -2,37 +2,18 @@ import { combineLatest as observableCombineLatest, Observable } from 'rxjs'; import { Injectable } from '@angular/core'; import { RemoteData } from '../data/remote-data'; import { PaginatedList } from '../data/paginated-list'; -import { DSpaceSerializer } from '../dspace-rest-v2/dspace.serializer'; import { PageInfo } from '../shared/page-info.model'; -import { - CreateMetadataFieldRequest, - CreateMetadataSchemaRequest, - DeleteRequest, - GetRequest, - RestRequest, - UpdateMetadataFieldRequest, - UpdateMetadataSchemaRequest -} from '../data/request.models'; -import { GenericConstructor } from '../shared/generic-constructor'; -import { ResponseParsingService } from '../data/parsing.service'; -import { RegistryMetadataschemasResponseParsingService } from '../data/registry-metadataschemas-response-parsing.service'; +import { FindListOptions } from '../data/request.models'; import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; import { RequestService } from '../data/request.service'; -import { RegistryMetadataschemasResponse } from './registry-metadataschemas-response.model'; import { MetadatafieldSuccessResponse, MetadataschemaSuccessResponse, - RegistryMetadatafieldsSuccessResponse, - RegistryMetadataschemasSuccessResponse, RestResponse } from '../cache/response.models'; import { HALEndpointService } from '../shared/hal-endpoint.service'; -import { RegistryMetadatafieldsResponseParsingService } from '../data/registry-metadatafields-response-parsing.service'; -import { RegistryMetadatafieldsResponse } from './registry-metadatafields-response.model'; -import { hasNoValue, hasValue, isNotEmpty, isNotEmptyOperator } from '../../shared/empty.util'; -import { URLCombiner } from '../url-combiner/url-combiner'; -import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model'; -import { configureRequest, getResponseFromEntry } from '../shared/operators'; +import { hasNoValue, hasValue, hasValueOperator, isNotEmpty, isNotEmptyOperator } from '../../shared/empty.util'; +import { getAllSucceededRemoteDataPayload, getFirstSucceededRemoteDataPayload } from '../shared/operators'; import { createSelector, select, Store } from '@ngrx/store'; import { AppState } from '../../app.reducer'; import { MetadataRegistryState } from '../../+admin/admin-registries/metadata-registry/metadata-registry.reducers'; @@ -48,15 +29,14 @@ import { MetadataRegistrySelectFieldAction, MetadataRegistrySelectSchemaAction } from '../../+admin/admin-registries/metadata-registry/metadata-registry.actions'; -import { distinctUntilChanged, flatMap, map, take, tap } from 'rxjs/operators'; +import { flatMap, map, tap } from 'rxjs/operators'; import { NotificationsService } from '../../shared/notifications/notifications.service'; -import { NotificationOptions } from '../../shared/notifications/models/notification-options.model'; -import { HttpOptions } from '../dspace-rest-v2/dspace-rest-v2.service'; -import { HttpHeaders } from '@angular/common/http'; import { TranslateService } from '@ngx-translate/core'; import { MetadataSchema } from '../metadata/metadata-schema.model'; import { MetadataField } from '../metadata/metadata-field.model'; -import { getClassForType } from '../cache/builders/build-decorators'; +import { MetadataSchemaDataService } from '../data/metadata-schema-data.service'; +import { MetadataFieldDataService } from '../data/metadata-field-data.service'; +import { FollowLinkConfig } from '../../shared/utils/follow-link-config.model'; const metadataRegistryStateSelector = (state: AppState) => state.metadataRegistry; const editMetadataSchemaSelector = createSelector(metadataRegistryStateSelector, (metadataState: MetadataRegistryState) => metadataState.editSchema); @@ -70,221 +50,64 @@ const selectedMetadataFieldsSelector = createSelector(metadataRegistryStateSelec @Injectable() export class RegistryService { - private metadataSchemasPath = 'metadataschemas'; - private metadataFieldsPath = 'metadatafields'; - - // private bitstreamFormatsPath = 'bitstreamformats'; - - constructor(protected requestService: RequestService, - private rdb: RemoteDataBuildService, - private halService: HALEndpointService, - private store: Store, + constructor(private store: Store, private notificationsService: NotificationsService, - private translateService: TranslateService) { + private translateService: TranslateService, + private metadataSchemaService: MetadataSchemaDataService, + private metadataFieldService: MetadataFieldDataService) { } /** * Retrieves all metadata schemas - * @param pagination The pagination info used to retrieve the schemas + * @param options The options used to retrieve the schemas + * @param linksToFollow List of {@link FollowLinkConfig} that indicate which {@link HALLink}s should be automatically resolved */ - public getMetadataSchemas(pagination: PaginationComponentOptions): Observable>> { - const requestObs = this.getMetadataSchemasRequestObs(pagination); - - const requestEntryObs = requestObs.pipe( - flatMap((request: RestRequest) => this.requestService.getByHref(request.href)) - ); - - const rmrObs: Observable = requestEntryObs.pipe( - getResponseFromEntry(), - map((response: RegistryMetadataschemasSuccessResponse) => response.metadataschemasResponse) - ); - - const metadataschemasObs: Observable = rmrObs.pipe( - map((rmr: RegistryMetadataschemasResponse) => rmr.metadataschemas) - ); - - const pageInfoObs: Observable = requestEntryObs.pipe( - getResponseFromEntry(), - map((response: RegistryMetadataschemasSuccessResponse) => response.pageInfo) - ); - - const payloadObs = observableCombineLatest(metadataschemasObs, pageInfoObs).pipe( - map(([metadataschemas, pageInfo]) => { - return new PaginatedList(pageInfo, metadataschemas); - }) - ); - - return this.rdb.toRemoteDataObservable(requestEntryObs, payloadObs); + public getMetadataSchemas(options: FindListOptions = {}, ...linksToFollow: Array>): Observable>> { + return this.metadataSchemaService.findAll(options, ...linksToFollow); } /** * Retrieves a metadata schema by its name * @param schemaName The name of the schema to find + * @param linksToFollow List of {@link FollowLinkConfig} that indicate which {@link HALLink}s should be automatically resolved */ - public getMetadataSchemaByName(schemaName: string): Observable> { - // Temporary pagination to get ALL metadataschemas until there's a rest api endpoint for fetching a specific schema - const pagination: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), { - id: 'all-metadatafields-pagination', - pageSize: 10000 + public getMetadataSchemaByName(schemaName: string, ...linksToFollow: Array>): Observable> { + // Temporary options to get ALL metadataschemas until there's a rest api endpoint for fetching a specific schema + const options: FindListOptions = Object.assign(new FindListOptions(), { + elementsPerPage: 10000 }); - const requestObs = this.getMetadataSchemasRequestObs(pagination); - - const requestEntryObs = requestObs.pipe( - flatMap((request: RestRequest) => this.requestService.getByHref(request.href)) + return this.getMetadataSchemas(options).pipe( + getFirstSucceededRemoteDataPayload(), + map((schemas: PaginatedList) => schemas.page), + isNotEmptyOperator(), + map((schemas: MetadataSchema[]) => schemas.filter((schema) => schema.prefix === schemaName)[0]), + flatMap((schema: MetadataSchema) => this.metadataSchemaService.findById(`${schema.id}`, ...linksToFollow)) ); - - const rmrObs: Observable = requestEntryObs.pipe( - getResponseFromEntry(), - map((response: RegistryMetadataschemasSuccessResponse) => response.metadataschemasResponse) - ); - - const metadataschemaObs: Observable = rmrObs.pipe( - map((rmr: RegistryMetadataschemasResponse) => rmr.metadataschemas), - map((metadataSchemas: MetadataSchema[]) => metadataSchemas.filter((value) => value.prefix === schemaName)[0]) - ); - - return this.rdb.toRemoteDataObservable(requestEntryObs, metadataschemaObs); } /** * retrieves all metadata fields that belong to a certain metadata schema * @param schema The schema to filter by - * @param pagination The pagination info used to retrieve the fields + * @param options The options info used to retrieve the fields + * @param linksToFollow List of {@link FollowLinkConfig} that indicate which {@link HALLink}s should be automatically resolved */ - public getMetadataFieldsBySchema(schema: MetadataSchema, pagination: PaginationComponentOptions): Observable>> { - const requestObs = this.getMetadataFieldsBySchemaRequestObs(pagination, schema); - - const requestEntryObs = requestObs.pipe( - flatMap((request: RestRequest) => this.requestService.getByHref(request.href)) - ); - - const rmrObs: Observable = requestEntryObs.pipe( - getResponseFromEntry(), - map((response: RegistryMetadatafieldsSuccessResponse) => response.metadatafieldsResponse) - ); - - const metadatafieldsObs: Observable = rmrObs.pipe( - map((rmr: RegistryMetadatafieldsResponse) => rmr.metadatafields) - ); - - const pageInfoObs: Observable = requestEntryObs.pipe( - getResponseFromEntry(), - - map((response: RegistryMetadatafieldsSuccessResponse) => response.pageInfo) - ); - - const payloadObs = observableCombineLatest(metadatafieldsObs, pageInfoObs).pipe( - map(([metadatafields, pageInfo]) => { - return new PaginatedList(pageInfo, metadatafields); - }) - ); - - return this.rdb.toRemoteDataObservable(requestEntryObs, payloadObs); + public getMetadataFieldsBySchema(schema: MetadataSchema, options: FindListOptions = {}, ...linksToFollow: Array>): Observable>> { + return this.metadataFieldService.findBySchema(schema, options, ...linksToFollow); } /** * Retrieve all existing metadata fields as a paginated list - * @param pagination Pagination options to determine which page of metadata fields should be requested - * When no pagination is provided, all metadata fields are requested in one large page + * @param options Options to determine which page of metadata fields should be requested + * When no options are provided, all metadata fields are requested in one large page + * @param linksToFollow List of {@link FollowLinkConfig} that indicate which {@link HALLink}s should be automatically resolved * @returns an observable that emits a remote data object with a page of metadata fields */ - public getAllMetadataFields(pagination?: PaginationComponentOptions): Observable>> { - if (hasNoValue(pagination)) { - pagination = {currentPage: 1, pageSize: 10000} as any; + public getAllMetadataFields(options?: FindListOptions, ...linksToFollow: Array>): Observable>> { + if (hasNoValue(options)) { + options = {currentPage: 1, elementsPerPage: 10000} as any; } - const requestObs = this.getMetadataFieldsRequestObs(pagination); - - const requestEntryObs = requestObs.pipe( - flatMap((request: RestRequest) => this.requestService.getByHref(request.href)) - ); - - const rmrObs: Observable = requestEntryObs.pipe( - getResponseFromEntry(), - map((response: RegistryMetadatafieldsSuccessResponse) => response.metadatafieldsResponse) - ); - - const metadatafieldsObs: Observable = rmrObs.pipe( - map((rmr: RegistryMetadatafieldsResponse) => rmr.metadatafields), - /* Make sure to explicitly cast this into a MetadataField object, on first page loads this object comes from the object cache created by the server and its prototype is unknown */ - map((metadataFields: MetadataField[]) => metadataFields.map((metadataField: MetadataField) => Object.assign(new MetadataField(), metadataField))) - ); - - const pageInfoObs: Observable = requestEntryObs.pipe( - getResponseFromEntry(), - - map((response: RegistryMetadatafieldsSuccessResponse) => response.pageInfo) - ); - - const payloadObs = observableCombineLatest(metadatafieldsObs, pageInfoObs).pipe( - map(([metadatafields, pageInfo]) => { - return new PaginatedList(pageInfo, metadatafields); - }) - ); - - return this.rdb.toRemoteDataObservable(requestEntryObs, payloadObs); - } - - public getMetadataSchemasRequestObs(pagination: PaginationComponentOptions): Observable { - return this.halService.getEndpoint(this.metadataSchemasPath).pipe( - map((url: string) => { - const args: string[] = []; - args.push(`size=${pagination.pageSize}`); - args.push(`page=${pagination.currentPage - 1}`); - if (isNotEmpty(args)) { - url = new URLCombiner(url, `?${args.join('&')}`).toString(); - } - const request = new GetRequest(this.requestService.generateRequestId(), url); - return Object.assign(request, { - getResponseParser(): GenericConstructor { - return RegistryMetadataschemasResponseParsingService; - } - }); - }), - tap((request: RestRequest) => this.requestService.configure(request)), - ); - } - - private getMetadataFieldsBySchemaRequestObs(pagination: PaginationComponentOptions, schema: MetadataSchema): Observable { - return this.halService.getEndpoint(this.metadataFieldsPath + '/search/bySchema').pipe( - // return this.halService.getEndpoint(this.metadataFieldsPath).pipe( - map((url: string) => { - const args: string[] = []; - args.push(`schema=${schema.prefix}`); - args.push(`size=${pagination.pageSize}`); - args.push(`page=${pagination.currentPage - 1}`); - if (isNotEmpty(args)) { - url = new URLCombiner(url, `?${args.join('&')}`).toString(); - } - const request = new GetRequest(this.requestService.generateRequestId(), url); - return Object.assign(request, { - getResponseParser(): GenericConstructor { - return RegistryMetadatafieldsResponseParsingService; - } - }); - }), - tap((request: RestRequest) => this.requestService.configure(request)), - ); - } - - private getMetadataFieldsRequestObs(pagination: PaginationComponentOptions): Observable { - return this.halService.getEndpoint(this.metadataFieldsPath).pipe( - map((url: string) => { - const args: string[] = []; - args.push(`size=${pagination.pageSize}`); - args.push(`page=${pagination.currentPage - 1}`); - if (isNotEmpty(args)) { - url = new URLCombiner(url, `?${args.join('&')}`).toString(); - } - const request = new GetRequest(this.requestService.generateRequestId(), url); - return Object.assign(request, { - getResponseParser(): GenericConstructor { - return RegistryMetadatafieldsResponseParsingService; - } - }); - }), - tap((request: RestRequest) => this.requestService.configure(request)), - ); + return this.metadataFieldService.findAll(options, ...linksToFollow); } public editMetadataSchema(schema: MetadataSchema) { @@ -386,59 +209,17 @@ export class RegistryService { * Create or Update a MetadataSchema * If the MetadataSchema contains an id, it is assumed the schema already exists and is updated instead * Since creating or updating is nearly identical, the only real difference is the request (and slight difference in endpoint): - * - On creation, a CreateMetadataSchemaRequest is used - * - On update, a UpdateMetadataSchemaRequest is used + * - On creation, a CreateRequest is used + * - On update, a PutRequest is used * @param schema The MetadataSchema to create or update */ public createOrUpdateMetadataSchema(schema: MetadataSchema): Observable { const isUpdate = hasValue(schema.id); - const requestId = this.requestService.generateRequestId(); - const endpoint$ = this.halService.getEndpoint(this.metadataSchemasPath).pipe( - isNotEmptyOperator(), - map((endpoint: string) => (isUpdate ? `${endpoint}/${schema.id}` : endpoint)), - distinctUntilChanged() - ); - - const serializedSchema = new DSpaceSerializer(getClassForType(MetadataSchema.type)).serialize(schema); - - const request$ = endpoint$.pipe( - take(1), - map((endpoint: string) => { - if (isUpdate) { - const options: HttpOptions = Object.create({}); - let headers = new HttpHeaders(); - headers = headers.append('Content-Type', 'application/json'); - options.headers = headers; - return new UpdateMetadataSchemaRequest(requestId, endpoint, JSON.stringify(serializedSchema), options); - } else { - return new CreateMetadataSchemaRequest(requestId, endpoint, JSON.stringify(serializedSchema)); - } - }) - ); - - // Execute the post/put request - request$.pipe( - configureRequest(this.requestService) - ).subscribe(); - - // Return created/updated schema - return this.requestService.getByUUID(requestId).pipe( - getResponseFromEntry(), - map((response: RestResponse) => { - if (!response.isSuccessful) { - if (hasValue((response as any).errorMessage)) { - this.notificationsService.error('Server Error:', (response as any).errorMessage, new NotificationOptions(-1)); - } - } else { - this.showNotifications(true, isUpdate, false, {prefix: schema.prefix}); - return response; - } - }), - isNotEmptyOperator(), - map((response: MetadataschemaSuccessResponse) => { - if (isNotEmpty(response.metadataschema)) { - return response.metadataschema; - } + return this.metadataSchemaService.createOrUpdateMetadataSchema(schema).pipe( + getFirstSucceededRemoteDataPayload(), + hasValueOperator(), + tap(() => { + this.showNotifications(true, isUpdate, false, {prefix: schema.prefix}); }) ); } @@ -448,74 +229,32 @@ export class RegistryService { * @param id The id of the metadata schema to delete */ public deleteMetadataSchema(id: number): Observable { - return this.delete(this.metadataSchemasPath, id); + return this.metadataSchemaService.deleteAndReturnResponse(`${id}`); } /** * Method that clears a cached metadata schema request and returns its REST url */ public clearMetadataSchemaRequests(): Observable { - return this.halService.getEndpoint(this.metadataSchemasPath).pipe( - tap((href: string) => this.requestService.removeByHrefSubstring(href)) - ); + return this.metadataSchemaService.clearRequests(); } /** * Create or Update a MetadataField * If the MetadataField contains an id, it is assumed the field already exists and is updated instead * Since creating or updating is nearly identical, the only real difference is the request (and slight difference in endpoint): - * - On creation, a CreateMetadataFieldRequest is used - * - On update, a UpdateMetadataFieldRequest is used + * - On creation, a CreateRequest is used + * - On update, a PutRequest is used * @param field The MetadataField to create or update */ public createOrUpdateMetadataField(field: MetadataField): Observable { const isUpdate = hasValue(field.id); - const requestId = this.requestService.generateRequestId(); - const endpoint$ = this.halService.getEndpoint(this.metadataFieldsPath).pipe( - isNotEmptyOperator(), - map((endpoint: string) => (isUpdate ? `${endpoint}/${field.id}` : `${endpoint}?schemaId=${field.schema.id}`)), - distinctUntilChanged() - ); - - const request$ = endpoint$.pipe( - take(1), - map((endpoint: string) => { - if (isUpdate) { - const options: HttpOptions = Object.create({}); - let headers = new HttpHeaders(); - headers = headers.append('Content-Type', 'application/json'); - options.headers = headers; - return new UpdateMetadataFieldRequest(requestId, endpoint, JSON.stringify(field), options); - } else { - return new CreateMetadataFieldRequest(requestId, endpoint, JSON.stringify(field)); - } - }) - ); - - // Execute the post/put request - request$.pipe( - configureRequest(this.requestService) - ).subscribe(); - - // Return created/updated field - return this.requestService.getByUUID(requestId).pipe( - getResponseFromEntry(), - map((response: RestResponse) => { - if (!response.isSuccessful) { - if (hasValue((response as any).errorMessage)) { - this.notificationsService.error('Server Error:', (response as any).errorMessage, new NotificationOptions(-1)); - } - } else { - const fieldString = `${field.schema.prefix}.${field.element}${field.qualifier ? `.${field.qualifier}` : ''}`; - this.showNotifications(true, isUpdate, true, {field: fieldString}); - return response; - } - }), - isNotEmptyOperator(), - map((response: MetadatafieldSuccessResponse) => { - if (isNotEmpty(response.metadatafield)) { - return response.metadatafield; - } + return this.metadataFieldService.createOrUpdateMetadataField(field).pipe( + getFirstSucceededRemoteDataPayload(), + hasValueOperator(), + tap(() => { + const fieldString = `${field.schema.prefix}.${field.element}${field.qualifier ? `.${field.qualifier}` : ''}`; + this.showNotifications(true, isUpdate, true, {field: fieldString}); }) ); } @@ -525,38 +264,13 @@ export class RegistryService { * @param id The id of the metadata field to delete */ public deleteMetadataField(id: number): Observable { - return this.delete(this.metadataFieldsPath, id); + return this.metadataFieldService.deleteAndReturnResponse(`${id}`); } /** * Method that clears a cached metadata field request and returns its REST url */ public clearMetadataFieldRequests(): Observable { - return this.halService.getEndpoint(this.metadataFieldsPath).pipe( - tap((href: string) => this.requestService.removeByHrefSubstring(href)) - ); - } - - private delete(path: string, id: number): Observable { - const requestId = this.requestService.generateRequestId(); - const endpoint$ = this.halService.getEndpoint(path).pipe( - isNotEmptyOperator(), - map((endpoint: string) => `${endpoint}/${id}`), - distinctUntilChanged() - ); - - const request$ = endpoint$.pipe( - take(1), - map((endpoint: string) => new DeleteRequest(requestId, endpoint)) - ); - - // Execute the delete request - request$.pipe( - configureRequest(this.requestService) - ).subscribe(); - - return this.requestService.getByUUID(requestId).pipe( - getResponseFromEntry() - ); + return this.metadataFieldService.clearRequests(); } private showNotifications(success: boolean, edited: boolean, isField: boolean, options: any) { diff --git a/src/app/shared/collection-dropdown/collection-dropdown.component.html b/src/app/shared/collection-dropdown/collection-dropdown.component.html new file mode 100644 index 0000000000..36269294c1 --- /dev/null +++ b/src/app/shared/collection-dropdown/collection-dropdown.component.html @@ -0,0 +1,43 @@ +
+ +
+ +
+
+ + + +
+
\ No newline at end of file diff --git a/src/app/shared/collection-dropdown/collection-dropdown.component.scss b/src/app/shared/collection-dropdown/collection-dropdown.component.scss new file mode 100644 index 0000000000..deecc39510 --- /dev/null +++ b/src/app/shared/collection-dropdown/collection-dropdown.component.scss @@ -0,0 +1,15 @@ +.scrollable-menu { + height: auto; + max-height: $dropdown-menu-max-height; + overflow-x: hidden; +} + +.collection-item { + border-bottom: $dropdown-border-width solid $dropdown-border-color; +} + +#collectionControlsDropdownMenu { + outline: 0; + left: 0 !important; + box-shadow: $btn-focus-box-shadow; +} diff --git a/src/app/shared/collection-dropdown/collection-dropdown.component.spec.ts b/src/app/shared/collection-dropdown/collection-dropdown.component.spec.ts new file mode 100644 index 0000000000..8530be665e --- /dev/null +++ b/src/app/shared/collection-dropdown/collection-dropdown.component.spec.ts @@ -0,0 +1,241 @@ +import { async, ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing'; + +import { CollectionDropdownComponent } from './collection-dropdown.component'; +import { FollowLinkConfig } from '../utils/follow-link-config.model'; +import { Observable, of } from 'rxjs'; +import { RemoteData } from 'src/app/core/data/remote-data'; +import { PaginatedList } from 'src/app/core/data/paginated-list'; +import { cold, getTestScheduler, hot } from 'jasmine-marbles'; +import { createSuccessfulRemoteDataObject } from '../remote-data.utils'; +import { PageInfo } from 'src/app/core/shared/page-info.model'; +import { Collection } from '../../core/shared/collection.model'; +import { NO_ERRORS_SCHEMA, ChangeDetectorRef, ElementRef } from '@angular/core'; +import { CollectionDataService } from 'src/app/core/data/collection-data.service'; +import { FindListOptions } from 'src/app/core/data/request.models'; +import { TranslateModule, TranslateLoader } from '@ngx-translate/core'; +import { TranslateLoaderMock } from '../mocks/translate-loader.mock'; +import { TestScheduler } from 'rxjs/testing'; +import { By } from '@angular/platform-browser'; +import { Community } from 'src/app/core/shared/community.model'; + +const community: Community = Object.assign(new Community(), { + id: 'ce64f48e-2c9b-411a-ac36-ee429c0e6a88', + uuid: 'ce64f48e-2c9b-411a-ac36-ee429c0e6a88', + name: 'Community 1' +}); + +const collections: Collection[] = [ + Object.assign(new Collection(), { + id: 'ce64f48e-2c9b-411a-ac36-ee429c0e6a88', + name: 'Collection 1', + metadata: [ + { + key: 'dc.title', + language: 'en_US', + value: 'Community 1-Collection 1' + }], + parentCommunity: of( + new RemoteData(false, false, true, undefined, community, 200) + ) + }), + Object.assign(new Collection(), { + id: '59ee713b-ee53-4220-8c3f-9860dc84fe33', + name: 'Collection 2', + metadata: [ + { + key: 'dc.title', + language: 'en_US', + value: 'Community 1-Collection 2' + }], + parentCommunity: of( + new RemoteData(false, false, true, undefined, community, 200) + ) + }), + Object.assign(new Collection(), { + id: 'e9dbf393-7127-415f-8919-55be34a6e9ed', + name: 'Collection 3', + metadata: [ + { + key: 'dc.title', + language: 'en_US', + value: 'Community 1-Collection 3' + }], + parentCommunity: of( + new RemoteData(false, false, true, undefined, community, 200) + ) + }), + Object.assign(new Collection(), { + id: '59da2ff0-9bf4-45bf-88be-e35abd33f304', + name: 'Collection 4', + metadata: [ + { + key: 'dc.title', + language: 'en_US', + value: 'Community 1-Collection 4' + }], + parentCommunity: of( + new RemoteData(false, false, true, undefined, community, 200) + ) + }), + Object.assign(new Collection(), { + id: 'a5159760-f362-4659-9e81-e3253ad91ede', + name: 'Collection 5', + metadata: [ + { + key: 'dc.title', + language: 'en_US', + value: 'Community 1-Collection 5' + }], + parentCommunity: of( + new RemoteData(false, false, true, undefined, community, 200) + ) + }) +]; + +const listElementMock = { + communities: [ + { + id: 'ce64f48e-2c9b-411a-ac36-ee429c0e6a88', + name: 'Community 1' + } + ], + collection: { + id: 'e9dbf393-7127-415f-8919-55be34a6e9ed', + uuid: 'e9dbf393-7127-415f-8919-55be34a6e9ed', + name: 'Collection 3' + } + }; + +// tslint:disable-next-line: max-classes-per-file +class CollectionDataServiceMock { + getAuthorizedCollection(query: string, options: FindListOptions = {}, ...linksToFollow: Array>): Observable>> { + return of( + createSuccessfulRemoteDataObject( + new PaginatedList(new PageInfo(), collections) + ) + ); + } +} + +describe('CollectionDropdownComponent', () => { + let component: CollectionDropdownComponent; + let fixture: ComponentFixture; + let scheduler: TestScheduler; + const searchedCollection = 'TEXT'; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: TranslateLoaderMock + } + }) + ], + declarations: [ CollectionDropdownComponent ], + providers: [ + {provide: CollectionDataService, useClass: CollectionDataServiceMock}, + {provide: ChangeDetectorRef, useValue: {}}, + {provide: ElementRef, userValue: {}} + ], + schemas: [NO_ERRORS_SCHEMA] + }) + .compileComponents(); + })); + + beforeEach(() => { + scheduler = getTestScheduler(); + fixture = TestBed.createComponent(CollectionDropdownComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should populate collections list with five items', () => { + const elements = fixture.debugElement.queryAll(By.css('.collection-item')); + expect(elements.length).toEqual(5); + }); + + it('should trigger onSelect method when select a new collection from list', fakeAsync(() => { + spyOn(component, 'onSelect'); + const collectionItem = fixture.debugElement.query(By.css('.collection-item:nth-child(2)')); + collectionItem.triggerEventHandler('click', null); + fixture.detectChanges(); + tick(); + fixture.whenStable().then(() => { + expect(component.onSelect).toHaveBeenCalled(); + }); + })); + + it('should init component with collection list', fakeAsync(() => { + spyOn(component.subs, 'push').and.callThrough(); + spyOn(component, 'resetPagination').and.callThrough(); + spyOn(component, 'populateCollectionList').and.callThrough(); + component.ngOnInit(); + tick(); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(component.subs.push).toHaveBeenCalled(); + expect(component.resetPagination).toHaveBeenCalled(); + expect(component.populateCollectionList).toHaveBeenCalled(); + }); + })); + + it('should emit collectionChange event when selecting a new collection', () => { + spyOn(component.selectionChange, 'emit').and.callThrough(); + component.ngOnInit(); + component.onSelect(listElementMock as any); + fixture.detectChanges(); + + expect(component.selectionChange.emit).toHaveBeenCalledWith(listElementMock as any); + }); + + it('should reset collections list after reset of searchField', fakeAsync(() => { + spyOn(component.subs, 'push').and.callThrough(); + spyOn(component, 'reset').and.callThrough(); + spyOn(component.searchField, 'setValue').and.callThrough(); + spyOn(component, 'resetPagination').and.callThrough(); + spyOn(component, 'populateCollectionList').and.callThrough(); + component.reset(); + const input = fixture.debugElement.query(By.css('input.form-control')); + const el = input.nativeElement; + el.value = searchedCollection; + el.dispatchEvent(new Event('input')); + fixture.detectChanges(); + tick(500); + + fixture.whenStable().then(() => { + expect(component.reset).toHaveBeenCalled(); + expect(component.searchField.setValue).toHaveBeenCalledWith(''); + expect(component.resetPagination).toHaveBeenCalled(); + expect(component.currentQuery).toEqual(''); + expect(component.populateCollectionList).toHaveBeenCalledWith(component.currentQuery, component.currentPage); + expect(component.searchListCollection).toEqual(collections as any); + expect(component.subs.push).toHaveBeenCalled(); + }); + })); + + it('should reset searchField when dropdown menu has been closed', () => { + spyOn(component.searchField, 'setValue').and.callThrough(); + component.reset(); + + expect(component.searchField.setValue).toHaveBeenCalled(); + }); + + it('should change loader status', () => { + spyOn(component.isLoadingList, 'next').and.callThrough(); + component.hideShowLoader(true); + + expect(component.isLoadingList.next).toHaveBeenCalledWith(true); + }); + + it('reset pagination fields', () => { + component.resetPagination(); + + expect(component.currentPage).toEqual(1); + expect(component.currentQuery).toEqual(''); + expect(component.hasNextPage).toEqual(true); + expect(component.searchListCollection).toEqual([]); + }); +}); diff --git a/src/app/shared/collection-dropdown/collection-dropdown.component.ts b/src/app/shared/collection-dropdown/collection-dropdown.component.ts new file mode 100644 index 0000000000..05105d74a7 --- /dev/null +++ b/src/app/shared/collection-dropdown/collection-dropdown.component.ts @@ -0,0 +1,236 @@ +import { Component, OnInit, HostListener, ChangeDetectorRef, OnDestroy, Output, EventEmitter, ElementRef } from '@angular/core'; +import { FormControl } from '@angular/forms'; +import { Observable, Subscription, BehaviorSubject } from 'rxjs'; +import { hasValue } from '../empty.util'; +import { map, mergeMap, startWith, debounceTime, distinctUntilChanged, switchMap, reduce } from 'rxjs/operators'; +import { RemoteData } from 'src/app/core/data/remote-data'; +import { FindListOptions } from 'src/app/core/data/request.models'; +import { PaginatedList } from 'src/app/core/data/paginated-list'; +import { Community } from 'src/app/core/shared/community.model'; +import { CollectionDataService } from 'src/app/core/data/collection-data.service'; +import { Collection } from '../../core/shared/collection.model'; +import { followLink } from '../utils/follow-link-config.model'; +import { getFirstSucceededRemoteDataPayload, getSucceededRemoteWithNotEmptyData } from '../../core/shared/operators'; + +/** + * An interface to represent a collection entry + */ +interface CollectionListEntryItem { + id: string; + uuid: string; + name: string; +} + +/** + * An interface to represent an entry in the collection list + */ +interface CollectionListEntry { + communities: CollectionListEntryItem[], + collection: CollectionListEntryItem +} + +@Component({ + selector: 'ds-collection-dropdown', + templateUrl: './collection-dropdown.component.html', + styleUrls: ['./collection-dropdown.component.scss'] +}) +export class CollectionDropdownComponent implements OnInit, OnDestroy { + + /** + * The search form control + * @type {FormControl} + */ + public searchField: FormControl = new FormControl(); + + /** + * The collection list obtained from a search + * @type {Observable} + */ + public searchListCollection$: Observable; + + /** + * A boolean representing if dropdown list is scrollable to the bottom + * @type {boolean} + */ + private scrollableBottom = false; + + /** + * A boolean representing if dropdown list is scrollable to the top + * @type {boolean} + */ + private scrollableTop = false; + + /** + * Array to track all subscriptions and unsubscribe them onDestroy + * @type {Array} + */ + public subs: Subscription[] = []; + + /** + * The list of collection to render + */ + searchListCollection: CollectionListEntry[] = []; + + @Output() selectionChange = new EventEmitter(); + /** + * A boolean representing if the loader is visible or not + */ + isLoadingList: BehaviorSubject = new BehaviorSubject(false); + + /** + * A numeric representig current page + */ + currentPage: number; + + /** + * A boolean representing if exist another page to render + */ + hasNextPage: boolean; + + /** + * Current seach query used to filter collection list + */ + currentQuery: string; + + constructor( + private changeDetectorRef: ChangeDetectorRef, + private collectionDataService: CollectionDataService, + private el: ElementRef + ) { } + + /** + * Method called on mousewheel event, it prevent the page scroll + * when arriving at the top/bottom of dropdown menu + * + * @param event + * mousewheel event + */ + @HostListener('mousewheel', ['$event']) onMousewheel(event) { + if (event.wheelDelta > 0 && this.scrollableTop) { + event.preventDefault(); + } + if (event.wheelDelta < 0 && this.scrollableBottom) { + event.preventDefault(); + } + } + + /** + * Initialize collection list + */ + ngOnInit() { + this.subs.push(this.searchField.valueChanges.pipe( + debounceTime(500), + distinctUntilChanged(), + startWith('') + ).subscribe( + (next) => { + if (hasValue(next) && next !== this.currentQuery) { + this.resetPagination(); + this.currentQuery = next; + this.populateCollectionList(this.currentQuery, this.currentPage); + } + } + )); + // Workaround for prevent the scroll of main page when this component is placed in a dialog + setTimeout(() => this.el.nativeElement.querySelector('input').focus(), 0); + } + + /** + * Check if dropdown scrollbar is at the top or bottom of the dropdown list + * + * @param event + */ + onScroll(event) { + this.scrollableBottom = (event.target.scrollTop + event.target.clientHeight === event.target.scrollHeight); + this.scrollableTop = (event.target.scrollTop === 0); + } + + /** + * Method used from infitity scroll for retrive more data on scroll down + */ + onScrollDown() { + if ( this.hasNextPage ) { + this.populateCollectionList(this.currentQuery, ++this.currentPage); + } + } + + /** + * Emit a [selectionChange] event when a new collection is selected from list + * + * @param event + * the selected [CollectionListEntry] + */ + onSelect(event: CollectionListEntry) { + this.selectionChange.emit(event); + } + + /** + * Method called for populate the collection list + * @param query text for filter the collection list + * @param page page number + */ + populateCollectionList(query: string, page: number) { + this.isLoadingList.next(true); + // Set the pagination info + const findOptions: FindListOptions = { + elementsPerPage: 10, + currentPage: page + }; + this.searchListCollection$ = this.collectionDataService + .getAuthorizedCollection(query, findOptions, followLink('parentCommunity')) + .pipe( + getSucceededRemoteWithNotEmptyData(), + switchMap((collections: RemoteData>) => { + if ( (this.searchListCollection.length + findOptions.elementsPerPage) >= collections.payload.totalElements ) { + this.hasNextPage = false; + } + return collections.payload.page; + }), + mergeMap((collection: Collection) => collection.parentCommunity.pipe( + getFirstSucceededRemoteDataPayload(), + map((community: Community) => ({ + communities: [{ id: community.id, name: community.name }], + collection: { id: collection.id, uuid: collection.id, name: collection.name } + }) + ))), + reduce((acc: any, value: any) => [...acc, ...value], []), + startWith([]) + ); + this.subs.push(this.searchListCollection$.subscribe( + (next) => { this.searchListCollection.push(...next); }, undefined, + () => { this.hideShowLoader(false); this.changeDetectorRef.detectChanges(); } + )); + } + + /** + * Unsubscribe from all subscriptions + */ + ngOnDestroy(): void { + this.subs.filter((sub) => hasValue(sub)).forEach((sub) => sub.unsubscribe()); + } + + /** + * Reset search form control + */ + reset() { + this.searchField.setValue(''); + } + + /** + * Reset pagination values + */ + resetPagination() { + this.currentPage = 1; + this.currentQuery = ''; + this.hasNextPage = true; + this.searchListCollection = []; + } + + /** + * Hide/Show the collection list loader + * @param hideShow true for show, false otherwise + */ + hideShowLoader(hideShow: boolean) { + this.isLoadingList.next(hideShow); + } +} diff --git a/src/app/shared/comcol-forms/comcol-form/comcol-form.component.spec.ts b/src/app/shared/comcol-forms/comcol-form/comcol-form.component.spec.ts index a1bac46f87..3fcdc280d0 100644 --- a/src/app/shared/comcol-forms/comcol-form/comcol-form.component.spec.ts +++ b/src/app/shared/comcol-forms/comcol-form/comcol-form.component.spec.ts @@ -22,6 +22,7 @@ import { NotificationsService } from '../../notifications/notifications.service' import { NotificationsServiceStub } from '../../testing/notifications-service.stub'; import { VarDirective } from '../../utils/var.directive'; import { ComColFormComponent } from './comcol-form.component'; +import { Operation } from 'fast-json-patch'; describe('ComColFormComponent', () => { let comp: ComColFormComponent; @@ -40,11 +41,8 @@ describe('ComColFormComponent', () => { } }; const dcTitle = 'dc.title'; - const dcRandom = 'dc.random'; const dcAbstract = 'dc.description.abstract'; - const titleMD = { [dcTitle]: [{ value: 'Community Title', language: null }] }; - const randomMD = { [dcRandom]: [{ value: 'Random metadata excluded from form', language: null }] }; const abstractMD = { [dcAbstract]: [{ value: 'Community description', language: null }] }; const newTitleMD = { [dcTitle]: [{ value: 'New Community Title', language: null }] }; const formModel = [ @@ -112,33 +110,47 @@ describe('ComColFormComponent', () => { }); it('should emit the new version of the community', () => { - comp.dso = Object.assign( - new Community(), - { - metadata: { - ...titleMD, - ...randomMD - } - } - ); + comp.dso = new Community(); comp.onSubmit(); + const operations: Operation[] = [ + { + op: 'replace', + path: '/metadata/dc.title', + value: { + value: 'New Community Title', + language: null, + }, + }, + { + op: 'replace', + path: '/metadata/dc.description.abstract', + value: { + value: 'Community description', + language: null, + }, + }, + ]; + expect(comp.submitForm.emit).toHaveBeenCalledWith( { - dso: Object.assign( - {}, - new Community(), - { + dso: Object.assign({}, comp.dso, { metadata: { - ...newTitleMD, - ...randomMD, - ...abstractMD + 'dc.title': [{ + value: 'New Community Title', + language: null, + }], + 'dc.description.abstract': [{ + value: 'Community description', + language: null, + }], }, - type: Community.type - }, + type: Community.type, + } ), uploader: undefined, - deleteLogo: false + deleteLogo: false, + operations: operations, } ); }) @@ -164,11 +176,6 @@ describe('ComColFormComponent', () => { it('should emit finish', () => { expect(comp.finish.emit).toHaveBeenCalled(); }); - - it('should remove the object\'s cache', () => { - expect(requestServiceStub.removeByHrefSubstring).toHaveBeenCalled(); - expect(objectCacheStub.remove).toHaveBeenCalled(); - }); }); describe('onUploadError', () => { @@ -239,6 +246,11 @@ describe('ComColFormComponent', () => { it('should display a success notification', () => { expect(notificationsService.success).toHaveBeenCalled(); }); + + it('should remove the object\'s cache', () => { + expect(requestServiceStub.removeByHrefSubstring).toHaveBeenCalled(); + expect(objectCacheStub.remove).toHaveBeenCalled(); + }); }); describe('when dsoService.deleteLogo returns an error response', () => { diff --git a/src/app/shared/comcol-forms/comcol-form/comcol-form.component.ts b/src/app/shared/comcol-forms/comcol-form/comcol-form.component.ts index f8199d2aad..91e896ce6c 100644 --- a/src/app/shared/comcol-forms/comcol-form/comcol-form.component.ts +++ b/src/app/shared/comcol-forms/comcol-form/comcol-form.component.ts @@ -25,6 +25,7 @@ import { hasValue, isNotEmpty } from '../../empty.util'; import { NotificationsService } from '../../notifications/notifications.service'; import { UploaderOptions } from '../../uploader/uploader-options.model'; import { UploaderComponent } from '../../uploader/uploader.component'; +import { Operation } from 'fast-json-patch'; /** * A form for creating and editing Communities or Collections @@ -85,7 +86,8 @@ export class ComColFormComponent implements OnInit, OnDe @Output() submitForm: EventEmitter<{ dso: T, uploader: FileUploader, - deleteLogo: boolean + deleteLogo: boolean, + operations: Operation[], }> = new EventEmitter(); /** @@ -189,9 +191,9 @@ export class ComColFormComponent implements OnInit, OnDe const formMetadata = {} as MetadataMap; this.formModel.forEach((fieldModel: DynamicInputModel) => { const value: MetadataValue = { - value: fieldModel.value as string, - language: null - } as any; + value: fieldModel.value as string, + language: null + } as any; if (formMetadata.hasOwnProperty(fieldModel.name)) { formMetadata[fieldModel.name].push(value); } else { @@ -206,10 +208,26 @@ export class ComColFormComponent implements OnInit, OnDe }, type: Community.type }); + + const operations: Operation[] = []; + this.formModel.forEach((fieldModel: DynamicInputModel) => { + if (fieldModel.value !== this.dso.firstMetadataValue(fieldModel.name)) { + operations.push({ + op: 'replace', + path: `/metadata/${fieldModel.name}`, + value: { + value: fieldModel.value, + language: null, + }, + }); + } + }); + this.submitForm.emit({ dso: updatedDSO, uploader: hasValue(this.uploaderComponent) ? this.uploaderComponent.uploader : undefined, - deleteLogo: this.markLogoForDeletion + deleteLogo: this.markLogoForDeletion, + operations: operations, }); } @@ -257,7 +275,9 @@ export class ComColFormComponent implements OnInit, OnDe * The request was successful, display a success notification */ public onCompleteItem() { - this.refreshCache(); + if (hasValue(this.dso.id)) { + this.refreshCache(); + } this.notificationsService.success(null, this.translate.get(this.type.value + '.edit.logo.notifications.add.success')); this.finish.emit(); } diff --git a/src/app/shared/comcol-forms/create-comcol-page/create-comcol-page.component.ts b/src/app/shared/comcol-forms/create-comcol-page/create-comcol-page.component.ts index a8d6499cbd..4a7cd9afb1 100644 --- a/src/app/shared/comcol-forms/create-comcol-page/create-comcol-page.component.ts +++ b/src/app/shared/comcol-forms/create-comcol-page/create-comcol-page.component.ts @@ -77,7 +77,8 @@ export class CreateComColPageComponent implements const uploader = event.uploader; this.parentUUID$.pipe(take(1)).subscribe((uuid: string) => { - this.dsoDataService.create(dso, new RequestParam('parent', uuid)) + const params = uuid ? [new RequestParam('parent', uuid)] : []; + this.dsoDataService.create(dso, ...params) .pipe(getSucceededRemoteData()) .subscribe((dsoRD: RemoteData) => { if (isNotUndefined(dsoRD)) { diff --git a/src/app/shared/comcol-forms/edit-comcol-page/comcol-metadata/comcol-metadata.component.spec.ts b/src/app/shared/comcol-forms/edit-comcol-page/comcol-metadata/comcol-metadata.component.spec.ts index 414d64cbff..b50a1d3ac4 100644 --- a/src/app/shared/comcol-forms/edit-comcol-page/comcol-metadata/comcol-metadata.component.spec.ts +++ b/src/app/shared/comcol-forms/edit-comcol-page/comcol-metadata/comcol-metadata.component.spec.ts @@ -13,13 +13,13 @@ import { DSpaceObject } from '../../../../core/shared/dspace-object.model'; import { NotificationsService } from '../../../notifications/notifications.service'; import { SharedModule } from '../../../shared.module'; import { NotificationsServiceStub } from '../../../testing/notifications-service.stub'; -import { createFailedRemoteDataObject$, createSuccessfulRemoteDataObject$ } from '../../../remote-data.utils'; +import { createSuccessfulRemoteDataObject$ } from '../../../remote-data.utils'; import { ComcolMetadataComponent } from './comcol-metadata.component'; describe('ComColMetadataComponent', () => { let comp: ComcolMetadataComponent; let fixture: ComponentFixture>; - let dsoDataService: CommunityDataService; + let dsoDataService; let router: Router; let community; @@ -49,6 +49,7 @@ describe('ComColMetadataComponent', () => { communityDataServiceStub = { update: (com, uuid?) => createSuccessfulRemoteDataObject$(newCommunity), + patch: () => null, getLogoEndpoint: () => observableOf(logoEndpoint) }; @@ -95,37 +96,60 @@ describe('ComColMetadataComponent', () => { describe('with an empty queue in the uploader', () => { beforeEach(() => { data = { - dso: Object.assign(new Community(), { - metadata: [{ - key: 'dc.title', - value: 'test' - }] - }), + operations: [ + { + op: 'replace', + path: '/metadata/dc.title', + value: { + value: 'test', + language: null, + }, + }, + ], + dso: new Community(), uploader: { options: { url: '' }, queue: [], /* tslint:disable:no-empty */ - uploadAll: () => {} + uploadAll: () => { + } /* tslint:enable:no-empty */ - } - } + }, + deleteLogo: false, + }; + spyOn(router, 'navigate'); }); - it('should navigate when successful', () => { - spyOn(router, 'navigate'); - comp.onSubmit(data); - fixture.detectChanges(); - expect(router.navigate).toHaveBeenCalled(); + describe('when successful', () => { + + beforeEach(() => { + spyOn(dsoDataService, 'patch').and.returnValue(observableOf({ + isSuccessful: true, + })); + }); + + it('should navigate', () => { + comp.onSubmit(data); + fixture.detectChanges(); + expect(router.navigate).toHaveBeenCalled(); + }); }); - it('should not navigate on failure', () => { - spyOn(router, 'navigate'); - spyOn(dsoDataService, 'update').and.returnValue(createFailedRemoteDataObject$(newCommunity)); - comp.onSubmit(data); - fixture.detectChanges(); - expect(router.navigate).not.toHaveBeenCalled(); + describe('on failure', () => { + + beforeEach(() => { + spyOn(dsoDataService, 'patch').and.returnValue(observableOf({ + isSuccessful: false, + })); + }); + + it('should not navigate', () => { + comp.onSubmit(data); + fixture.detectChanges(); + expect(router.navigate).not.toHaveBeenCalled(); + }); }); }); diff --git a/src/app/shared/comcol-forms/edit-comcol-page/comcol-metadata/comcol-metadata.component.ts b/src/app/shared/comcol-forms/edit-comcol-page/comcol-metadata/comcol-metadata.component.ts index 1031fead10..02c28d989c 100644 --- a/src/app/shared/comcol-forms/edit-comcol-page/comcol-metadata/comcol-metadata.component.ts +++ b/src/app/shared/comcol-forms/edit-comcol-page/comcol-metadata/comcol-metadata.component.ts @@ -5,8 +5,7 @@ import { RemoteData } from '../../../../core/data/remote-data'; import { ActivatedRoute, Router } from '@angular/router'; import { first, map, take } from 'rxjs/operators'; import { getSucceededRemoteData } from '../../../../core/shared/operators'; -import { hasValue, isNotUndefined } from '../../../empty.util'; -import { DataService } from '../../../../core/data/data.service'; +import { hasValue, isEmpty } from '../../../empty.util'; import { ResourceType } from '../../../../core/shared/resource-type'; import { ComColDataService } from '../../../../core/data/comcol-data.service'; import { NotificationsService } from '../../../notifications/notifications.service'; @@ -49,26 +48,33 @@ export class ComcolMetadataComponent implements On * @param event The event returned by the community/collection form. Contains the new dso and logo uploader */ onSubmit(event) { - const dso = event.dso; + const uploader = event.uploader; const deleteLogo = event.deleteLogo; - this.dsoDataService.update(dso) - .pipe(getSucceededRemoteData()) - .subscribe((dsoRD: RemoteData) => { - if (isNotUndefined(dsoRD)) { - const newUUID = dsoRD.payload.uuid; - if (hasValue(uploader) && uploader.queue.length > 0) { - this.dsoDataService.getLogoEndpoint(newUUID).pipe(take(1)).subscribe((href: string) => { - uploader.options.url = href; - uploader.uploadAll(); - }); - } else if (!deleteLogo) { - this.router.navigate([this.frontendURL + newUUID]); - } - this.notificationsService.success(null, this.translate.get(this.type.value + '.edit.notifications.success')); - } + const newLogo = hasValue(uploader) && uploader.queue.length > 0; + if (newLogo) { + this.dsoDataService.getLogoEndpoint(event.dso.uuid).pipe(take(1)).subscribe((href: string) => { + uploader.options.url = href; + uploader.uploadAll(); }); + } + + if (!isEmpty(event.operations)) { + this.dsoDataService.patch(event.dso, event.operations) + .subscribe(async (response) => { + if (response.isSuccessful) { + if (!newLogo && !deleteLogo) { + await this.router.navigate([this.frontendURL + event.dso.uuid]); + } + this.notificationsService.success(null, this.translate.get(`${this.type.value}.edit.notifications.success`)); + } else if (response.statusCode === 403) { + this.notificationsService.error(null, this.translate.get(`${this.type.value}.edit.notifications.unauthorized`)); + } else { + this.notificationsService.error(null, this.translate.get(`${this.type.value}.edit.notifications.error`)); + } + }); + } } /** diff --git a/src/app/shared/dso-selector/modal-wrappers/create-collection-parent-selector/create-collection-parent-selector.component.spec.ts b/src/app/shared/dso-selector/modal-wrappers/create-collection-parent-selector/create-collection-parent-selector.component.spec.ts index 480f6ff709..df62534593 100644 --- a/src/app/shared/dso-selector/modal-wrappers/create-collection-parent-selector/create-collection-parent-selector.component.spec.ts +++ b/src/app/shared/dso-selector/modal-wrappers/create-collection-parent-selector/create-collection-parent-selector.component.spec.ts @@ -39,7 +39,15 @@ describe('CreateCollectionParentSelectorComponent', () => { { provide: NgbActiveModal, useValue: modalStub }, { provide: ActivatedRoute, - useValue: { root: { firstChild: { firstChild: { data: observableOf({ community: communityRD }) } } } } + useValue: { + root: { + snapshot: { + data: { + dso: communityRD, + }, + }, + } + }, }, { provide: Router, useValue: router diff --git a/src/app/shared/dso-selector/modal-wrappers/create-community-parent-selector/create-community-parent-selector.component.html b/src/app/shared/dso-selector/modal-wrappers/create-community-parent-selector/create-community-parent-selector.component.html index e6a0db3b62..d0ba9c7108 100644 --- a/src/app/shared/dso-selector/modal-wrappers/create-community-parent-selector/create-community-parent-selector.component.html +++ b/src/app/shared/dso-selector/modal-wrappers/create-community-parent-selector/create-community-parent-selector.component.html @@ -14,6 +14,6 @@
{{'dso-selector.create.community.sub-level' | translate}}
- + - \ No newline at end of file + diff --git a/src/app/shared/dso-selector/modal-wrappers/create-community-parent-selector/create-community-parent-selector.component.spec.ts b/src/app/shared/dso-selector/modal-wrappers/create-community-parent-selector/create-community-parent-selector.component.spec.ts index b723d3fe98..9c6185199c 100644 --- a/src/app/shared/dso-selector/modal-wrappers/create-community-parent-selector/create-community-parent-selector.component.spec.ts +++ b/src/app/shared/dso-selector/modal-wrappers/create-community-parent-selector/create-community-parent-selector.component.spec.ts @@ -33,7 +33,15 @@ describe('CreateCommunityParentSelectorComponent', () => { { provide: NgbActiveModal, useValue: modalStub }, { provide: ActivatedRoute, - useValue: { root: { firstChild: { firstChild: { data: observableOf({ community: communityRD }) } } } } + useValue: { + root: { + snapshot: { + data: { + dso: communityRD, + }, + }, + } + }, }, { provide: Router, useValue: router diff --git a/src/app/shared/dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component.html b/src/app/shared/dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component.html new file mode 100644 index 0000000000..ef8865ad87 --- /dev/null +++ b/src/app/shared/dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component.html @@ -0,0 +1,11 @@ +
+ + +
diff --git a/src/app/shared/dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component.spec.ts b/src/app/shared/dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component.spec.ts index 854349a47c..e8cd35fb50 100644 --- a/src/app/shared/dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component.spec.ts +++ b/src/app/shared/dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component.spec.ts @@ -32,7 +32,15 @@ describe('CreateItemParentSelectorComponent', () => { { provide: NgbActiveModal, useValue: modalStub }, { provide: ActivatedRoute, - useValue: { root: { firstChild: { firstChild: { data: observableOf({ collection: collectionRD }) } } } } + useValue: { + root: { + snapshot: { + data: { + dso: collectionRD, + }, + }, + } + }, }, { provide: Router, useValue: router diff --git a/src/app/shared/dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component.ts b/src/app/shared/dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component.ts index 02a0bd79cd..45d15ae306 100644 --- a/src/app/shared/dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component.ts +++ b/src/app/shared/dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component.ts @@ -13,7 +13,8 @@ import { DSOSelectorModalWrapperComponent, SelectorActionType } from '../dso-sel @Component({ selector: 'ds-create-item-parent-selector', // styleUrls: ['./create-item-parent-selector.component.scss'], - templateUrl: '../dso-selector-modal-wrapper.component.html', + // templateUrl: '../dso-selector-modal-wrapper.component.html', + templateUrl: './create-item-parent-selector.component.html' }) export class CreateItemParentSelectorComponent extends DSOSelectorModalWrapperComponent implements OnInit { objectType = DSpaceObjectType.ITEM; diff --git a/src/app/shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component.html b/src/app/shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component.html index 1181e097eb..4800bb8733 100644 --- a/src/app/shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component.html +++ b/src/app/shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component.html @@ -5,6 +5,6 @@ diff --git a/src/app/shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component.spec.ts b/src/app/shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component.spec.ts index 7b5c020f1b..f52ce3fc8f 100644 --- a/src/app/shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component.spec.ts +++ b/src/app/shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component.spec.ts @@ -41,8 +41,16 @@ describe('DSOSelectorModalWrapperComponent', () => { { provide: NgbActiveModal, useValue: modalStub }, { provide: ActivatedRoute, - useValue: { root: { firstChild: { firstChild: { data: observableOf({ item: itemRD }) } } } } - } + useValue: { + root: { + snapshot: { + data: { + dso: itemRD, + }, + }, + } + } + }, ], schemas: [NO_ERRORS_SCHEMA] }).compileComponents(); @@ -63,11 +71,7 @@ describe('DSOSelectorModalWrapperComponent', () => { }); it('should initially set the DSO to the activated route\'s item/collection/community', () => { - component.dsoRD$ - .pipe(first()) - .subscribe((a) => { - expect(a).toEqual(itemRD); - }) + expect(component.dsoRD).toEqual(itemRD); }); describe('selectObject', () => { diff --git a/src/app/shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component.ts b/src/app/shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component.ts index 881476cac6..c13bd2b69d 100644 --- a/src/app/shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component.ts +++ b/src/app/shared/dso-selector/modal-wrappers/dso-selector-modal-wrapper.component.ts @@ -1,11 +1,12 @@ import { Injectable, Input, OnInit } from '@angular/core'; -import { ActivatedRoute } from '@angular/router'; +import { ActivatedRoute, ActivatedRouteSnapshot } from '@angular/router'; import { Observable } from 'rxjs'; import { DSpaceObject } from '../../../core/shared/dspace-object.model'; import { RemoteData } from '../../../core/data/remote-data'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { map } from 'rxjs/operators'; import { DSpaceObjectType } from '../../../core/shared/dspace-object-type.model'; +import { hasValue, isNotEmpty } from '../../empty.util'; export enum SelectorActionType { CREATE = 'create', @@ -21,7 +22,7 @@ export abstract class DSOSelectorModalWrapperComponent implements OnInit { /** * The current page's DSO */ - @Input() dsoRD$: Observable>; + @Input() dsoRD: RemoteData; /** * The type of the DSO that's being edited or created @@ -45,10 +46,30 @@ export abstract class DSOSelectorModalWrapperComponent implements OnInit { * Get de current page's DSO based on the selectorType */ ngOnInit(): void { - const typeString = this.selectorType.toString().toLowerCase(); - this.dsoRD$ = this.route.root.firstChild.firstChild.data.pipe(map((data) => data[typeString])); + const matchingRoute = this.findRouteData( + (route: ActivatedRouteSnapshot) => hasValue(route.data.dso), + this.route.root.snapshot + ); + if (hasValue(matchingRoute)) { + this.dsoRD = matchingRoute.data.dso; + } } + findRouteData(predicate: (value: ActivatedRouteSnapshot, index?: number, obj?: ActivatedRouteSnapshot[]) => unknown, ...routes: ActivatedRouteSnapshot[]) { + const result = routes.find(predicate); + if (hasValue(result)) { + return result; + } else { + const nextLevelRoutes = routes + .map((route: ActivatedRouteSnapshot) => route.children) + .reduce((combined: ActivatedRouteSnapshot[], current: ActivatedRouteSnapshot[]) => [...combined, ...current]); + if (isNotEmpty(nextLevelRoutes)) { + return this.findRouteData(predicate, ...nextLevelRoutes) + } else { + return undefined; + } + } + } /** * Method called when an object has been selected * @param dso The selected DSpaceObject diff --git a/src/app/shared/dso-selector/modal-wrappers/edit-collection-selector/edit-collection-selector.component.spec.ts b/src/app/shared/dso-selector/modal-wrappers/edit-collection-selector/edit-collection-selector.component.spec.ts index a17d9e4c21..21ff5e846d 100644 --- a/src/app/shared/dso-selector/modal-wrappers/edit-collection-selector/edit-collection-selector.component.spec.ts +++ b/src/app/shared/dso-selector/modal-wrappers/edit-collection-selector/edit-collection-selector.component.spec.ts @@ -33,7 +33,15 @@ describe('EditCollectionSelectorComponent', () => { { provide: NgbActiveModal, useValue: modalStub }, { provide: ActivatedRoute, - useValue: { root: { firstChild: { firstChild: { data: observableOf({ collection: collectionRD }) } } } } + useValue: { + root: { + snapshot: { + data: { + dso: collectionRD, + }, + }, + } + }, }, { provide: Router, useValue: router diff --git a/src/app/shared/dso-selector/modal-wrappers/edit-community-selector/edit-community-selector.component.spec.ts b/src/app/shared/dso-selector/modal-wrappers/edit-community-selector/edit-community-selector.component.spec.ts index c48d29baa9..b37fa23024 100644 --- a/src/app/shared/dso-selector/modal-wrappers/edit-community-selector/edit-community-selector.component.spec.ts +++ b/src/app/shared/dso-selector/modal-wrappers/edit-community-selector/edit-community-selector.component.spec.ts @@ -33,7 +33,15 @@ describe('EditCommunitySelectorComponent', () => { { provide: NgbActiveModal, useValue: modalStub }, { provide: ActivatedRoute, - useValue: { root: { firstChild: { firstChild: { data: observableOf({ community: communityRD }) } } } } + useValue: { + root: { + snapshot: { + data: { + dso: communityRD, + }, + }, + } + }, }, { provide: Router, useValue: router diff --git a/src/app/shared/dso-selector/modal-wrappers/edit-item-selector/edit-item-selector.component.spec.ts b/src/app/shared/dso-selector/modal-wrappers/edit-item-selector/edit-item-selector.component.spec.ts index 582320acae..e310d6ac02 100644 --- a/src/app/shared/dso-selector/modal-wrappers/edit-item-selector/edit-item-selector.component.spec.ts +++ b/src/app/shared/dso-selector/modal-wrappers/edit-item-selector/edit-item-selector.component.spec.ts @@ -33,7 +33,15 @@ describe('EditItemSelectorComponent', () => { { provide: NgbActiveModal, useValue: modalStub }, { provide: ActivatedRoute, - useValue: { root: { firstChild: { firstChild: { data: observableOf({ item: itemRD }) } } } } + useValue: { + root: { + snapshot: { + data: { + dso: itemRD, + }, + }, + } + }, }, { provide: Router, useValue: router diff --git a/src/app/shared/mocks/request.service.mock.ts b/src/app/shared/mocks/request.service.mock.ts index da297f56ac..6a3f182868 100644 --- a/src/app/shared/mocks/request.service.mock.ts +++ b/src/app/shared/mocks/request.service.mock.ts @@ -11,7 +11,7 @@ export function getMockRequestService(requestEntry$: Observable = getByUUID: requestEntry$, uriEncodeBody: jasmine.createSpy('uriEncodeBody'), isCachedOrPending: false, - removeByHrefSubstring: jasmine.createSpy('removeByHrefSubstring'), + removeByHrefSubstring: jasmine.createSpy('removeByHrefSubstring').and.returnValue(observableOf(true)), hasByHrefObservable: observableOf(false) }); } diff --git a/src/app/shared/notifications/notifications.service.ts b/src/app/shared/notifications/notifications.service.ts index fa65d69530..ab21ab61f7 100644 --- a/src/app/shared/notifications/notifications.service.ts +++ b/src/app/shared/notifications/notifications.service.ts @@ -75,7 +75,7 @@ export class NotificationsService { this.translate.get(hrefTranslateLabel) .pipe(first()) .subscribe((hrefMsg) => { - const anchor = ` + const anchor = ` ${hrefMsg} `; const interpolateParams = Object.create({}); diff --git a/src/app/shared/pagination-drag-and-drop/abstract-paginated-drag-and-drop-list.component.spec.ts b/src/app/shared/pagination-drag-and-drop/abstract-paginated-drag-and-drop-list.component.spec.ts index 9fcfd21586..5fd7f3ec56 100644 --- a/src/app/shared/pagination-drag-and-drop/abstract-paginated-drag-and-drop-list.component.spec.ts +++ b/src/app/shared/pagination-drag-and-drop/abstract-paginated-drag-and-drop-list.component.spec.ts @@ -12,14 +12,16 @@ import { take } from 'rxjs/operators'; import { PaginationComponent } from '../pagination/pagination.component'; import { createSuccessfulRemoteDataObject } from '../remote-data.utils'; import { createPaginatedList } from '../testing/utils.test'; +import { ObjectValuesPipe } from '../utils/object-values-pipe'; class MockAbstractPaginatedDragAndDropListComponent extends AbstractPaginatedDragAndDropListComponent { constructor(protected objectUpdatesService: ObjectUpdatesService, protected elRef: ElementRef, + protected objectValuesPipe: ObjectValuesPipe, protected mockUrl: string, protected mockObjectsRD$: Observable>>) { - super(objectUpdatesService, elRef); + super(objectUpdatesService, elRef, objectValuesPipe); } initializeObjectsRD(): void { @@ -35,6 +37,7 @@ describe('AbstractPaginatedDragAndDropListComponent', () => { let component: MockAbstractPaginatedDragAndDropListComponent; let objectUpdatesService: ObjectUpdatesService; let elRef: ElementRef; + let objectValuesPipe: ObjectValuesPipe; const url = 'mock-abstract-paginated-drag-and-drop-list-component'; @@ -52,32 +55,26 @@ describe('AbstractPaginatedDragAndDropListComponent', () => { beforeEach(() => { objectUpdatesService = jasmine.createSpyObj('objectUpdatesService', { - initializeWithCustomOrder: {}, - addPageToCustomOrder: {}, - getFieldUpdatesByCustomOrder: observableOf(updates), - saveMoveFieldUpdate: {} + initialize: {}, + getFieldUpdatesExclusive: observableOf(updates) }); elRef = { nativeElement: jasmine.createSpyObj('nativeElement', { querySelector: {} }) }; + objectValuesPipe = new ObjectValuesPipe(); paginationComponent = jasmine.createSpyObj('paginationComponent', { doPageChange: {} }); objectsRD$ = new BehaviorSubject(objectsRD); - component = new MockAbstractPaginatedDragAndDropListComponent(objectUpdatesService, elRef, url, objectsRD$); + component = new MockAbstractPaginatedDragAndDropListComponent(objectUpdatesService, elRef, objectValuesPipe, url, objectsRD$); component.paginationComponent = paginationComponent; component.ngOnInit(); }); - it('should call initializeWithCustomOrder to initialize the first page and add it to initializedPages', (done) => { - expect(component.initializedPages.indexOf(0)).toBeLessThan(0); - component.updates$.pipe(take(1)).subscribe(() => { - expect(objectUpdatesService.initializeWithCustomOrder).toHaveBeenCalled(); - expect(component.initializedPages.indexOf(0)).toBeGreaterThanOrEqual(0); - done(); - }); + it('should call initialize to initialize the objects in the store', () => { + expect(objectUpdatesService.initialize).toHaveBeenCalled(); }); it('should initialize the updates correctly', (done) => { @@ -87,43 +84,6 @@ describe('AbstractPaginatedDragAndDropListComponent', () => { }); }); - describe('when a new page is loaded', () => { - const page = 5; - - beforeEach((done) => { - component.updates$.pipe(take(1)).subscribe(() => { - component.currentPage$.next(page); - objectsRD$.next(objectsRD); - done(); - }); - }); - - it('should call addPageToCustomOrder to initialize the new page and add it to initializedPages', (done) => { - component.updates$.pipe(take(1)).subscribe(() => { - expect(objectUpdatesService.addPageToCustomOrder).toHaveBeenCalled(); - expect(component.initializedPages.indexOf(page - 1)).toBeGreaterThanOrEqual(0); - done(); - }); - }); - - describe('twice', () => { - beforeEach((done) => { - component.updates$.pipe(take(1)).subscribe(() => { - component.currentPage$.next(page); - objectsRD$.next(objectsRD); - done(); - }); - }); - - it('shouldn\'t call addPageToCustomOrder again, as the page has already been initialized', (done) => { - component.updates$.pipe(take(1)).subscribe(() => { - expect(objectUpdatesService.addPageToCustomOrder).toHaveBeenCalledTimes(1); - done(); - }); - }); - }); - }); - describe('switchPage', () => { const page = 3; @@ -149,30 +109,31 @@ describe('AbstractPaginatedDragAndDropListComponent', () => { beforeEach(() => { elRef.nativeElement.querySelector.and.returnValue(hoverElement); - component.initializedPages.push(hoverPage - 1); + spyOn(component.dropObject, 'emit'); component.drop(event); }); - it('should detect the page and set currentPage$ to its value', () => { - expect(component.currentPage$.value).toEqual(hoverPage); - }); - - it('should detect the page and update the pagination component with its value', () => { - expect(paginationComponent.doPageChange).toHaveBeenCalledWith(hoverPage); - }); - - it('should send out a saveMoveFieldUpdate with the correct values', () => { - expect(objectUpdatesService.saveMoveFieldUpdate).toHaveBeenCalledWith(url, event.previousIndex, 0, 0, hoverPage - 1, object1); + it('should send out a dropObject event with the expected processed paginated indexes', () => { + expect(component.dropObject.emit).toHaveBeenCalledWith(Object.assign({ + fromIndex: ((component.currentPage$.value - 1) * component.pageSize) + event.previousIndex, + toIndex: ((hoverPage - 1) * component.pageSize), + finish: jasmine.anything() + })); }); }); describe('when the user is not hovering over a new page', () => { beforeEach(() => { + spyOn(component.dropObject, 'emit'); component.drop(event); }); - it('should send out a saveMoveFieldUpdate with the correct values', () => { - expect(objectUpdatesService.saveMoveFieldUpdate).toHaveBeenCalledWith(url, event.previousIndex, event.currentIndex, 0, 0); + it('should send out a dropObject event with the expected properties', () => { + expect(component.dropObject.emit).toHaveBeenCalledWith(Object.assign({ + fromIndex: event.previousIndex, + toIndex: event.currentIndex, + finish: jasmine.anything() + })); }); }); }); diff --git a/src/app/shared/pagination-drag-and-drop/abstract-paginated-drag-and-drop-list.component.ts b/src/app/shared/pagination-drag-and-drop/abstract-paginated-drag-and-drop-list.component.ts index a34b5d5bc0..f8a4cdee61 100644 --- a/src/app/shared/pagination-drag-and-drop/abstract-paginated-drag-and-drop-list.component.ts +++ b/src/app/shared/pagination-drag-and-drop/abstract-paginated-drag-and-drop-list.component.ts @@ -1,23 +1,33 @@ -import { FieldUpdates } from '../../core/data/object-updates/object-updates.reducer'; +import { FieldUpdate, FieldUpdates } from '../../core/data/object-updates/object-updates.reducer'; import { Observable } from 'rxjs/internal/Observable'; import { RemoteData } from '../../core/data/remote-data'; import { PaginatedList } from '../../core/data/paginated-list'; import { PaginationComponentOptions } from '../pagination/pagination-component-options.model'; import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject'; import { ObjectUpdatesService } from '../../core/data/object-updates/object-updates.service'; -import { switchMap, take, tap } from 'rxjs/operators'; -import { hasValue, isEmpty, isNotEmpty } from '../empty.util'; +import { distinctUntilChanged, map, switchMap, take } from 'rxjs/operators'; +import { hasValue, isNotEmpty } from '../empty.util'; import { paginatedListToArray } from '../../core/shared/operators'; import { DSpaceObject } from '../../core/shared/dspace-object.model'; -import { CdkDragDrop } from '@angular/cdk/drag-drop'; -import { ElementRef, ViewChild } from '@angular/core'; +import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop'; +import { ElementRef, EventEmitter, OnDestroy, Output, ViewChild } from '@angular/core'; import { PaginationComponent } from '../pagination/pagination.component'; +import { ObjectValuesPipe } from '../utils/object-values-pipe'; +import { compareArraysUsing } from '../../+item-page/simple/item-types/shared/item-relationships-utils'; +import { Subscription } from 'rxjs/internal/Subscription'; + +/** + * Operator used for comparing {@link FieldUpdate}s by their field's UUID + */ +export const compareArraysUsingFieldUuids = () => + compareArraysUsing((fieldUpdate: FieldUpdate) => (hasValue(fieldUpdate) && hasValue(fieldUpdate.field)) ? fieldUpdate.field.uuid : undefined); /** * An abstract component containing general methods and logic to be able to drag and drop objects within a paginated * list. This implementation supports being able to drag and drop objects between pages. - * Dragging an object on top of a page number will automatically detect the page it's being dropped on, send an update - * to the store and add the object on top of that page. + * Dragging an object on top of a page number will automatically detect the page it's being dropped on and send a + * dropObject event to the parent component containing detailed information about the indexes the object was dropped from + * and to. * * To extend this component, it is important to make sure to: * - Initialize objectsRD$ within the initializeObjectsRD() method @@ -28,12 +38,19 @@ import { PaginationComponent } from '../pagination/pagination.component'; * * An example component extending from this abstract component: PaginatedDragAndDropBitstreamListComponent */ -export abstract class AbstractPaginatedDragAndDropListComponent { +export abstract class AbstractPaginatedDragAndDropListComponent implements OnDestroy { /** * A view on the child pagination component */ @ViewChild(PaginationComponent, {static: false}) paginationComponent: PaginationComponent; + /** + * Send an event when the user drops an object on the pagination + * The event contains details about the index the object came from and is dropped to (across the entirety of the list, + * not just within a single page) + */ + @Output() dropObject: EventEmitter = new EventEmitter(); + /** * The URL to use for accessing the object updates from this list */ @@ -49,6 +66,12 @@ export abstract class AbstractPaginatedDragAndDropListComponent; + /** + * A list of object UUIDs + * This is the order the objects will be displayed in + */ + customOrder: string[]; + /** * The amount of objects to display per page */ @@ -70,23 +93,21 @@ export abstract class AbstractPaginatedDragAndDropListComponent(1); /** - * A list of pages that have been initialized in the field-update store + * Whether or not we should display a loading animation + * This is used to display a loading page when the user drops a bitstream onto a new page. The loading animation + * should stop once the bitstream has moved to the new page and the new page's response has loaded and contains the + * dropped object on top (see this.stopLoadingWhenFirstIs below) */ - initializedPages: number[] = []; + loading$: BehaviorSubject = new BehaviorSubject(false); /** - * An object storing information about an update that should be fired whenever fireToUpdate is called + * List of subscriptions */ - toUpdate: { - fromIndex: number, - toIndex: number, - fromPage: number, - toPage: number, - field?: T - }; + subs: Subscription[] = []; protected constructor(protected objectUpdatesService: ObjectUpdatesService, - protected elRef: ElementRef) { + protected elRef: ElementRef, + protected objectValuesPipe: ObjectValuesPipe) { } /** @@ -110,28 +131,29 @@ export abstract class AbstractPaginatedDragAndDropListComponent { + this.objectUpdatesService.initialize(this.url, objects, new Date()); + }); this.updates$ = this.objectsRD$.pipe( paginatedListToArray(), - tap((objects: T[]) => { - // Pages in the field-update store are indexed starting at 0 (because they're stored in an array of pages) - const updatesPage = this.currentPage$.value - 1; - if (isEmpty(this.initializedPages)) { - // No updates have been initialized yet for this list, initialize the first page - this.objectUpdatesService.initializeWithCustomOrder(this.url, objects, new Date(), this.pageSize, updatesPage); - this.initializedPages.push(updatesPage); - } else if (this.initializedPages.indexOf(updatesPage) < 0) { - // Updates were initialized for this list, but not the page we're on. Add the current page to the field-update store for this list - this.objectUpdatesService.addPageToCustomOrder(this.url, objects, updatesPage); - this.initializedPages.push(updatesPage); - } - - // The new page is loaded into the store, check if there are any updates waiting and fire those as well - this.fireToUpdate(); + switchMap((objects: T[]) => this.objectUpdatesService.getFieldUpdatesExclusive(this.url, objects)) + ); + this.subs.push( + this.updates$.pipe( + map((fieldUpdates) => this.objectValuesPipe.transform(fieldUpdates)), + distinctUntilChanged(compareArraysUsingFieldUuids()) + ).subscribe((updateValues) => { + this.customOrder = updateValues.map((fieldUpdate) => fieldUpdate.field.uuid); + // We received new values, stop displaying a loading indicator if it's present + this.loading$.next(false); }), - switchMap((objects: T[]) => this.objectUpdatesService.getFieldUpdatesByCustomOrder(this.url, objects, this.currentPage$.value - 1)) + // Disable the pagination when objects are loading + this.loading$.subscribe((loading) => this.options.disabled = loading) ); } @@ -144,52 +166,60 @@ export abstract class AbstractPaginatedDragAndDropListComponent) { + const dragIndex = event.previousIndex; + let dropIndex = event.currentIndex; + const dragPage = this.currentPage$.value - 1; + let dropPage = this.currentPage$.value - 1; + // Check if the user is hovering over any of the pagination's pages at the time of dropping the object const droppedOnElement = this.elRef.nativeElement.querySelector('.page-item:hover'); if (hasValue(droppedOnElement) && hasValue(droppedOnElement.textContent)) { // The user is hovering over a page, fetch the page's number from the element - const page = Number(droppedOnElement.textContent); - if (hasValue(page) && !Number.isNaN(page)) { - const id = event.item.element.nativeElement.id; - this.updates$.pipe(take(1)).subscribe((updates: FieldUpdates) => { - const field = hasValue(updates[id]) ? updates[id].field : undefined; - this.toUpdate = Object.assign({ - fromIndex: event.previousIndex, - toIndex: 0, - fromPage: this.currentPage$.value - 1, - toPage: page - 1, - field - }); - // Switch to the dropped-on page and force a page update for the pagination component - this.currentPage$.next(page); - this.paginationComponent.doPageChange(page); - if (this.initializedPages.indexOf(page - 1) >= 0) { - // The page the object is being dropped to has already been loaded before, directly fire an update to the store. - // For pages that haven't been loaded before, the updates$ observable will call fireToUpdate after the new page - // has loaded - this.fireToUpdate(); - } - }); + const droppedPage = Number(droppedOnElement.textContent); + if (hasValue(droppedPage) && !Number.isNaN(droppedPage)) { + dropPage = droppedPage - 1; + dropIndex = 0; } - } else { - this.objectUpdatesService.saveMoveFieldUpdate(this.url, event.previousIndex, event.currentIndex, this.currentPage$.value - 1, this.currentPage$.value - 1); + } + + const isNewPage = dragPage !== dropPage; + // Move the object in the custom order array if the drop happened within the same page + // This allows us to instantly display a change in the order, instead of waiting for the REST API's response first + if (!isNewPage && dragIndex !== dropIndex) { + moveItemInArray(this.customOrder, dragIndex, dropIndex); + } + + const redirectPage = dropPage + 1; + const fromIndex = (dragPage * this.pageSize) + dragIndex; + const toIndex = (dropPage * this.pageSize) + dropIndex; + // Send out a drop event (and navigate to the new page) when the "from" and "to" indexes are different from each other + if (fromIndex !== toIndex) { + if (isNewPage) { + this.loading$.next(true); + } + this.dropObject.emit(Object.assign({ + fromIndex, + toIndex, + finish: () => { + if (isNewPage) { + this.paginationComponent.doPageChange(redirectPage); + } + } + })); } } /** - * Method checking if there's an update ready to be fired. Send out a MoveFieldUpdate to the store if there's an - * update present and clear the update afterwards. + * unsub all subscriptions */ - fireToUpdate() { - if (hasValue(this.toUpdate)) { - this.objectUpdatesService.saveMoveFieldUpdate(this.url, this.toUpdate.fromIndex, this.toUpdate.toIndex, this.toUpdate.fromPage, this.toUpdate.toPage, this.toUpdate.field); - this.toUpdate = undefined; - } + ngOnDestroy(): void { + this.subs.filter((sub) => hasValue(sub)).forEach((sub) => sub.unsubscribe()); } } diff --git a/src/app/shared/pagination/pagination.utils.ts b/src/app/shared/pagination/pagination.utils.ts new file mode 100644 index 0000000000..5701c96b54 --- /dev/null +++ b/src/app/shared/pagination/pagination.utils.ts @@ -0,0 +1,14 @@ +import { PaginationComponentOptions } from './pagination-component-options.model'; +import { FindListOptions } from '../../core/data/request.models'; + +/** + * Transform a PaginationComponentOptions object into a FindListOptions object + * @param pagination The PaginationComponentOptions to transform + * @param original An original FindListOptions object to start from + */ +export function toFindListOptions(pagination: PaginationComponentOptions, original?: FindListOptions): FindListOptions { + return Object.assign(new FindListOptions(), original, { + currentPage: pagination.currentPage, + elementsPerPage: pagination.pageSize + }); +} diff --git a/src/app/shared/shared.module.ts b/src/app/shared/shared.module.ts index 67d7db5c5d..8ef3f91257 100644 --- a/src/app/shared/shared.module.ts +++ b/src/app/shared/shared.module.ts @@ -202,6 +202,7 @@ import { ResourcePolicyTargetResolver } from './resource-policies/resolvers/reso import { ResourcePolicyResolver } from './resource-policies/resolvers/resource-policy.resolver'; import { EpersonSearchBoxComponent } from './resource-policies/form/eperson-group-list/eperson-search-box/eperson-search-box.component'; import { GroupSearchBoxComponent } from './resource-policies/form/eperson-group-list/group-search-box/group-search-box.component'; +import { CollectionDropdownComponent } from './collection-dropdown/collection-dropdown.component'; const MODULES = [ // Do NOT include UniversalModule, HttpModule, or JsonpModule here @@ -386,7 +387,8 @@ const COMPONENTS = [ ResourcePolicyFormComponent, EpersonGroupListComponent, EpersonSearchBoxComponent, - GroupSearchBoxComponent + GroupSearchBoxComponent, + CollectionDropdownComponent ]; const ENTRY_COMPONENTS = [ @@ -504,8 +506,7 @@ const DIRECTIVES = [ ...COMPONENTS, ...DIRECTIVES, ...ENTRY_COMPONENTS, - ...SHARED_ITEM_PAGE_COMPONENTS, - + ...SHARED_ITEM_PAGE_COMPONENTS ], providers: [ ...PROVIDERS diff --git a/src/app/submission/form/collection/submission-form-collection.component.html b/src/app/submission/form/collection/submission-form-collection.component.html index 6f4a8a864c..d897cc31fd 100644 --- a/src/app/submission/form/collection/submission-form-collection.component.html +++ b/src/app/submission/form/collection/submission-form-collection.component.html @@ -1,5 +1,20 @@
-
+
+
+ {{ 'submission.sections.general.collection' | translate }} +
+
+ {{ selectedCollectionName$ | async }} +
+
+
{{ 'submission.sections.general.collection' | translate }} @@ -10,7 +25,7 @@ class="btn btn-outline-primary" (blur)="onClose()" (click)="onClose()" - [disabled]="(disabled$ | async) || (processingChange$ | async)" + [disabled]="(processingChange$ | async)" ngbDropdownToggle> {{ selectedCollectionName$ | async }} @@ -20,31 +35,9 @@ class="dropdown-menu" id="collectionControlsDropdownMenu" aria-labelledby="collectionControlsMenuButton"> -
- -
- -
- - -
+ +
diff --git a/src/app/submission/form/collection/submission-form-collection.component.spec.ts b/src/app/submission/form/collection/submission-form-collection.component.spec.ts index 105d94b966..0132289266 100644 --- a/src/app/submission/form/collection/submission-form-collection.component.spec.ts +++ b/src/app/submission/form/collection/submission-form-collection.component.spec.ts @@ -1,14 +1,11 @@ -import { ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA, DebugElement, SimpleChange } from '@angular/core'; +import { ChangeDetectorRef, Component, CUSTOM_ELEMENTS_SCHEMA, DebugElement } from '@angular/core'; import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; -import { of as observableOf } from 'rxjs'; -import { filter } from 'rxjs/operators'; import { TranslateModule } from '@ngx-translate/core'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { Store } from '@ngrx/store'; -import { cold } from 'jasmine-marbles'; import { SubmissionServiceStub } from '../../../shared/testing/submission-service.stub'; import { mockSubmissionId, mockSubmissionRestResponse } from '../../../shared/mocks/submission.mock'; @@ -19,172 +16,13 @@ import { SubmissionJsonPatchOperationsService } from '../../../core/submission/s import { SubmissionJsonPatchOperationsServiceStub } from '../../../shared/testing/submission-json-patch-operations-service.stub'; import { JsonPatchOperationsBuilder } from '../../../core/json-patch/builder/json-patch-operations-builder'; import { JsonPatchOperationPathCombiner } from '../../../core/json-patch/builder/json-patch-operation-path-combiner'; -import { RemoteData } from '../../../core/data/remote-data'; -import { Community } from '../../../core/shared/community.model'; -import { PaginatedList } from '../../../core/data/paginated-list'; -import { PageInfo } from '../../../core/shared/page-info.model'; -import { Collection } from '../../../core/shared/collection.model'; import { createTestComponent } from '../../../shared/testing/utils.test'; import { CollectionDataService } from '../../../core/data/collection-data.service'; - -const subcommunities = [Object.assign(new Community(), { - name: 'SubCommunity 1', - id: '123456789-1', - metadata: [ - { - key: 'dc.title', - language: 'en_US', - value: 'SubCommunity 1' - }] -}), - Object.assign(new Community(), { - name: 'SubCommunity 1', - id: '123456789s-1', - metadata: [ - { - key: 'dc.title', - language: 'en_US', - value: 'SubCommunity 1' - }] - }) -]; - -const mockCommunity1Collection1 = Object.assign(new Collection(), { - name: 'Community 1-Collection 1', - id: '1234567890-1', - metadata: [ - { - key: 'dc.title', - language: 'en_US', - value: 'Community 1-Collection 1' - }] -}); - -const mockCommunity1Collection2 = Object.assign(new Collection(), { - name: 'Community 1-Collection 2', - id: '1234567890-2', - metadata: [ - { - key: 'dc.title', - language: 'en_US', - value: 'Community 1-Collection 2' - }] -}); - -const mockCommunity2Collection1 = Object.assign(new Collection(), { - name: 'Community 2-Collection 1', - id: '1234567890-3', - metadata: [ - { - key: 'dc.title', - language: 'en_US', - value: 'Community 2-Collection 1' - }] -}); - -const mockCommunity2Collection2 = Object.assign(new Collection(), { - name: 'Community 2-Collection 2', - id: '1234567890-4', - metadata: [ - { - key: 'dc.title', - language: 'en_US', - value: 'Community 2-Collection 2' - }] -}); - -const mockCommunity = Object.assign(new Community(), { - name: 'Community 1', - id: '123456789-1', - metadata: [ - { - key: 'dc.title', - language: 'en_US', - value: 'Community 1' - }], - collections: observableOf(new RemoteData(true, true, true, - undefined, new PaginatedList(new PageInfo(), [mockCommunity1Collection1, mockCommunity1Collection2]))), - subcommunities: observableOf(new RemoteData(true, true, true, - undefined, new PaginatedList(new PageInfo(), subcommunities))), -}); - -const mockCommunity2 = Object.assign(new Community(), { - name: 'Community 2', - id: '123456789-2', - metadata: [ - { - key: 'dc.title', - language: 'en_US', - value: 'Community 2' - }], - collections: observableOf(new RemoteData(true, true, true, - undefined, new PaginatedList(new PageInfo(), [mockCommunity2Collection1, mockCommunity2Collection2]))), - subcommunities: observableOf(new RemoteData(true, true, true, - undefined, new PaginatedList(new PageInfo(), []))), -}); - -const mockCommunity1Collection1Rd = observableOf(new RemoteData(true, true, true, - undefined, mockCommunity1Collection1)); - -const mockCommunityList = observableOf(new RemoteData(true, true, true, - undefined, new PaginatedList(new PageInfo(), [mockCommunity, mockCommunity2]))); - -const mockCommunityCollectionList = observableOf(new RemoteData(true, true, true, - undefined, new PaginatedList(new PageInfo(), [mockCommunity1Collection1, mockCommunity1Collection2]))); - -const mockCommunity2CollectionList = observableOf(new RemoteData(true, true, true, - undefined, new PaginatedList(new PageInfo(), [mockCommunity2Collection1, mockCommunity2Collection2]))); - -const mockCollectionList = [ - { - communities: [ - { - id: '123456789-1', - name: 'Community 1' - } - ], - collection: { - id: '1234567890-1', - name: 'Community 1-Collection 1' - } - }, - { - communities: [ - { - id: '123456789-1', - name: 'Community 1' - } - ], - collection: { - id: '1234567890-2', - name: 'Community 1-Collection 2' - } - }, - { - communities: [ - { - id: '123456789-2', - name: 'Community 2' - } - ], - collection: { - id: '1234567890-3', - name: 'Community 2-Collection 1' - } - }, - { - communities: [ - { - id: '123456789-2', - name: 'Community 2' - } - ], - collection: { - id: '1234567890-4', - name: 'Community 2-Collection 2' - } - } -]; +import { hot, cold } from 'jasmine-marbles'; +import { of } from 'rxjs'; +import { SectionsService } from '../../sections/sections.service'; +import { componentFactoryName } from '@angular/compiler'; +import { Collection } from 'src/app/core/shared/collection.model'; describe('SubmissionFormCollectionComponent Component', () => { @@ -198,7 +36,57 @@ describe('SubmissionFormCollectionComponent Component', () => { const collectionId = '1234567890-1'; const definition = 'traditional'; const submissionRestResponse = mockSubmissionRestResponse; - const searchedCollection = 'Community 2-Collection 2'; + + const mockCollectionList = [ + { + communities: [ + { + id: '123456789-1', + name: 'Community 1' + } + ], + collection: { + id: '1234567890-1', + name: 'Community 1-Collection 1' + } + }, + { + communities: [ + { + id: '123456789-1', + name: 'Community 1' + } + ], + collection: { + id: '1234567890-2', + name: 'Community 1-Collection 2' + } + }, + { + communities: [ + { + id: '123456789-2', + name: 'Community 2' + } + ], + collection: { + id: '1234567890-3', + name: 'Community 2-Collection 1' + } + }, + { + communities: [ + { + id: '123456789-2', + name: 'Community 2' + } + ], + collection: { + id: '1234567890-4', + name: 'Community 2-Collection 2' + } + } + ]; const communityDataService: any = jasmine.createSpyObj('communityDataService', { findAll: jasmine.createSpy('findAll') @@ -217,6 +105,10 @@ describe('SubmissionFormCollectionComponent Component', () => { replace: jasmine.createSpy('replace') }); + const sectionsService: any = jasmine.createSpyObj('sectionsService', { + isSectionAvailable: of(true) + }); + beforeEach(async(() => { TestBed.configureTestingModule({ imports: [ @@ -236,6 +128,7 @@ describe('SubmissionFormCollectionComponent Component', () => { { provide: CommunityDataService, useValue: communityDataService }, { provide: JsonPatchOperationsBuilder, useValue: jsonPatchOpBuilder }, { provide: Store, useValue: store }, + { provide: SectionsService, useValue: sectionsService }, ChangeDetectorRef, SubmissionFormCollectionComponent ], @@ -299,72 +192,11 @@ describe('SubmissionFormCollectionComponent Component', () => { expect(compAsAny.pathCombiner).toEqual(expected); }); - it('should init collection list properly', () => { - communityDataService.findAll.and.returnValue(mockCommunityList); - collectionDataService.findById.and.returnValue(mockCommunity1Collection1Rd); - collectionDataService.getAuthorizedCollectionByCommunity.and.returnValues(mockCommunityCollectionList, mockCommunity2CollectionList); - - comp.ngOnChanges({ - currentCollectionId: new SimpleChange(null, collectionId, true) - }); - - expect(comp.searchListCollection$).toBeObservable(cold('(ab)', { - a: [], - b: mockCollectionList - })); - - expect(comp.selectedCollectionName$).toBeObservable(cold('(a|)', { - a: 'Community 1-Collection 1' - })); - }); - - it('should show only the searched collection', () => { - comp.searchListCollection$ = observableOf(mockCollectionList); - fixture.detectChanges(); - - comp.searchField.setValue(searchedCollection); - fixture.detectChanges(); - - comp.searchListCollection$.pipe( - filter(() => !comp.disabled$.getValue()) - ).subscribe((list) => { - expect(list).toEqual([mockCollectionList[3]]); - }); - - }); - - it('should emit collectionChange event when selecting a new collection', () => { - spyOn(comp.searchField, 'reset').and.callThrough(); - spyOn(comp.collectionChange, 'emit').and.callThrough(); - jsonPatchOpServiceStub.jsonPatchByResourceID.and.returnValue(observableOf(submissionRestResponse)); - comp.ngOnInit(); - comp.onSelect(mockCollectionList[1]); - fixture.detectChanges(); - - expect(comp.searchField.reset).toHaveBeenCalled(); - expect(comp.collectionChange.emit).toHaveBeenCalledWith(submissionRestResponse[0] as any); - expect(submissionServiceStub.changeSubmissionCollection).toHaveBeenCalled(); - expect(comp.selectedCollectionId).toBe(mockCollectionList[1].collection.id); - expect(comp.selectedCollectionName$).toBeObservable(cold('(a|)', { - a: mockCollectionList[1].collection.name - })); - - }); - - it('should reset searchField when dropdown menu has been closed', () => { - spyOn(comp.searchField, 'reset').and.callThrough(); - comp.toggled(false); - - expect(comp.searchField.reset).toHaveBeenCalled(); - }); - describe('', () => { let dropdowBtn: DebugElement; let dropdownMenu: DebugElement; beforeEach(() => { - - comp.searchListCollection$ = observableOf(mockCollectionList); fixture.detectChanges(); dropdowBtn = fixture.debugElement.query(By.css('#collectionControlsMenuButton')); dropdownMenu = fixture.debugElement.query(By.css('#collectionControlsDropdownMenu')); @@ -387,49 +219,46 @@ describe('SubmissionFormCollectionComponent Component', () => { fixture.whenStable().then(() => { expect(comp.onClose).toHaveBeenCalled(); expect(dropdownMenu.nativeElement.classList).toContain('show'); - expect(dropdownMenu.queryAll(By.css('.collection-item')).length).toBe(4); }); })); - it('should trigger onSelect method when select a new collection from dropdown menu', fakeAsync(() => { + it('the dropdown menu should be enable', () => { + const dropDown = fixture.debugElement.query(By.css('#collectionControlsDropdownMenu')); + expect(dropDown).toBeTruthy(); + }); - spyOn(comp, 'onSelect'); - dropdowBtn.triggerEventHandler('click', null); - tick(); + it('the dropdown menu should be disabled', () => { + comp.available$ = of(false); + fixture.detectChanges(); + const dropDown = fixture.debugElement.query(By.css('#collectionControlsDropdownMenu')); + expect(dropDown).toBeFalsy(); + }); + + it('should be simulated when the drop-down menu is closed', () => { + spyOn(comp, 'onClose'); + comp.onClose(); + expect(comp.onClose).toHaveBeenCalled(); + }); + + it('should be simulated when the drop-down menu is toggled', () => { + spyOn(comp, 'toggled'); + comp.toggled(false); + expect(comp.toggled).toHaveBeenCalled(); + }); + + it('should ', () => { + spyOn(comp.collectionChange, 'emit').and.callThrough(); + jsonPatchOpServiceStub.jsonPatchByResourceID.and.returnValue(of(submissionRestResponse)); + comp.ngOnInit(); + comp.onSelect(mockCollectionList[1]); fixture.detectChanges(); - const secondLink: DebugElement = dropdownMenu.query(By.css('.collection-item:nth-child(2)')); - secondLink.triggerEventHandler('click', null); - tick(); - fixture.detectChanges(); - - fixture.whenStable().then(() => { - - expect(comp.onSelect).toHaveBeenCalled(); - }); - })); - - it('should update searchField on input type', fakeAsync(() => { - - dropdowBtn.triggerEventHandler('click', null); - tick(); - fixture.detectChanges(); - - fixture.whenStable().then(() => { - const input = fixture.debugElement.query(By.css('input.form-control')); - const el = input.nativeElement; - - expect(el.value).toBe(''); - - el.value = searchedCollection; - el.dispatchEvent(new Event('input')); - - fixture.detectChanges(); - - expect(fixture.componentInstance.searchField.value).toEqual(searchedCollection); - }); - })); - + expect(submissionServiceStub.changeSubmissionCollection).toHaveBeenCalled(); + expect(comp.selectedCollectionId).toBe(mockCollectionList[1].collection.id); + expect(comp.selectedCollectionName$).toBeObservable(cold('(a|)', { + a: mockCollectionList[1].collection.name + })); + }); }); }); diff --git a/src/app/submission/form/collection/submission-form-collection.component.ts b/src/app/submission/form/collection/submission-form-collection.component.ts index f84764d6a4..aa1bf9cb0a 100644 --- a/src/app/submission/form/collection/submission-form-collection.component.ts +++ b/src/app/submission/form/collection/submission-form-collection.component.ts @@ -2,57 +2,31 @@ import { ChangeDetectorRef, Component, EventEmitter, - HostListener, Input, OnChanges, OnInit, Output, - SimpleChanges + SimpleChanges, + ViewChild } from '@angular/core'; -import { FormControl } from '@angular/forms'; -import { BehaviorSubject, combineLatest, Observable, of as observableOf, Subscription } from 'rxjs'; +import { BehaviorSubject, Observable, of as observableOf, Subscription } from 'rxjs'; import { - debounceTime, - distinctUntilChanged, - filter, find, - flatMap, - map, - mergeMap, - reduce, - startWith + map } from 'rxjs/operators'; import { Collection } from '../../../core/shared/collection.model'; -import { CommunityDataService } from '../../../core/data/community-data.service'; -import { Community } from '../../../core/shared/community.model'; -import { hasValue, isEmpty, isNotEmpty } from '../../../shared/empty.util'; +import { hasValue, isNotEmpty } from '../../../shared/empty.util'; import { RemoteData } from '../../../core/data/remote-data'; import { JsonPatchOperationPathCombiner } from '../../../core/json-patch/builder/json-patch-operation-path-combiner'; import { JsonPatchOperationsBuilder } from '../../../core/json-patch/builder/json-patch-operations-builder'; -import { PaginatedList } from '../../../core/data/paginated-list'; import { SubmissionService } from '../../submission.service'; import { SubmissionObject } from '../../../core/submission/models/submission-object.model'; import { SubmissionJsonPatchOperationsService } from '../../../core/submission/submission-json-patch-operations.service'; import { CollectionDataService } from '../../../core/data/collection-data.service'; -import { FindListOptions } from '../../../core/data/request.models'; - -/** - * An interface to represent a collection entry - */ -interface CollectionListEntryItem { - id: string; - name: string; -} - -/** - * An interface to represent an entry in the collection list - */ -interface CollectionListEntry { - communities: CollectionListEntryItem[], - collection: CollectionListEntryItem -} +import { CollectionDropdownComponent } from 'src/app/shared/collection-dropdown/collection-dropdown.component'; +import { SectionsService } from '../../sections/sections.service'; /** * This component allows to show the current collection the submission belonging to and to change it. @@ -88,30 +62,12 @@ export class SubmissionFormCollectionComponent implements OnChanges, OnInit { */ @Output() collectionChange: EventEmitter = new EventEmitter(); - /** - * A boolean representing if this dropdown button is disabled - * @type {BehaviorSubject} - */ - public disabled$ = new BehaviorSubject(true); - /** * A boolean representing if a collection change operation is processing * @type {BehaviorSubject} */ public processingChange$ = new BehaviorSubject(false); - /** - * The search form control - * @type {FormControl} - */ - public searchField: FormControl = new FormControl(); - - /** - * The collection list obtained from a search - * @type {Observable} - */ - public searchListCollection$: Observable; - /** * The selected collection id * @type {string} @@ -130,24 +86,23 @@ export class SubmissionFormCollectionComponent implements OnChanges, OnInit { */ protected pathCombiner: JsonPatchOperationPathCombiner; - /** - * A boolean representing if dropdown list is scrollable to the bottom - * @type {boolean} - */ - private scrollableBottom = false; - - /** - * A boolean representing if dropdown list is scrollable to the top - * @type {boolean} - */ - private scrollableTop = false; - /** * Array to track all subscriptions and unsubscribe them onDestroy * @type {Array} */ private subs: Subscription[] = []; + /** + * The html child that contains the collections list + */ + @ViewChild(CollectionDropdownComponent, {static: false}) collectionDropdown: CollectionDropdownComponent; + + /** + * A boolean representing if the collection section is available + * @type {BehaviorSubject} + */ + available$: Observable; + /** * Initialize instance variables * @@ -159,37 +114,11 @@ export class SubmissionFormCollectionComponent implements OnChanges, OnInit { * @param {SubmissionService} submissionService */ constructor(protected cdr: ChangeDetectorRef, - private communityDataService: CommunityDataService, private collectionDataService: CollectionDataService, private operationsBuilder: JsonPatchOperationsBuilder, private operationsService: SubmissionJsonPatchOperationsService, - private submissionService: SubmissionService) { - } - - /** - * Method called on mousewheel event, it prevent the page scroll - * when arriving at the top/bottom of dropdown menu - * - * @param event - * mousewheel event - */ - @HostListener('mousewheel', ['$event']) onMousewheel(event) { - if (event.wheelDelta > 0 && this.scrollableTop) { - event.preventDefault(); - } - if (event.wheelDelta < 0 && this.scrollableBottom) { - event.preventDefault(); - } - } - - /** - * Check if dropdown scrollbar is at the top or bottom of the dropdown list - * - * @param event - */ - onScroll(event) { - this.scrollableBottom = (event.target.scrollTop + event.target.clientHeight === event.target.scrollHeight); - this.scrollableTop = (event.target.scrollTop === 0); + private submissionService: SubmissionService, + private sectionsService: SectionsService) { } /** @@ -204,51 +133,6 @@ export class SubmissionFormCollectionComponent implements OnChanges, OnInit { find((collectionRD: RemoteData) => isNotEmpty(collectionRD.payload)), map((collectionRD: RemoteData) => collectionRD.payload.name) ); - - const findOptions: FindListOptions = { - elementsPerPage: 1000 - }; - - // Retrieve collection list only when is the first change - if (changes.currentCollectionId.isFirstChange()) { - // @TODO replace with search/top browse endpoint - // @TODO implement community/subcommunity hierarchy - const communities$ = this.communityDataService.findAll(findOptions).pipe( - find((communities: RemoteData>) => isNotEmpty(communities.payload)), - mergeMap((communities: RemoteData>) => communities.payload.page)); - - const listCollection$ = communities$.pipe( - flatMap((communityData: Community) => { - return this.collectionDataService.getAuthorizedCollectionByCommunity(communityData.uuid, findOptions).pipe( - find((collections: RemoteData>) => !collections.isResponsePending && collections.hasSucceeded), - mergeMap((collections: RemoteData>) => collections.payload.page), - filter((collectionData: Collection) => isNotEmpty(collectionData)), - map((collectionData: Collection) => ({ - communities: [{ id: communityData.id, name: communityData.name }], - collection: { id: collectionData.id, name: collectionData.name } - })) - ); - }), - reduce((acc: any, value: any) => [...acc, ...value], []), - startWith([]) - ); - - const searchTerm$ = this.searchField.valueChanges.pipe( - debounceTime(200), - distinctUntilChanged(), - startWith('') - ); - - this.searchListCollection$ = combineLatest(searchTerm$, listCollection$).pipe( - map(([searchTerm, listCollection]) => { - this.disabled$.next(isEmpty(listCollection)); - if (isEmpty(searchTerm)) { - return listCollection; - } else { - return listCollection.filter((v) => v.collection.name.toLowerCase().indexOf(searchTerm.toLowerCase()) > -1).slice(0, 5); - } - })); - } } } @@ -257,6 +141,7 @@ export class SubmissionFormCollectionComponent implements OnChanges, OnInit { */ ngOnInit() { this.pathCombiner = new JsonPatchOperationPathCombiner('sections', 'collection'); + this.available$ = this.sectionsService.isSectionAvailable(this.submissionId, 'collection'); } /** @@ -273,7 +158,6 @@ export class SubmissionFormCollectionComponent implements OnChanges, OnInit { * the selected [CollectionListEntryItem] */ onSelect(event) { - this.searchField.reset(); this.processingChange$.next(true); this.operationsBuilder.replace(this.pathCombiner.getPath(), event.collection.id, true); this.subs.push(this.operationsService.jsonPatchByResourceID( @@ -296,7 +180,7 @@ export class SubmissionFormCollectionComponent implements OnChanges, OnInit { * Reset search form control on dropdown menu close */ onClose() { - this.searchField.reset(); + this.collectionDropdown.reset(); } /** @@ -307,7 +191,7 @@ export class SubmissionFormCollectionComponent implements OnChanges, OnInit { */ toggled(isOpen: boolean) { if (!isOpen) { - this.searchField.reset(); + this.collectionDropdown.reset(); } } } diff --git a/src/assets/i18n/en.json5 b/src/assets/i18n/en.json5 index 776ec09e1f..9c69ba5199 100644 --- a/src/assets/i18n/en.json5 +++ b/src/assets/i18n/en.json5 @@ -8,6 +8,10 @@ + "admin.registries.bitstream-formats.breadcrumbs": "Format registry", + + "admin.registries.bitstream-formats.create.breadcrumbs": "Bitstream format", + "admin.registries.bitstream-formats.create.failure.content": "An error occurred while creating the new bitstream format.", "admin.registries.bitstream-formats.create.failure.head": "Failure", @@ -30,6 +34,8 @@ "admin.registries.bitstream-formats.description": "This list of bitstream formats provides information about known formats and their support level.", + "admin.registries.bitstream-formats.edit.breadcrumbs": "Bitstream format", + "admin.registries.bitstream-formats.edit.description.hint": "", "admin.registries.bitstream-formats.edit.description.label": "Description", @@ -94,6 +100,8 @@ + "admin.registries.metadata.breadcrumbs": "Metadata registry", + "admin.registries.metadata.description": "The metadata registry maintains a list of all metadata fields available in the repository. These fields may be divided amongst multiple schemas. However, DSpace requires the qualified Dublin Core schema.", "admin.registries.metadata.form.create": "Create metadata schema", @@ -120,6 +128,8 @@ + "admin.registries.schema.breadcrumbs": "Metadata schema", + "admin.registries.schema.description": "This is the metadata schema for \"{{namespace}}\".", "admin.registries.schema.fields.head": "Schema metadata fields", @@ -767,6 +777,10 @@ "community.edit.notifications.success": "Successfully edited the Community", + "community.edit.notifications.unauthorized": "You do not have privileges to make this change", + + "community.edit.notifications.error": "An error occured while editing the Community", + "community.edit.return": "Return", @@ -1793,7 +1807,7 @@ "mydspace.description": "", - "mydspace.general.text-here": "HERE", + "mydspace.general.text-here": "here", "mydspace.messages.controller-help": "Select this option to send a message to item's submitter.",