diff --git a/resources/i18n/en.json b/resources/i18n/en.json index 1bdcb0cf5f..4260568a7e 100644 --- a/resources/i18n/en.json +++ b/resources/i18n/en.json @@ -97,7 +97,7 @@ "uri": "URI", "files": "Files", "collections": "Collections", - "subject": "Keywords", + "subject": "Keywords", "citation": "Citation", "filesection": { "download": "Download", @@ -392,6 +392,7 @@ }, "login": "Log In", "logout": "Log Out", + "mydspace": "MyDSpace", "language": "Language switch", "search": "Search" }, @@ -428,6 +429,57 @@ "help": "Select a community to browse its collections." } }, + "mydspace": { + "title": "MyDSpace", + "description": "", + "new-submission": "New submission", + "results": { + "head": "Your submissions", + "no-results": "There were no items to show", + "no-title": "No title", + "no-authors": "No Authors", + "no-date": "No Date", + "no-abstract": "No Abstract", + "no-files": "No Files", + "no-uri": "No Uri", + "no-collections": "No Collections" + }, + "messages": { + "title": "Messages", + "to": "To", + "hide-msg": "Hide message", + "show-msg": "Show message", + "no-messages": "No messages yet.", + "no-content": "No content.", + "send-btn": "Send", + "subject-placeholder": "Subject...", + "description-placeholder": "Insert your message here...", + "mark-as-read": "Mark as read", + "mark-as-unread": "Mark as unread", + "submitter-help": "Select this option to send a message to controller.", + "controller-help": "Select this option to send a message to item's submitter." + }, + "show": { + "workspace": "Your Submissions", + "workflow": "All tasks" + }, + "status": { + "workflow": "Workflow", + "validation": "Validation", + "waiting-for-controller": "Waiting for controller", + "workspace": "Workspace", + "archived": "Archived" + }, + "view-btn": "View", + "general": { + "text-here": "HERE" + }, + "upload": { + "upload-successful": "New workspace item created. Click {{here}} for edit it.", + "upload-multiple-successful": "{{qty}} new workspace items created.", + "upload-failed": "Error creating new workspace. Please verify the content uploaded before retry." + } + }, "search": { "journal": { "title": "DSpace Angular :: Journal Search", @@ -451,7 +503,8 @@ "description": "", "form": { "search": "Search", - "search_dspace": "Search DSpace" + "search_dspace": "Search DSpace", + "search_mydspace": "Search MyDSpace" }, "results": { "head": "Search Results", @@ -471,9 +524,13 @@ "rpp": "Results per page" } }, + "switch-configuration": { + "title":"Show" + }, "view-switch": { "show-list": "Show as list", - "show-grid": "Show as grid" + "show-grid": "Show as grid", + "show-detail": "Show detail" }, "filters": { "head": "Filters", @@ -484,7 +541,11 @@ "f.dateIssued.max": "End date", "f.subject": "Subject", "f.has_content_in_original_bundle": "Has files", - "f.entityType": "Item Type" + "f.entityType": "Item Type", + "f.namedresourcetype": "Status", + "f.dateSubmitted": "Date submitted", + "f.itemtype": "Type", + "f.submitter": "Submitter" }, "filter": { "show-more": "Show more", @@ -516,6 +577,26 @@ "entityType": { "placeholder": "Item Type", "head": "Item Type" + }, + "namedresourcetype": { + "placeholder": "Status", + "head": "Status" + }, + "dateSubmitted": { + "placeholder": "Date submitted", + "head": "Date submitted" + }, + "itemtype": { + "placeholder": "Type", + "head": "Type" + }, + "submitter": { + "placeholder": "Submitter", + "head": "Submitter" + }, + "objectpeople": { + "placeholder": "People", + "head": "People" } } } @@ -736,6 +817,7 @@ "item": "Loading item...", "objects": "Loading...", "search-results": "Loading search results...", + "mydspace-results": "Loading items...", "browse-by": "Loading items...", "browse-by-page": "Loading page..." }, @@ -927,6 +1009,49 @@ } } } + }, + "workflow": { + "generic": { + "delete": "Delete", + "delete-help": "If you would to discard this item, select \"Delete\". You will then be asked to confirm it.", + "edit": "Edit", + "edit-help": "Select this option to change the item's metadata.", + "view": "View", + "view-help": "Select this option to view the item's metadata." + }, + "tasks": { + "generic": { + "processing": "Processing...", + "success": "Operation successful", + "error": "Error occurred during operation...", + "submitter": "Submitter" + }, + "claimed": { + "approve": "Approve", + "approve_help": "If you have reviewed the item and it is suitable for inclusion in the collection, select \"Approve\".", + "edit": "Edit", + "edit_help": "Select this option to change the item's metadata.", + "reject": { + "submit": "Reject", + "reason": { + "submit": "Reject item", + "title": "Reason", + "info": "Please enter your reason for rejecting the submission into the box below, indicating whether the submitter may fix a problem and resubmit.", + "placeholder": "Describe the reason of reject" + } + }, + "reject_help": "If you have reviewed the item and found it is not suitable for inclusion in the collection, select \"Reject\". You will then be asked to enter a message indicating why the item is unsuitable, and whether the submitter should change something and resubmit.", + "return": "Return to pool", + "return_help": "Return the task to the pool so that another user may perform the task." + + }, + "pool": { + "claim": "Claim", + "claim_help": "Assign this task to yourself.", + "show-detail": "Show detail", + "hide-detail": "Hide detail" + } + } } }, "uploader": { 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 4364b0234a..c6402c1f3b 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 @@ -28,6 +28,7 @@ describe('MetadataFieldFormComponent', () => { const registryServiceStub = { getActiveMetadataField: () => observableOf(undefined), createOrUpdateMetadataField: (field: MetadataField) => observableOf(field), + cancelEditMetadataField: () => {}, cancelEditMetadataSchema: () => {}, }; const formBuilderServiceStub = { @@ -62,6 +63,11 @@ describe('MetadataFieldFormComponent', () => { registryService = s; })); + afterEach(() => { + component = null; + registryService = null + }) + describe('when submitting the form', () => { const element = 'fakeElement'; const qualifier = 'fakeQualifier'; diff --git a/src/app/+collection-page/edit-collection-page/edit-collection-page.component.ts b/src/app/+collection-page/edit-collection-page/edit-collection-page.component.ts index a3978a5e43..ba70bd26c6 100644 --- a/src/app/+collection-page/edit-collection-page/edit-collection-page.component.ts +++ b/src/app/+collection-page/edit-collection-page/edit-collection-page.component.ts @@ -1,7 +1,6 @@ import { Component } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { EditComColPageComponent } from '../../shared/comcol-forms/edit-comcol-page/edit-comcol-page.component'; -import { NormalizedCollection } from '../../core/cache/models/normalized-collection.model'; import { Collection } from '../../core/shared/collection.model'; import { CollectionDataService } from '../../core/data/collection-data.service'; diff --git a/src/app/+item-page/edit-item-page/edit-item-page.component.ts b/src/app/+item-page/edit-item-page/edit-item-page.component.ts index 4ea47f08e7..eafc04ae0b 100644 --- a/src/app/+item-page/edit-item-page/edit-item-page.component.ts +++ b/src/app/+item-page/edit-item-page/edit-item-page.component.ts @@ -1,6 +1,6 @@ import { fadeIn, fadeInOut } from '../../shared/animations/fade'; import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core'; -import { ActivatedRoute, Params, Router } from '@angular/router'; +import { ActivatedRoute, Router } from '@angular/router'; import { RemoteData } from '../../core/data/remote-data'; import { Item } from '../../core/shared/item.model'; import { Observable } from 'rxjs'; diff --git a/src/app/+item-page/item-page.module.ts b/src/app/+item-page/item-page.module.ts index 0c4ccc868b..123e3ea143 100644 --- a/src/app/+item-page/item-page.module.ts +++ b/src/app/+item-page/item-page.module.ts @@ -6,9 +6,7 @@ import { GenericItemPageFieldComponent } from './simple/field-components/specifi import { ItemPageComponent } from './simple/item-page.component'; import { ItemPageRoutingModule } from './item-page-routing.module'; -import { MetadataValuesComponent } from './field-components/metadata-values/metadata-values.component'; import { MetadataUriValuesComponent } from './field-components/metadata-uri-values/metadata-uri-values.component'; -import { MetadataFieldWrapperComponent } from './field-components/metadata-field-wrapper/metadata-field-wrapper.component'; import { ItemPageAuthorFieldComponent } from './simple/field-components/specific-field/author/item-page-author-field.component'; import { ItemPageDateFieldComponent } from './simple/field-components/specific-field/date/item-page-date-field.component'; import { ItemPageAbstractFieldComponent } from './simple/field-components/specific-field/abstract/item-page-abstract-field.component'; @@ -44,9 +42,7 @@ import { RelatedEntitiesSearchComponent } from './simple/related-entities/relate declarations: [ ItemPageComponent, FullItemPageComponent, - MetadataValuesComponent, MetadataUriValuesComponent, - MetadataFieldWrapperComponent, ItemPageAuthorFieldComponent, ItemPageDateFieldComponent, ItemPageAbstractFieldComponent, diff --git a/src/app/+item-page/simple/item-page.component.ts b/src/app/+item-page/simple/item-page.component.ts index 69487e7d40..b90dede66f 100644 --- a/src/app/+item-page/simple/item-page.component.ts +++ b/src/app/+item-page/simple/item-page.component.ts @@ -61,6 +61,6 @@ export class ItemPageComponent implements OnInit { this.thumbnail$ = this.itemRD$.pipe( map((rd: RemoteData) => rd.payload), filter((item: Item) => hasValue(item)), - mergeMap((item: Item) => item.getThumbnail()),); + mergeMap((item: Item) => item.getThumbnail())); } } diff --git a/src/app/+my-dspace-page/my-dspace-configuration-value-type.ts b/src/app/+my-dspace-page/my-dspace-configuration-value-type.ts new file mode 100644 index 0000000000..baf2f0b920 --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-configuration-value-type.ts @@ -0,0 +1,4 @@ +export enum MyDSpaceConfigurationValueType { + Workspace = 'workspace', + Workflow = 'workflow' +} diff --git a/src/app/+my-dspace-page/my-dspace-configuration.service.spec.ts b/src/app/+my-dspace-page/my-dspace-configuration.service.spec.ts new file mode 100644 index 0000000000..a2cc960f41 --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-configuration.service.spec.ts @@ -0,0 +1,257 @@ +import { of as observableOf } from 'rxjs'; + +import { MyDSpaceConfigurationService } from './my-dspace-configuration.service'; +import { PaginatedSearchOptions } from '../+search-page/paginated-search-options.model'; +import { PaginationComponentOptions } from '../shared/pagination/pagination-component-options.model'; +import { SortDirection, SortOptions } from '../core/cache/models/sort-options.model'; +import { SearchFilter } from '../+search-page/search-filter.model'; +import { ActivatedRouteStub } from '../shared/testing/active-router-stub'; +import { MockRoleService } from '../shared/mocks/mock-role-service'; +import { cold, hot } from 'jasmine-marbles'; +import { MyDSpaceConfigurationValueType } from './my-dspace-configuration-value-type'; + +describe('MyDSpaceConfigurationService', () => { + let service: MyDSpaceConfigurationService; + const value1 = 'random value'; + const prefixFilter = { + 'f.namedresourcetype': ['another value'], + 'f.dateSubmitted.min': ['2013'], + 'f.dateSubmitted.max': ['2018'] + }; + const defaults = new PaginatedSearchOptions({ + pagination: Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 }), + sort: new SortOptions('score', SortDirection.DESC), + query: '', + scope: '' + }); + + const backendFilters = [new SearchFilter('f.namedresourcetype', ['another value']), new SearchFilter('f.dateSubmitted', ['[2013 TO 2018]'])]; + + const spy = jasmine.createSpyObj('RouteService', { + getQueryParameterValue: observableOf(value1), + getQueryParamsWithPrefix: observableOf(prefixFilter) + }); + + const activatedRoute: any = new ActivatedRouteStub(); + + const roleService: any = new MockRoleService(); + + const fixedFilterService = jasmine.createSpyObj('SearchFixedFilterService', { + getQueryByFilterName: observableOf(''), + }); + + beforeEach(() => { + service = new MyDSpaceConfigurationService(roleService, fixedFilterService, spy, activatedRoute); + }); + + describe('when the scope is called', () => { + beforeEach(() => { + service.getCurrentScope(''); + }); + it('should call getQueryParameterValue on the routeService with parameter name \'scope\'', () => { + expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('scope'); + }); + }); + + describe('when getCurrentConfiguration is called', () => { + beforeEach(() => { + service.getCurrentConfiguration(''); + }); + it('should call getQueryParameterValue on the routeService with parameter name \'configuration\'', () => { + expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('configuration'); + }); + }); + + describe('when getCurrentQuery is called', () => { + beforeEach(() => { + service.getCurrentQuery(''); + }); + it('should call getQueryParameterValue on the routeService with parameter name \'query\'', () => { + expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('query'); + }); + }); + + describe('when getCurrentDSOType is called', () => { + beforeEach(() => { + service.getCurrentDSOType(); + }); + it('should call getQueryParameterValue on the routeService with parameter name \'dsoType\'', () => { + expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('dsoType'); + }); + }); + + describe('when getCurrentFrontendFilters is called', () => { + beforeEach(() => { + service.getCurrentFrontendFilters(); + }); + it('should call getQueryParamsWithPrefix on the routeService with parameter prefix \'f.\'', () => { + expect((service as any).routeService.getQueryParamsWithPrefix).toHaveBeenCalledWith('f.'); + }); + }); + + describe('when getCurrentFilters is called', () => { + let parsedValues$; + beforeEach(() => { + parsedValues$ = service.getCurrentFilters(); + }); + it('should call getQueryParamsWithPrefix on the routeService with parameter prefix \'f.\'', () => { + expect((service as any).routeService.getQueryParamsWithPrefix).toHaveBeenCalledWith('f.'); + parsedValues$.subscribe((values) => { + expect(values).toEqual(backendFilters); + }); + }); + }); + + describe('when getCurrentSort is called', () => { + beforeEach(() => { + service.getCurrentSort({} as any); + }); + it('should call getQueryParameterValue on the routeService with parameter name \'sortDirection\'', () => { + expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('sortDirection'); + }); + it('should call getQueryParameterValue on the routeService with parameter name \'sortField\'', () => { + expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('sortField'); + }); + }); + + describe('when getCurrentPagination is called', () => { + beforeEach(() => { + service.getCurrentPagination({ currentPage: 1, pageSize: 10 } as any); + }); + it('should call getQueryParameterValue on the routeService with parameter name \'page\'', () => { + expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('page'); + }); + it('should call getQueryParameterValue on the routeService with parameter name \'pageSize\'', () => { + expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('pageSize'); + }); + }); + + describe('when subscribeToSearchOptions or subscribeToPaginatedSearchOptions is called', () => { + beforeEach(() => { + spyOn(service, 'getCurrentPagination').and.callThrough(); + spyOn(service, 'getCurrentSort').and.callThrough(); + spyOn(service, 'getCurrentScope').and.callThrough(); + spyOn(service, 'getCurrentConfiguration').and.callThrough(); + spyOn(service, 'getCurrentQuery').and.callThrough(); + spyOn(service, 'getCurrentDSOType').and.callThrough(); + spyOn(service, 'getCurrentFilters').and.callThrough(); + }); + + describe('when subscribeToSearchOptions is called', () => { + beforeEach(() => { + (service as any).subscribeToSearchOptions(defaults) + }); + it('should call all getters it needs, but not call any others', () => { + expect(service.getCurrentPagination).not.toHaveBeenCalled(); + expect(service.getCurrentSort).not.toHaveBeenCalled(); + expect(service.getCurrentScope).toHaveBeenCalled(); + expect(service.getCurrentConfiguration).toHaveBeenCalled(); + expect(service.getCurrentQuery).toHaveBeenCalled(); + expect(service.getCurrentDSOType).toHaveBeenCalled(); + expect(service.getCurrentFilters).toHaveBeenCalled(); + }); + }); + + describe('when subscribeToPaginatedSearchOptions is called', () => { + beforeEach(() => { + (service as any).subscribeToPaginatedSearchOptions(defaults); + }); + it('should call all getters it needs', () => { + expect(service.getCurrentPagination).toHaveBeenCalled(); + expect(service.getCurrentSort).toHaveBeenCalled(); + expect(service.getCurrentScope).toHaveBeenCalled(); + expect(service.getCurrentConfiguration).toHaveBeenCalled(); + expect(service.getCurrentQuery).toHaveBeenCalled(); + expect(service.getCurrentDSOType).toHaveBeenCalled(); + expect(service.getCurrentFilters).toHaveBeenCalled(); + }); + }); + }); + + describe('when getAvailableConfigurationTypes is called', () => { + + it('should return properly list when user is submitter', () => { + roleService.setSubmitter(true); + roleService.setController(false); + roleService.setAdmin(false); + + const list$ = service.getAvailableConfigurationTypes(); + + expect(list$).toBeObservable(cold('(b|)', { + b: [ + MyDSpaceConfigurationValueType.Workspace + ] + })); + }); + + it('should return properly list when user is controller', () => { + roleService.setSubmitter(false); + roleService.setController(true); + roleService.setAdmin(false); + + const list$ = service.getAvailableConfigurationTypes(); + + expect(list$).toBeObservable(cold('(b|)', { + b: [ + MyDSpaceConfigurationValueType.Workflow + ] + })); + }); + + it('should return properly list when user is admin', () => { + roleService.setSubmitter(false); + roleService.setController(false); + roleService.setAdmin(true); + + const list$ = service.getAvailableConfigurationTypes(); + + expect(list$).toBeObservable(cold('(b|)', { + b: [ + MyDSpaceConfigurationValueType.Workflow + ] + })); + }); + + it('should return properly list when user is submitter and controller', () => { + roleService.setSubmitter(true); + roleService.setController(true); + roleService.setAdmin(false); + + const list$ = service.getAvailableConfigurationTypes(); + + expect(list$).toBeObservable(cold('(b|)', { + b: [ + MyDSpaceConfigurationValueType.Workspace, + MyDSpaceConfigurationValueType.Workflow + ] + })); + }); + }); + + describe('when getAvailableConfigurationOptions is called', () => { + + it('should return properly options list', () => { + spyOn(service, 'getAvailableConfigurationTypes').and.returnValue(hot('a', { + a: [ + MyDSpaceConfigurationValueType.Workspace, + MyDSpaceConfigurationValueType.Workflow + ] + })); + + const list$ = service.getAvailableConfigurationOptions(); + + expect(list$).toBeObservable(cold('(b|)', { + b: [ + { + value: MyDSpaceConfigurationValueType.Workspace, + label: `mydspace.show.${MyDSpaceConfigurationValueType.Workspace}` + }, + { + value: MyDSpaceConfigurationValueType.Workflow, + label: `mydspace.show.${MyDSpaceConfigurationValueType.Workflow}` + } + ] + })); + }); + }); +}); diff --git a/src/app/+my-dspace-page/my-dspace-configuration.service.ts b/src/app/+my-dspace-page/my-dspace-configuration.service.ts new file mode 100644 index 0000000000..705ec897f8 --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-configuration.service.ts @@ -0,0 +1,120 @@ +import { Injectable } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; + +import { combineLatest, Observable } from 'rxjs'; +import { first, map } from 'rxjs/operators'; + +import { MyDSpaceConfigurationValueType } from './my-dspace-configuration-value-type'; +import { RoleService } from '../core/roles/role.service'; +import { SearchConfigurationOption } from '../+search-page/search-switch-configuration/search-configuration-option.model'; +import { SearchConfigurationService } from '../+search-page/search-service/search-configuration.service'; +import { RouteService } from '../shared/services/route.service'; +import { PaginationComponentOptions } from '../shared/pagination/pagination-component-options.model'; +import { SortDirection, SortOptions } from '../core/cache/models/sort-options.model'; +import { SearchFixedFilterService } from '../+search-page/search-filters/search-filter/search-fixed-filter.service'; + +/** + * Service that performs all actions that have to do with the current mydspace configuration + */ +@Injectable() +export class MyDSpaceConfigurationService extends SearchConfigurationService { + /** + * Default pagination settings + */ + protected defaultPagination = Object.assign(new PaginationComponentOptions(), { + id: 'mydspace-page', + pageSize: 10, + currentPage: 1 + }); + + /** + * Default sort settings + */ + protected defaultSort = new SortOptions('dc.date.issued', SortDirection.DESC); + + /** + * Default configuration parameter setting + */ + protected defaultConfiguration = 'workspace'; + + /** + * Default scope setting + */ + protected defaultScope = ''; + + /** + * Default query setting + */ + protected defaultQuery = ''; + + private isAdmin$: Observable; + private isController$: Observable; + private isSubmitter$: Observable; + + /** + * Initialize class + * + * @param {roleService} roleService + * @param {SearchFixedFilterService} fixedFilterService + * @param {RouteService} routeService + * @param {ActivatedRoute} route + */ + constructor(protected roleService: RoleService, + protected fixedFilterService: SearchFixedFilterService, + protected routeService: RouteService, + protected route: ActivatedRoute) { + + super(routeService, fixedFilterService, route); + + // override parent class initialization + this._defaults = null; + this.initDefaults(); + + this.isSubmitter$ = this.roleService.isSubmitter(); + this.isController$ = this.roleService.isController(); + this.isAdmin$ = this.roleService.isAdmin(); + } + + /** + * Returns the list of available configuration depend on the user role + * + * @return {Observable} + * Emits the available configuration list + */ + public getAvailableConfigurationTypes(): Observable { + return combineLatest(this.isSubmitter$, this.isController$, this.isAdmin$).pipe( + first(), + map(([isSubmitter, isController, isAdmin]: [boolean, boolean, boolean]) => { + const availableConf: MyDSpaceConfigurationValueType[] = []; + if (isSubmitter) { + availableConf.push(MyDSpaceConfigurationValueType.Workspace); + } + if (isController || isAdmin) { + availableConf.push(MyDSpaceConfigurationValueType.Workflow); + } + return availableConf; + })); + } + + /** + * Returns the select options for the available configuration list + * + * @return {Observable} + * Emits the select options list + */ + public getAvailableConfigurationOptions(): Observable { + return this.getAvailableConfigurationTypes().pipe( + first(), + map((availableConfigurationTypes: MyDSpaceConfigurationValueType[]) => { + const configurationOptions: SearchConfigurationOption[] = []; + availableConfigurationTypes.forEach((type) => { + const value = type; + const label = `mydspace.show.${value}`; + configurationOptions.push({ value, label }); + }); + return configurationOptions; + }) + ) + } + +} 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 new file mode 100644 index 0000000000..280d694d27 --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.html @@ -0,0 +1,15 @@ + + + + + + + + {{'mydspace.new-submission' | translate}} + + + + diff --git a/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.scss b/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.scss new file mode 100644 index 0000000000..40a955b349 --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.scss @@ -0,0 +1,11 @@ +.parent { + display: flex; +} + +.upload { + flex: auto; +} + +.add { + flex: initial; +} 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 new file mode 100644 index 0000000000..012f86f579 --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.spec.ts @@ -0,0 +1,101 @@ +import { ChangeDetectorRef, Component, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, inject, TestBed } from '@angular/core/testing'; +import { RouterTestingModule } from '@angular/router/testing'; + +import { Store } from '@ngrx/store'; +import { of as observableOf } from 'rxjs'; +import { TranslateLoader, TranslateModule, TranslateService } from '@ngx-translate/core'; +import { ScrollToService } from '@nicky-lenaers/ngx-scroll-to'; + +import { HALEndpointService } from '../../core/shared/hal-endpoint.service'; +import { AuthServiceStub } from '../../shared/testing/auth-service-stub'; +import { AuthService } from '../../core/auth/auth.service'; +import { HALEndpointServiceStub } from '../../shared/testing/hal-endpoint-service-stub'; +import { createTestComponent } from '../../shared/testing/utils'; +import { MyDSpaceNewSubmissionComponent } from './my-dspace-new-submission.component'; +import { AppState } from '../../app.reducer'; +import { MockTranslateLoader } from '../../shared/mocks/mock-translate-loader'; +import { getMockTranslateService } from '../../shared/mocks/mock-translate.service'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { NotificationsServiceStub } from '../../shared/testing/notifications-service-stub'; +import { SharedModule } from '../../shared/shared.module'; +import { getMockScrollToService } from '../../shared/mocks/mock-scroll-to-service'; +import { UploaderService } from '../../shared/uploader/uploader.service'; + +describe('MyDSpaceNewSubmissionComponent test', () => { + + const translateService: any = getMockTranslateService(); + const store: Store = jasmine.createSpyObj('store', { + /* tslint:disable:no-empty */ + dispatch: {}, + /* tslint:enable:no-empty */ + pipe: observableOf(true) + }); + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + RouterTestingModule, + SharedModule, + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }) + ], + declarations: [ + MyDSpaceNewSubmissionComponent, + TestComponent + ], + providers: [ + { provide: AuthService, useClass: AuthServiceStub }, + { provide: HALEndpointService, useValue: new HALEndpointServiceStub('workspaceitems') }, + { provide: NotificationsService, useValue: new NotificationsServiceStub() }, + { provide: ScrollToService, useValue: getMockScrollToService() }, + { provide: Store, useValue: store }, + { provide: TranslateService, useValue: translateService }, + ChangeDetectorRef, + MyDSpaceNewSubmissionComponent, + UploaderService + ], + schemas: [NO_ERRORS_SCHEMA] + }).compileComponents(); + })); + + describe('', () => { + let testComp: TestComponent; + let testFixture: ComponentFixture; + + // synchronous beforeEach + beforeEach(() => { + const html = ` + `; + + testFixture = createTestComponent(html, TestComponent) as ComponentFixture; + testComp = testFixture.componentInstance; + }); + + afterEach(() => { + testFixture.destroy(); + }); + + it('should create MyDSpaceNewSubmissionComponent', inject([MyDSpaceNewSubmissionComponent], (app: MyDSpaceNewSubmissionComponent) => { + + expect(app).toBeDefined(); + + })); + }); + +}); + +// declare a test component +@Component({ + selector: 'ds-test-cmp', + template: `` +}) +class TestComponent { + + reload = (event) => { + return; + } +} 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 new file mode 100644 index 0000000000..938a1ec899 --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-new-submission/my-dspace-new-submission.component.ts @@ -0,0 +1,118 @@ +import { ChangeDetectorRef, Component, EventEmitter, OnDestroy, OnInit, Output } from '@angular/core'; + +import { Subscription } from 'rxjs'; +import { first } from 'rxjs/operators'; +import { Store } from '@ngrx/store'; +import { TranslateService } from '@ngx-translate/core'; + +import { SubmissionState } from '../../submission/submission.reducers'; +import { AuthService } from '../../core/auth/auth.service'; +import { MyDSpaceResult } from '../my-dspace-result.model'; +import { DSpaceObject } from '../../core/shared/dspace-object.model'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { NotificationOptions } from '../../shared/notifications/models/notification-options.model'; +import { UploaderOptions } from '../../shared/uploader/uploader-options.model'; +import { HALEndpointService } from '../../core/shared/hal-endpoint.service'; +import { NotificationType } from '../../shared/notifications/models/notification-type'; +import { hasValue } from '../../shared/empty.util'; + +/** + * This component represents the whole mydspace page header + */ +@Component({ + selector: 'ds-my-dspace-new-submission', + styleUrls: ['./my-dspace-new-submission.component.scss'], + templateUrl: './my-dspace-new-submission.component.html' +}) +export class MyDSpaceNewSubmissionComponent implements OnDestroy, OnInit { + @Output() uploadEnd = new EventEmitter>>(); + + /** + * The UploaderOptions object + */ + public uploadFilesOptions: UploaderOptions = { + url: '', + authToken: null, + disableMultipart: false, + itemAlias: null + }; + + /** + * Subscription to unsubscribe from + */ + private sub: Subscription; + + /** + * Initialize instance variables + * + * @param {AuthService} authService + * @param {ChangeDetectorRef} changeDetectorRef + * @param {HALEndpointService} halService + * @param {NotificationsService} notificationsService + * @param {Store} store + * @param {TranslateService} translate + */ + constructor(private authService: AuthService, + private changeDetectorRef: ChangeDetectorRef, + private halService: HALEndpointService, + private notificationsService: NotificationsService, + private store: Store, + private translate: TranslateService) { + } + + /** + * Initialize url and Bearer token + */ + ngOnInit() { + this.sub = this.halService.getEndpoint('workspaceitems').pipe(first()).subscribe((url) => { + this.uploadFilesOptions.url = url; + this.uploadFilesOptions.authToken = this.authService.buildAuthHeader(); + this.changeDetectorRef.detectChanges(); + } + ); + } + + /** + * Method called when file upload is completed to notify upload status + */ + public onCompleteItem(res) { + if (res && res._embedded && res._embedded.workspaceitems && res._embedded.workspaceitems.length > 0) { + const workspaceitems = res._embedded.workspaceitems; + this.uploadEnd.emit(workspaceitems); + + if (workspaceitems.length === 1) { + const options = new NotificationOptions(); + options.timeOut = 0; + const link = '/workspaceitems/' + workspaceitems[0].id + '/edit'; + this.notificationsService.notificationWithAnchor( + NotificationType.Success, + options, + link, + 'mydspace.general.text-here', + 'mydspace.upload.upload-successful', + 'here'); + } else if (workspaceitems.length > 1) { + this.notificationsService.success(null, this.translate.get('mydspace.upload.upload-multiple-successful', {qty: workspaceitems.length})); + } + + } else { + this.notificationsService.error(null, this.translate.get('mydspace.upload.upload-failed')); + } + } + + /** + * Method called on file upload error + */ + public onUploadError() { + this.notificationsService.error(null, this.translate.get('mydspace.upload.upload-failed')); + } + + /** + * Unsubscribe from the subscription + */ + ngOnDestroy(): void { + if (hasValue(this.sub)) { + this.sub.unsubscribe(); + } + } +} diff --git a/src/app/+my-dspace-page/my-dspace-page-routing.module.ts b/src/app/+my-dspace-page/my-dspace-page-routing.module.ts new file mode 100644 index 0000000000..d70a007e3a --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-page-routing.module.ts @@ -0,0 +1,25 @@ +import { NgModule } from '@angular/core'; +import { RouterModule } from '@angular/router'; + +import { MyDSpacePageComponent } from './my-dspace-page.component'; +import { MyDSpaceGuard } from './my-dspace.guard'; + +@NgModule({ + imports: [ + RouterModule.forChild([ + { + path: '', + component: MyDSpacePageComponent, + data: { title: 'mydspace.title' }, + canActivate: [ + MyDSpaceGuard + ] + } + ]) + ] +}) +/** + * This module defines the default component to load when navigating to the mydspace page path. + */ +export class MyDspacePageRoutingModule { +} diff --git a/src/app/+my-dspace-page/my-dspace-page.component.html b/src/app/+my-dspace-page/my-dspace-page.component.html new file mode 100644 index 0000000000..79fad17b26 --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-page.component.html @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + + + {{"search.sidebar.open" + | translate}} + + + + + + + + + diff --git a/src/app/+my-dspace-page/my-dspace-page.component.scss b/src/app/+my-dspace-page/my-dspace-page.component.scss new file mode 100644 index 0000000000..86c589bf66 --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-page.component.scss @@ -0,0 +1 @@ +@import '../+search-page/search-page.component.scss'; diff --git a/src/app/+my-dspace-page/my-dspace-page.component.spec.ts b/src/app/+my-dspace-page/my-dspace-page.component.spec.ts new file mode 100644 index 0000000000..2e2195fff8 --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-page.component.spec.ts @@ -0,0 +1,194 @@ +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; +import { ActivatedRoute } from '@angular/router'; +import { By } from '@angular/platform-browser'; +import { NgbCollapseModule } from '@ng-bootstrap/ng-bootstrap'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { RouterTestingModule } from '@angular/router/testing'; + +import { Store } from '@ngrx/store'; +import { TranslateModule } from '@ngx-translate/core'; +import { cold } from 'jasmine-marbles'; +import { of as observableOf } from 'rxjs'; + +import { SortDirection, SortOptions } from '../core/cache/models/sort-options.model'; +import { CommunityDataService } from '../core/data/community-data.service'; +import { HostWindowService } from '../shared/host-window.service'; +import { PaginationComponentOptions } from '../shared/pagination/pagination-component-options.model'; +import { RemoteData } from '../core/data/remote-data'; +import { MyDSpacePageComponent, SEARCH_CONFIG_SERVICE } from './my-dspace-page.component'; +import { RouteService } from '../shared/services/route.service'; +import { routeServiceStub } from '../shared/testing/route-service-stub'; +import { SearchConfigurationServiceStub } from '../shared/testing/search-configuration-service-stub'; +import { SearchService } from '../+search-page/search-service/search.service'; +import { SearchConfigurationService } from '../+search-page/search-service/search-configuration.service'; +import { PaginatedSearchOptions } from '../+search-page/paginated-search-options.model'; +import { SearchSidebarService } from '../+search-page/search-sidebar/search-sidebar.service'; +import { SearchFilterService } from '../+search-page/search-filters/search-filter/search-filter.service'; +import { RoleDirective } from '../shared/roles/role.directive'; +import { RoleService } from '../core/roles/role.service'; +import { MockRoleService } from '../shared/mocks/mock-role-service'; + +describe('MyDSpacePageComponent', () => { + let comp: MyDSpacePageComponent; + let fixture: ComponentFixture; + let searchServiceObject: SearchService; + let searchConfigurationServiceObject: SearchConfigurationService; + const store: Store = jasmine.createSpyObj('store', { + /* tslint:disable:no-empty */ + dispatch: {}, + /* tslint:enable:no-empty */ + select: observableOf(true) + }); + const pagination: PaginationComponentOptions = new PaginationComponentOptions(); + pagination.id = 'mydspace-results-pagination'; + pagination.currentPage = 1; + pagination.pageSize = 10; + const sort: SortOptions = new SortOptions('score', SortDirection.DESC); + const mockResults = observableOf(new RemoteData(false, false, true, null, ['test', 'data'])); + const searchServiceStub = jasmine.createSpyObj('SearchService', { + search: mockResults, + getSearchLink: '/mydspace', + getScopes: observableOf(['test-scope']), + setServiceOptions: {} + }); + const configurationParam = 'default'; + const queryParam = 'test query'; + const scopeParam = '7669c72a-3f2a-451f-a3b9-9210e7a4c02f'; + const paginatedSearchOptions = new PaginatedSearchOptions({ + configuration: configurationParam, + query: queryParam, + scope: scopeParam, + pagination, + sort + }); + const activatedRouteStub = { + snapshot: { + queryParamMap: new Map([ + ['query', queryParam], + ['scope', scopeParam] + ]) + }, + queryParams: observableOf({ + query: queryParam, + scope: scopeParam + }) + }; + const sidebarService = { + isCollapsed: observableOf(true), + collapse: () => this.isCollapsed = observableOf(true), + expand: () => this.isCollapsed = observableOf(false) + }; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [TranslateModule.forRoot(), RouterTestingModule.withRoutes([]), NoopAnimationsModule, NgbCollapseModule.forRoot()], + declarations: [MyDSpacePageComponent, RoleDirective], + providers: [ + { provide: SearchService, useValue: searchServiceStub }, + { + provide: CommunityDataService, + useValue: jasmine.createSpyObj('communityService', ['findById', 'findAll']) + }, + { provide: ActivatedRoute, useValue: activatedRouteStub }, + { provide: RouteService, useValue: routeServiceStub }, + { + provide: Store, useValue: store + }, + { + provide: HostWindowService, useValue: jasmine.createSpyObj('hostWindowService', + { + isXs: observableOf(true), + isSm: observableOf(false), + isXsOrSm: observableOf(true) + }) + }, + { + provide: SearchSidebarService, + useValue: sidebarService + }, + { + provide: SearchFilterService, + useValue: {} + }, { + provide: SEARCH_CONFIG_SERVICE, + useValue: new SearchConfigurationServiceStub() + }, + { + provide: RoleService, + useValue: new MockRoleService() + } + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(MyDSpacePageComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(MyDSpacePageComponent); + comp = fixture.componentInstance; // SearchPageComponent test instance + fixture.detectChanges(); + searchServiceObject = (comp as any).service; + searchConfigurationServiceObject = (comp as any).searchConfigService; + }); + + afterEach(() => { + comp = null; + searchServiceObject = null; + searchConfigurationServiceObject = null; + }); + + it('should get the scope and query from the route parameters', () => { + + searchConfigurationServiceObject.paginatedSearchOptions.next(paginatedSearchOptions); + expect(comp.searchOptions$).toBeObservable(cold('b', { + b: paginatedSearchOptions + })); + + }); + + describe('when the open sidebar button is clicked in mobile view', () => { + + beforeEach(() => { + spyOn(comp, 'openSidebar'); + const openSidebarButton = fixture.debugElement.query(By.css('.open-sidebar')); + openSidebarButton.triggerEventHandler('click', null); + }); + + it('should trigger the openSidebar function', () => { + expect(comp.openSidebar).toHaveBeenCalled(); + }); + + }); + + describe('when sidebarCollapsed is true in mobile view', () => { + let menu: HTMLElement; + + beforeEach(() => { + menu = fixture.debugElement.query(By.css('#search-sidebar-sm')).nativeElement; + comp.isSidebarCollapsed = () => observableOf(true); + fixture.detectChanges(); + }); + + it('should close the sidebar', () => { + expect(menu.classList).not.toContain('active'); + }); + + }); + + describe('when sidebarCollapsed is false in mobile view', () => { + let menu: HTMLElement; + + beforeEach(() => { + menu = fixture.debugElement.query(By.css('#search-sidebar-sm')).nativeElement; + comp.isSidebarCollapsed = () => observableOf(false); + fixture.detectChanges(); + }); + + it('should open the menu', () => { + expect(menu.classList).toContain('active'); + }); + + }); +}); diff --git a/src/app/+my-dspace-page/my-dspace-page.component.ts b/src/app/+my-dspace-page/my-dspace-page.component.ts new file mode 100644 index 0000000000..9c5132727c --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-page.component.ts @@ -0,0 +1,156 @@ +import { ChangeDetectionStrategy, Component, Inject, InjectionToken, OnInit } from '@angular/core'; + +import { BehaviorSubject, Observable, Subscription } from 'rxjs'; +import { switchMap, tap, } from 'rxjs/operators'; + +import { PaginatedList } from '../core/data/paginated-list'; +import { RemoteData } from '../core/data/remote-data'; +import { DSpaceObject } from '../core/shared/dspace-object.model'; +import { pushInOut } from '../shared/animations/push'; +import { HostWindowService } from '../shared/host-window.service'; +import { PaginatedSearchOptions } from '../+search-page/paginated-search-options.model'; +import { SearchService } from '../+search-page/search-service/search.service'; +import { SearchSidebarService } from '../+search-page/search-sidebar/search-sidebar.service'; +import { hasValue } from '../shared/empty.util'; +import { getSucceededRemoteData } from '../core/shared/operators'; +import { MyDSpaceResult } from './my-dspace-result.model'; +import { MyDSpaceResponseParsingService } from '../core/data/mydspace-response-parsing.service'; +import { SearchConfigurationOption } from '../+search-page/search-switch-configuration/search-configuration-option.model'; +import { RoleType } from '../core/roles/role-types'; +import { SearchConfigurationService } from '../+search-page/search-service/search-configuration.service'; +import { MyDSpaceConfigurationService } from './my-dspace-configuration.service'; +import { ViewMode } from '../core/shared/view-mode.model'; +import { MyDSpaceRequest } from '../core/data/request.models'; + +export const MYDSPACE_ROUTE = '/mydspace'; +export const SEARCH_CONFIG_SERVICE: InjectionToken = new InjectionToken('searchConfigurationService'); + +/** + * This component represents the whole mydspace page + */ +@Component({ + selector: 'ds-my-dspace-page', + styleUrls: ['./my-dspace-page.component.scss'], + templateUrl: './my-dspace-page.component.html', + changeDetection: ChangeDetectionStrategy.OnPush, + animations: [pushInOut], + providers: [ + { + provide: SEARCH_CONFIG_SERVICE, + useClass: MyDSpaceConfigurationService + } + ] +}) +export class MyDSpacePageComponent implements OnInit { + + /** + * The list of available configuration options + */ + configurationList$: Observable; + + /** + * The current search results + */ + resultsRD$: BehaviorSubject>>> = new BehaviorSubject(null); + + /** + * The current paginated search options + */ + searchOptions$: Observable; + + /** + * The current relevant scopes + */ + scopeListRD$: Observable; + + /** + * Emits true if were on a small screen + */ + isXsOrSm$: Observable; + + /** + * Subscription to unsubscribe from + */ + sub: Subscription; + + /** + * Variable for enumeration RoleType + */ + roleTypeEnum = RoleType; + + /** + * List of available view mode + */ + viewModeList = [ViewMode.List, ViewMode.Detail]; + + constructor(private service: SearchService, + private sidebarService: SearchSidebarService, + private windowService: HostWindowService, + @Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: MyDSpaceConfigurationService) { + this.isXsOrSm$ = this.windowService.isXsOrSm(); + this.service.setServiceOptions(MyDSpaceResponseParsingService, MyDSpaceRequest); + } + + /** + * Initialize available configuration list + * + * Listening to changes in the paginated search options + * If something changes, update the search results + * + * Listen to changes in the scope + * If something changes, update the list of scopes for the dropdown + */ + ngOnInit(): void { + this.configurationList$ = this.searchConfigService.getAvailableConfigurationOptions(); + this.searchOptions$ = this.searchConfigService.paginatedSearchOptions; + + this.sub = this.searchOptions$.pipe( + tap(() => this.resultsRD$.next(null)), + switchMap((options: PaginatedSearchOptions) => this.service.search(options).pipe(getSucceededRemoteData()))) + .subscribe((results) => { + this.resultsRD$.next(results); + }); + this.scopeListRD$ = this.searchConfigService.getCurrentScope('').pipe( + switchMap((scopeId) => this.service.getScopes(scopeId)) + ); + + } + + /** + * Set the sidebar to a collapsed state + */ + public closeSidebar(): void { + this.sidebarService.collapse() + } + + /** + * Set the sidebar to an expanded state + */ + public openSidebar(): void { + this.sidebarService.expand(); + } + + /** + * Check if the sidebar is collapsed + * @returns {Observable} emits true if the sidebar is currently collapsed, false if it is expanded + */ + public isSidebarCollapsed(): Observable { + return this.sidebarService.isCollapsed; + } + + /** + * @returns {string} The base path to the search page + */ + public getSearchLink(): string { + return this.service.getSearchLink(); + } + + /** + * Unsubscribe from the subscription + */ + ngOnDestroy(): void { + if (hasValue(this.sub)) { + this.sub.unsubscribe(); + } + } +} diff --git a/src/app/+my-dspace-page/my-dspace-page.module.ts b/src/app/+my-dspace-page/my-dspace-page.module.ts new file mode 100644 index 0000000000..4b8cf37b7a --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-page.module.ts @@ -0,0 +1,69 @@ +import { CommonModule } from '@angular/common'; +import { NgModule } from '@angular/core'; + +import { SharedModule } from '../shared/shared.module'; + +import { MyDspacePageRoutingModule } from './my-dspace-page-routing.module'; +import { MyDSpacePageComponent } from './my-dspace-page.component'; +import { SearchPageModule } from '../+search-page/search-page.module'; +import { MyDSpaceResultsComponent } from './my-dspace-results/my-dspace-results.component'; +import { WorkspaceitemMyDSpaceResultListElementComponent } from '../shared/object-list/my-dspace-result-list-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-list-element.component'; +import { ItemMyDSpaceResultListElementComponent } from '../shared/object-list/my-dspace-result-list-element/item-my-dspace-result/item-my-dspace-result-list-element.component'; +import { WorkflowitemMyDSpaceResultListElementComponent } from '../shared/object-list/my-dspace-result-list-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-list-element.component'; +import { ClaimedMyDSpaceResultListElementComponent } from '../shared/object-list/my-dspace-result-list-element/claimed-my-dspace-result/claimed-my-dspace-result-list-element.component'; +import { PoolMyDSpaceResultListElementComponent } from '../shared/object-list/my-dspace-result-list-element/pool-my-dspace-result/pool-my-dspace-result-list-element.component'; +import { MyDSpaceNewSubmissionComponent } from './my-dspace-new-submission/my-dspace-new-submission.component'; +import { ItemMyDSpaceResultDetailElementComponent } from '../shared/object-detail/my-dspace-result-detail-element/item-my-dspace-result/item-my-dspace-result-detail-element.component'; +import { WorkspaceitemMyDSpaceResultDetailElementComponent } from '../shared/object-detail/my-dspace-result-detail-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-detail-element.component'; +import { WorkflowitemMyDSpaceResultDetailElementComponent } from '../shared/object-detail/my-dspace-result-detail-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-detail-element.component'; +import { ClaimedMyDSpaceResultDetailElementComponent } from '../shared/object-detail/my-dspace-result-detail-element/claimed-my-dspace-result/claimed-my-dspace-result-detail-element.component'; +import { PoolMyDSpaceResultDetailElementComponent } from '../shared/object-detail/my-dspace-result-detail-element/pool-my-dspace-result/pool-my-dspace-result-detail-lement.component'; +import { MyDSpaceGuard } from './my-dspace.guard'; +import { MyDSpaceConfigurationService } from './my-dspace-configuration.service'; + +@NgModule({ + imports: [ + CommonModule, + SharedModule, + MyDspacePageRoutingModule, + SearchPageModule + ], + declarations: [ + MyDSpacePageComponent, + MyDSpaceResultsComponent, + ItemMyDSpaceResultListElementComponent, + WorkspaceitemMyDSpaceResultListElementComponent, + WorkflowitemMyDSpaceResultListElementComponent, + ClaimedMyDSpaceResultListElementComponent, + PoolMyDSpaceResultListElementComponent, + ItemMyDSpaceResultDetailElementComponent, + WorkspaceitemMyDSpaceResultDetailElementComponent, + WorkflowitemMyDSpaceResultDetailElementComponent, + ClaimedMyDSpaceResultDetailElementComponent, + PoolMyDSpaceResultDetailElementComponent, + MyDSpaceNewSubmissionComponent + ], + providers: [ + MyDSpaceGuard, + MyDSpaceConfigurationService + ], + entryComponents: [ + ItemMyDSpaceResultListElementComponent, + WorkspaceitemMyDSpaceResultListElementComponent, + WorkflowitemMyDSpaceResultListElementComponent, + ClaimedMyDSpaceResultListElementComponent, + PoolMyDSpaceResultListElementComponent, + ItemMyDSpaceResultDetailElementComponent, + WorkspaceitemMyDSpaceResultDetailElementComponent, + WorkflowitemMyDSpaceResultDetailElementComponent, + ClaimedMyDSpaceResultDetailElementComponent, + PoolMyDSpaceResultDetailElementComponent + ] +}) + +/** + * This module handles all components that are necessary for the mydspace page + */ +export class MyDSpacePageModule { + +} diff --git a/src/app/+my-dspace-page/my-dspace-result.model.ts b/src/app/+my-dspace-page/my-dspace-result.model.ts new file mode 100644 index 0000000000..d300ed0bc8 --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-result.model.ts @@ -0,0 +1,19 @@ +import { DSpaceObject } from '../core/shared/dspace-object.model'; +import { MetadataMap } from '../core/shared/metadata.models'; +import { ListableObject } from '../shared/object-collection/shared/listable-object.model'; + +/** + * Represents a search result object of a certain () DSpaceObject + */ +export class MyDSpaceResult implements ListableObject { + /** + * The DSpaceObject that was found + */ + indexableObject: T; + + /** + * The metadata that was used to find this item, hithighlighted + */ + hitHighlights: MetadataMap; + +} diff --git a/src/app/+my-dspace-page/my-dspace-results/my-dspace-results.component.html b/src/app/+my-dspace-page/my-dspace-results/my-dspace-results.component.html new file mode 100644 index 0000000000..132a0d2204 --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-results/my-dspace-results.component.html @@ -0,0 +1,12 @@ + 0" @fadeIn> + + + + + +{{'mydspace.results.no-results' | translate}} diff --git a/src/app/+my-dspace-page/my-dspace-results/my-dspace-results.component.spec.ts b/src/app/+my-dspace-page/my-dspace-results/my-dspace-results.component.spec.ts new file mode 100644 index 0000000000..67625706a6 --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-results/my-dspace-results.component.spec.ts @@ -0,0 +1,58 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { By } from '@angular/platform-browser'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; +import { NO_ERRORS_SCHEMA } from '@angular/core'; + +import { TranslateModule } from '@ngx-translate/core'; +import { QueryParamsDirectiveStub } from '../../shared/testing/query-params-directive-stub'; +import { MyDSpaceResultsComponent } from './my-dspace-results.component'; + +describe('MyDSpaceResultsComponent', () => { + let comp: MyDSpaceResultsComponent; + let fixture: ComponentFixture; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [TranslateModule.forRoot(), NoopAnimationsModule], + declarations: [ + MyDSpaceResultsComponent, + QueryParamsDirectiveStub], + schemas: [NO_ERRORS_SCHEMA] + }).compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(MyDSpaceResultsComponent); + comp = fixture.componentInstance; // MyDSpaceResultsComponent test instance + }); + + it('should display results when results are not empty', () => { + (comp as any).searchResults = { hasSucceeded: true, isLoading: false, payload: { page: { length: 2 } } }; + (comp as any).searchConfig = {}; + fixture.detectChanges(); + expect(fixture.debugElement.query(By.css('ds-viewable-collection'))).not.toBeNull(); + }); + + it('should not display link when results are not empty', () => { + (comp as any).searchResults = { hasSucceeded: true, isLoading: false, payload: { page: { length: 2 } } }; + (comp as any).searchConfig = {}; + fixture.detectChanges(); + expect(fixture.debugElement.query(By.css('a'))).toBeNull(); + }); + + it('should display error message if error is != 400', () => { + (comp as any).searchResults = { hasFailed: true, error: { statusCode: 500 } }; + fixture.detectChanges(); + expect(fixture.debugElement.query(By.css('ds-error'))).not.toBeNull(); + }); + + it('should display a message if search result is empty', () => { + (comp as any).searchResults = { payload: { page: { length: 0 } } }; + (comp as any).searchConfig = { query: 'foobar' }; + fixture.detectChanges(); + + const linkDes = fixture.debugElement.queryAll(By.css('text-muted')); + + expect(linkDes).toBeDefined() + }); +}); diff --git a/src/app/+my-dspace-page/my-dspace-results/my-dspace-results.component.ts b/src/app/+my-dspace-page/my-dspace-results/my-dspace-results.component.ts new file mode 100644 index 0000000000..3a16def9c1 --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace-results/my-dspace-results.component.ts @@ -0,0 +1,51 @@ +import { Component, Input } from '@angular/core'; + +import { RemoteData } from '../../core/data/remote-data'; +import { DSpaceObject } from '../../core/shared/dspace-object.model'; +import { fadeIn, fadeInOut } from '../../shared/animations/fade'; +import { MyDSpaceResult } from '../my-dspace-result.model'; +import { SearchOptions } from '../../+search-page/search-options.model'; +import { PaginatedList } from '../../core/data/paginated-list'; +import { ViewMode } from '../../core/shared/view-mode.model'; +import { isEmpty } from '../../shared/empty.util'; + +/** + * Component that represents all results for mydspace page + */ +@Component({ + selector: 'ds-my-dspace-results', + templateUrl: './my-dspace-results.component.html', + animations: [ + fadeIn, + fadeInOut + ] +}) +export class MyDSpaceResultsComponent { + + /** + * The actual search result objects + */ + @Input() searchResults: RemoteData>>; + + /** + * The current configuration of the search + */ + @Input() searchConfig: SearchOptions; + + /** + * The current view mode for the search results + */ + @Input() viewMode: ViewMode; + + /** + * A boolean representing if search results entry are separated by a line + */ + hasBorder = true; + + /** + * Check if mydspace search results are loading + */ + isLoading() { + return !this.searchResults || isEmpty(this.searchResults) || this.searchResults.isLoading; + } +} diff --git a/src/app/+my-dspace-page/my-dspace.guard.ts b/src/app/+my-dspace-page/my-dspace.guard.ts new file mode 100644 index 0000000000..9cb9aff485 --- /dev/null +++ b/src/app/+my-dspace-page/my-dspace.guard.ts @@ -0,0 +1,57 @@ +import { Injectable } from '@angular/core'; +import { ActivatedRouteSnapshot, CanActivate, NavigationExtras, Router, RouterStateSnapshot } from '@angular/router'; + +import { Observable } from 'rxjs'; +import { first, map } from 'rxjs/operators'; +import { isEmpty } from '../shared/empty.util'; +import { MYDSPACE_ROUTE } from './my-dspace-page.component'; +import { MyDSpaceConfigurationValueType } from './my-dspace-configuration-value-type'; +import { MyDSpaceConfigurationService } from './my-dspace-configuration.service'; + +/** + * Prevent unauthorized activating and loading of mydspace configuration + * @class MyDSpaceGuard + */ +@Injectable() +export class MyDSpaceGuard implements CanActivate { + + /** + * @constructor + */ + constructor(private configurationService: MyDSpaceConfigurationService, private router: Router) { + } + + /** + * True when configuration is valid + * @method canActivate + */ + canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + return this.configurationService.getAvailableConfigurationTypes().pipe( + first(), + map((configurationList) => this.validateConfigurationParam(route.queryParamMap.get('configuration'), configurationList))); + } + + /** + * Check if the given configuration is present in the list of those available + * + * @param configuration + * the configuration to validate + * @param configurationList + * the list of available configuration + * + */ + private validateConfigurationParam(configuration: string, configurationList: MyDSpaceConfigurationValueType[]): boolean { + const configurationDefault: string = configurationList[0]; + if (isEmpty(configuration) || !configurationList.includes(configuration as MyDSpaceConfigurationValueType)) { + // If configuration param is empty or is not included in available configurations redirect to a default configuration value + const navigationExtras: NavigationExtras = { + queryParams: {configuration: configurationDefault} + }; + + this.router.navigate([MYDSPACE_ROUTE], navigationExtras); + return false; + } else { + return true; + } + } +} diff --git a/src/app/+search-page/filtered-search-page.component.ts b/src/app/+search-page/filtered-search-page.component.ts index da5920cd6d..05b1caf1dc 100644 --- a/src/app/+search-page/filtered-search-page.component.ts +++ b/src/app/+search-page/filtered-search-page.component.ts @@ -32,7 +32,7 @@ export class FilteredSearchPageComponent extends SearchPageComponent { constructor(protected service: SearchService, protected sidebarService: SearchSidebarService, protected windowService: HostWindowService, - protected searchConfigService: SearchConfigurationService, + public searchConfigService: SearchConfigurationService, protected routeService: RouteService) { super(service, sidebarService, windowService, searchConfigService, routeService); } diff --git a/src/app/+search-page/normalized-search-result.model.ts b/src/app/+search-page/normalized-search-result.model.ts index 46f14c042d..32f3217b54 100644 --- a/src/app/+search-page/normalized-search-result.model.ts +++ b/src/app/+search-page/normalized-search-result.model.ts @@ -1,4 +1,4 @@ -import { autoserialize } from 'cerialize'; +import { autoserialize, autoserializeAs } from 'cerialize'; import { MetadataMap } from '../core/shared/metadata.models'; import { ListableObject } from '../shared/object-collection/shared/listable-object.model'; @@ -10,7 +10,7 @@ export class NormalizedSearchResult implements ListableObject { * The UUID of the DSpaceObject that was found */ @autoserialize - dspaceObject: string; + indexableObject: string; /** * The metadata that was used to find this item, hithighlighted diff --git a/src/app/+search-page/paginated-search-options.model.ts b/src/app/+search-page/paginated-search-options.model.ts index 387c116a56..45cd0b8f09 100644 --- a/src/app/+search-page/paginated-search-options.model.ts +++ b/src/app/+search-page/paginated-search-options.model.ts @@ -12,7 +12,7 @@ export class PaginatedSearchOptions extends SearchOptions { pagination?: PaginationComponentOptions; sort?: SortOptions; - constructor(options: {scope?: string, query?: string, dsoType?: DSpaceObjectType, filters?: SearchFilter[], fixedFilter?: any, pagination?: PaginationComponentOptions, sort?: SortOptions}) { + constructor(options: {configuration?: string, scope?: string, query?: string, dsoType?: DSpaceObjectType, filters?: SearchFilter[], fixedFilter?: any, pagination?: PaginationComponentOptions, sort?: SortOptions}) { super(options); this.pagination = options.pagination; this.sort = options.sort; diff --git a/src/app/+search-page/search-filters/search-filter/search-authority-filter/search-authority-filter.component.html b/src/app/+search-page/search-filters/search-filter/search-authority-filter/search-authority-filter.component.html new file mode 100644 index 0000000000..6958c422e1 --- /dev/null +++ b/src/app/+search-page/search-filters/search-filter/search-authority-filter/search-authority-filter.component.html @@ -0,0 +1,27 @@ + + + + + + + + + + {{"search.filters.filter.show-more" + | translate}} + 1" + (click)="showFirstPageOnly()">{{"search.filters.filter.show-less" + | translate}} + + + + diff --git a/src/app/+search-page/search-filters/search-filter/search-authority-filter/search-authority-filter.component.scss b/src/app/+search-page/search-filters/search-filter/search-authority-filter/search-authority-filter.component.scss new file mode 100644 index 0000000000..33e354f2d8 --- /dev/null +++ b/src/app/+search-page/search-filters/search-filter/search-authority-filter/search-authority-filter.component.scss @@ -0,0 +1,23 @@ +@import '../../../../../styles/variables.scss'; +@import '../../../../../styles/mixins.scss'; + +.filters { + a { + color: $body-color; + &:hover, &focus { + text-decoration: none; + } + span.badge { + vertical-align: text-top; + } + } + .toggle-more-filters a { + color: $link-color; + text-decoration: underline; + cursor: pointer; + } +} +::ng-deep em { + font-weight: bold; + font-style: normal; +} diff --git a/src/app/+search-page/search-filters/search-filter/search-authority-filter/search-authority-filter.component.ts b/src/app/+search-page/search-filters/search-filter/search-authority-filter/search-authority-filter.component.ts new file mode 100644 index 0000000000..eaa73aba26 --- /dev/null +++ b/src/app/+search-page/search-filters/search-filter/search-authority-filter/search-authority-filter.component.ts @@ -0,0 +1,37 @@ +import { Component, OnInit } from '@angular/core'; + +import { FilterType } from '../../../search-service/filter-type.model'; +import { facetLoad, SearchFacetFilterComponent } from '../search-facet-filter/search-facet-filter.component'; +import { renderFacetFor } from '../search-filter-type-decorator'; +import { FacetValue } from '../../../search-service/facet-value.model'; + +@Component({ + selector: 'ds-search-authority-filter', + styleUrls: ['./search-authority-filter.component.scss'], + templateUrl: './search-authority-filter.component.html', + animations: [facetLoad] +}) + +/** + * Component that represents an authority facet for a specific filter configuration + */ +@renderFacetFor(FilterType.authority) +export class SearchAuthorityFilterComponent extends SearchFacetFilterComponent implements OnInit { + + /** + * TODO to review after https://github.com/DSpace/dspace-angular/issues/368 is resolved + * Retrieve facet value from search link + */ + protected getFacetValue(facet: FacetValue): string { + const search = facet.search; + const hashes = search.slice(search.indexOf('?') + 1).split('&'); + const params = {}; + hashes.map((hash) => { + const [key, val] = hash.split('='); + params[key] = decodeURIComponent(val) + }); + + return params[this.filterConfig.paramName]; + } + +} diff --git a/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.spec.ts b/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.spec.ts index f1dbedfb40..245c0e3ddb 100644 --- a/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.spec.ts +++ b/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.spec.ts @@ -19,10 +19,12 @@ import { By } from '@angular/platform-browser'; describe('SearchFacetOptionComponent', () => { let comp: SearchFacetOptionComponent; let fixture: ComponentFixture; - const filterName1 = 'test name'; + const filterName1 = 'testname'; + const filterName2 = 'testAuthorityname'; const value1 = 'testvalue1'; const value2 = 'test2'; - const value3 = 'another value3'; + const operator = 'authority'; + const mockFilterConfig = Object.assign(new SearchFilterConfig(), { name: filterName1, type: FilterType.range, @@ -32,14 +34,38 @@ describe('SearchFacetOptionComponent', () => { minValue: 200, maxValue: 3000, }); + + const mockAuthorityFilterConfig = Object.assign(new SearchFilterConfig(), { + name: filterName2, + type: FilterType.authority, + hasFacets: false, + isOpenByDefault: false, + pageSize: 2 + }); + const value: FacetValue = { - value: value2, - count: 20, - search: '' - }; + label: value2, + value: value2, + count: 20, + search: `` + }; + + const selectedValue: FacetValue = { + label: value1, + value: value1, + count: 20, + search: `http://test.org/api/discover/search/objects?f.${filterName1}=${value1},${operator}` + }; + + const authorityValue: FacetValue = { + label: value2, + value: value2, + count: 20, + search: `http://test.org/api/discover/search/objects?f.${filterName2}=${value2},${operator}` + }; const searchLink = '/search'; - const selectedValues = [value1]; + const selectedValues = [selectedValue]; const selectedValues$ = observableOf(selectedValues); let filterService; let searchService; @@ -90,7 +116,7 @@ describe('SearchFacetOptionComponent', () => { fixture.detectChanges(); }); - describe('when the updateAddParams method is called wih a value', () => { + describe('when the updateAddParams method is called with a value', () => { it('should update the addQueryParams with the new parameter values', () => { comp.addQueryParams = {}; (comp as any).updateAddParams(selectedValues); @@ -101,6 +127,21 @@ describe('SearchFacetOptionComponent', () => { }); }); + describe('when filter type is authority and the updateAddParams method is called with a value', () => { + it('should update the addQueryParams with the new parameter values', () => { + comp.filterValue = authorityValue; + comp.filterConfig = mockAuthorityFilterConfig; + fixture.detectChanges(); + + comp.addQueryParams = {}; + (comp as any).updateAddParams(selectedValues); + expect(comp.addQueryParams).toEqual({ + [mockAuthorityFilterConfig.paramName]: [value1, `${value2},${operator}`], + page: 1 + }); + }); + }); + describe('when isVisible emits true', () => { it('the facet option should be visible', () => { comp.isVisible = observableOf(true); diff --git a/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.ts b/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.ts index 016ebf62a3..8238cd14cc 100644 --- a/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.ts +++ b/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component.ts @@ -1,5 +1,5 @@ import { combineLatest as observableCombineLatest, Observable, Subscription } from 'rxjs'; -import { map, take } from 'rxjs/operators'; +import { map } from 'rxjs/operators'; import { Component, Input, OnDestroy, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { FacetValue } from '../../../../search-service/facet-value.model'; @@ -8,6 +8,7 @@ import { SearchService } from '../../../../search-service/search.service'; import { SearchFilterService } from '../../search-filter.service'; import { SearchConfigurationService } from '../../../../search-service/search-configuration.service'; import { hasValue } from '../../../../../shared/empty.util'; +import { FilterType } from '../../../../search-service/filter-type.model'; @Component({ selector: 'ds-search-facet-option', @@ -32,7 +33,7 @@ export class SearchFacetOptionComponent implements OnInit, OnDestroy { /** * Emits the active values for this filter */ - @Input() selectedValues$: Observable; + @Input() selectedValues$: Observable; /** * Emits true when this option should be visible and false when it should be invisible @@ -71,7 +72,7 @@ export class SearchFacetOptionComponent implements OnInit, OnDestroy { * Checks if a value for this filter is currently active */ private isChecked(): Observable { - return this.filterService.isFilterActiveWithValue(this.filterConfig.paramName, this.filterValue.value); + return this.filterService.isFilterActiveWithValue(this.filterConfig.paramName, this.getFacetValue()); } /** @@ -85,13 +86,33 @@ export class SearchFacetOptionComponent implements OnInit, OnDestroy { * Calculates the parameters that should change if a given value for this filter would be added to the active filters * @param {string[]} selectedValues The values that are currently selected for this filter */ - private updateAddParams(selectedValues: string[]): void { + private updateAddParams(selectedValues: FacetValue[]): void { this.addQueryParams = { - [this.filterConfig.paramName]: [...selectedValues, this.filterValue.value], + [this.filterConfig.paramName]: [...selectedValues.map((facetValue: FacetValue) => facetValue.label), this.getFacetValue()], page: 1 }; } + /** + * TODO to review after https://github.com/DSpace/dspace-angular/issues/368 is resolved + * Retrieve facet value related to facet type + */ + private getFacetValue(): string { + if (this.filterConfig.type === FilterType.authority) { + const search = this.filterValue.search; + const hashes = search.slice(search.indexOf('?') + 1).split('&'); + const params = {}; + hashes.map((hash) => { + const [key, val] = hash.split('='); + params[key] = decodeURIComponent(val) + }); + + return params[this.filterConfig.paramName]; + } else { + return this.filterValue.value; + } + } + /** * Make sure the subscription is unsubscribed from when this component is destroyed */ diff --git a/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.html b/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.html index b485fe0fd0..8e8ad9b4e3 100644 --- a/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.html +++ b/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.html @@ -1,8 +1,8 @@ - {{filterValue.value}} + {{filterValue.label}} {{filterValue.count}} - \ No newline at end of file + diff --git a/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.spec.ts b/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.spec.ts index 218730263b..d3264214ed 100644 --- a/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.spec.ts +++ b/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component.spec.ts @@ -35,10 +35,11 @@ describe('SearchFacetRangeOptionComponent', () => { maxValue: 3000, }); const value: FacetValue = { - value: value2, - count: 20, - search: '' - }; + label: value2, + value: value2, + count: 20, + search: '' + }; const searchLink = '/search'; let filterService; @@ -92,10 +93,11 @@ describe('SearchFacetRangeOptionComponent', () => { it('should update the changeQueryParams with the new parameter values', () => { comp.changeQueryParams = {}; comp.filterValue = { - value: '50-60', - count: 20, - search: '' - }; + label: '50-60', + value: '50-60', + count: 20, + search: '' + }; (comp as any).updateChangeParams(); expect(comp.changeQueryParams).toEqual({ [mockFilterConfig.paramName + RANGE_FILTER_MIN_SUFFIX]: ['50'], diff --git a/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.html b/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.html index ba43bae100..5657bd224e 100644 --- a/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.html +++ b/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.html @@ -2,5 +2,5 @@ [routerLink]="[getSearchLink()]" [queryParams]="removeQueryParams" queryParamsHandling="merge"> - {{selectedValue}} - \ No newline at end of file + {{selectedValue.label}} + diff --git a/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.spec.ts b/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.spec.ts index 545ba1d66b..01defb9893 100644 --- a/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.spec.ts +++ b/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.spec.ts @@ -13,13 +13,18 @@ import { RouterStub } from '../../../../../shared/testing/router-stub'; import { SearchConfigurationService } from '../../../../search-service/search-configuration.service'; import { SearchFilterService } from '../../search-filter.service'; import { SearchFacetSelectedOptionComponent } from './search-facet-selected-option.component'; +import { FacetValue } from '../../../../search-service/facet-value.model'; describe('SearchFacetSelectedOptionComponent', () => { let comp: SearchFacetSelectedOptionComponent; let fixture: ComponentFixture; const filterName1 = 'test name'; + const filterName2 = 'testAuthorityname'; + const label1 = 'test value 1'; const value1 = 'testvalue1'; + const label2 = 'test 2'; const value2 = 'test2'; + const operator = 'authority'; const mockFilterConfig = Object.assign(new SearchFilterConfig(), { name: filterName1, type: FilterType.range, @@ -29,10 +34,55 @@ describe('SearchFacetSelectedOptionComponent', () => { minValue: 200, maxValue: 3000, }); + const mockAuthorityFilterConfig = Object.assign(new SearchFilterConfig(), { + name: filterName2, + type: FilterType.authority, + hasFacets: false, + isOpenByDefault: false, + pageSize: 2 + }); const searchLink = '/search'; - const selectedValues = [value1, value2]; + const selectedValue: FacetValue = { + label: value1, + value: value1, + count: 20, + search: `http://test.org/api/discover/search/objects?f.${filterName1}=${value1}` + }; + const selectedValue2: FacetValue = { + label: value2, + value: value2, + count: 20, + search: `http://test.org/api/discover/search/objects?f.${filterName1}=${value2}` + }; + const selectedAuthorityValue: FacetValue = { + label: label1, + value: value1, + count: 20, + search: `http://test.org/api/discover/search/objects?f.${filterName2}=${value1},${operator}` + }; + const selectedAuthorityValue2: FacetValue = { + label: label2, + value: value2, + count: 20, + search: `http://test.org/api/discover/search/objects?f.${filterName2}=${value2},${operator}` + }; + const selectedValues = [selectedValue, selectedValue2]; + const selectedAuthorityValues = [selectedAuthorityValue, selectedAuthorityValue2]; + const facetValue = { + label: value2, + value: value2, + count: 1, + search: '' + }; + const authorityValue: FacetValue = { + label: label2, + value: value2, + count: 20, + search: `http://test.org/api/discover/search/objects?f.${filterName2}=${value2},${operator}` + }; const selectedValues$ = observableOf(selectedValues); + const selectedAuthorityValues$ = observableOf(selectedAuthorityValues); let filterService; let searchService; let router; @@ -76,7 +126,7 @@ describe('SearchFacetSelectedOptionComponent', () => { filterService = (comp as any).filterService; searchService = (comp as any).searchService; router = (comp as any).router; - comp.selectedValue = value2; + comp.selectedValue = facetValue; comp.selectedValues$ = selectedValues$; comp.filterConfig = mockFilterConfig; fixture.detectChanges(); @@ -92,4 +142,20 @@ describe('SearchFacetSelectedOptionComponent', () => { }); }); }); + + describe('when filter type is authority and the updateRemoveParams method is called with a value', () => { + it('should update the removeQueryParams with the new parameter values', () => { + spyOn(filterService, 'getSelectedValuesForFilter').and.returnValue(selectedAuthorityValues); + comp.selectedValue = authorityValue; + comp.selectedValues$ = selectedAuthorityValues$; + comp.filterConfig = mockAuthorityFilterConfig; + comp.removeQueryParams = {}; + fixture.detectChanges(); + (comp as any).updateRemoveParams(selectedAuthorityValues); + expect(comp.removeQueryParams).toEqual({ + [mockAuthorityFilterConfig.paramName]: [`${value1},${operator}`], + page: 1 + }); + }); + }); }); diff --git a/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.ts b/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.ts index 23ad3eccba..fae4add1de 100644 --- a/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.ts +++ b/src/app/+search-page/search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component.ts @@ -6,6 +6,8 @@ import { SearchService } from '../../../../search-service/search.service'; import { SearchFilterService } from '../../search-filter.service'; import { hasValue } from '../../../../../shared/empty.util'; import { SearchConfigurationService } from '../../../../search-service/search-configuration.service'; +import { FacetValue } from '../../../../search-service/facet-value.model'; +import { FilterType } from '../../../../search-service/filter-type.model'; @Component({ selector: 'ds-search-facet-selected-option', @@ -20,7 +22,7 @@ export class SearchFacetSelectedOptionComponent implements OnInit, OnDestroy { /** * The value for this component */ - @Input() selectedValue: string; + @Input() selectedValue: FacetValue; /** * The filter configuration for this facet option @@ -30,7 +32,7 @@ export class SearchFacetSelectedOptionComponent implements OnInit, OnDestroy { /** * Emits the active values for this filter */ - @Input() selectedValues$: Observable; + @Input() selectedValues$: Observable; /** * UI parameters when this filter is removed @@ -70,13 +72,35 @@ export class SearchFacetSelectedOptionComponent implements OnInit, OnDestroy { * Calculates the parameters that should change if a given value for this filter would be removed from the active filters * @param {string[]} selectedValues The values that are currently selected for this filter */ - private updateRemoveParams(selectedValues: string[]): void { + private updateRemoveParams(selectedValues: FacetValue[]): void { this.removeQueryParams = { - [this.filterConfig.paramName]: selectedValues.filter((v) => v !== this.selectedValue), + [this.filterConfig.paramName]: selectedValues + .filter((facetValue: FacetValue) => facetValue.label !== this.selectedValue.label) + .map((facetValue: FacetValue) => this.getFacetValue(facetValue)), page: 1 }; } + /** + * TODO to review after https://github.com/DSpace/dspace-angular/issues/368 is resolved + * Retrieve facet value related to facet type + */ + private getFacetValue(facetValue: FacetValue): string { + if (this.filterConfig.type === FilterType.authority) { + const search = facetValue.search; + const hashes = search.slice(search.indexOf('?') + 1).split('&'); + const params = {}; + hashes.map((hash) => { + const [key, val] = hash.split('='); + params[key] = decodeURIComponent(val) + }); + + return params[this.filterConfig.paramName]; + } else { + return facetValue.value; + } + } + /** * Make sure the subscription is unsubscribed from when this component is destroyed */ diff --git a/src/app/+search-page/search-filters/search-filter/search-facet-filter/search-facet-filter.component.spec.ts b/src/app/+search-page/search-filters/search-filter/search-facet-filter/search-facet-filter.component.spec.ts index cb3d4730b4..adb2919653 100644 --- a/src/app/+search-page/search-filters/search-filter/search-facet-filter/search-facet-filter.component.spec.ts +++ b/src/app/+search-page/search-filters/search-filter/search-facet-filter/search-facet-filter.component.spec.ts @@ -17,7 +17,8 @@ import { Router } from '@angular/router'; import { PageInfo } from '../../../../core/shared/page-info.model'; import { SearchFacetFilterComponent } from './search-facet-filter.component'; import { RemoteDataBuildService } from '../../../../core/cache/builders/remote-data-build.service'; -import { SearchConfigurationService } from '../../../search-service/search-configuration.service'; +import { SearchConfigurationServiceStub } from '../../../../shared/testing/search-configuration-service-stub'; +import { SEARCH_CONFIG_SERVICE } from '../../../../+my-dspace-page/my-dspace-page.component'; describe('SearchFacetFilterComponent', () => { let comp: SearchFacetFilterComponent; @@ -35,14 +36,17 @@ describe('SearchFacetFilterComponent', () => { }); const values: FacetValue[] = [ { + label: value1, value: value1, count: 52, search: '' }, { + label: value2, value: value2, count: 20, search: '' }, { + label: value3, value: value3, count: 5, search: '' @@ -66,7 +70,7 @@ describe('SearchFacetFilterComponent', () => { { provide: Router, useValue: new RouterStub() }, { provide: FILTER_CONFIG, useValue: new SearchFilterConfig() }, { provide: RemoteDataBuildService, useValue: {aggregate: () => observableOf({})} }, - { provide: SearchConfigurationService, useValue: {searchOptions: observableOf({})} }, + { provide: SEARCH_CONFIG_SERVICE, useValue: new SearchConfigurationServiceStub() }, { provide: SearchFilterService, useValue: { getSelectedValuesForFilter: () => observableOf(selectedValues), diff --git a/src/app/+search-page/search-filters/search-filter/search-facet-filter/search-facet-filter.component.ts b/src/app/+search-page/search-filters/search-filter/search-facet-filter/search-facet-filter.component.ts index 367947a377..5959a2331e 100644 --- a/src/app/+search-page/search-filters/search-filter/search-facet-filter/search-facet-filter.component.ts +++ b/src/app/+search-page/search-filters/search-filter/search-facet-filter/search-facet-filter.component.ts @@ -6,7 +6,7 @@ import { Subject, Subscription } from 'rxjs'; -import { switchMap, distinctUntilChanged, map, take } from 'rxjs/operators'; +import { switchMap, distinctUntilChanged, map, take, flatMap } from 'rxjs/operators'; import { animate, state, style, transition, trigger } from '@angular/animations'; import { Component, Inject, OnDestroy, OnInit } from '@angular/core'; import { Router } from '@angular/router'; @@ -23,6 +23,7 @@ import { SearchConfigurationService } from '../../../search-service/search-confi import { getSucceededRemoteData } from '../../../../core/shared/operators'; import { InputSuggestion } from '../../../../shared/input-suggestions/input-suggestions.model'; import { SearchOptions } from '../../../search-options.model'; +import { SEARCH_CONFIG_SERVICE } from '../../../../+my-dspace-page/my-dspace-page.component'; @Component({ selector: 'ds-search-facet-filter', @@ -56,7 +57,7 @@ export class SearchFacetFilterComponent implements OnInit, OnDestroy { /** * List of subscriptions to unsubscribe from */ - private subs: Subscription[] = []; + protected subs: Subscription[] = []; /** * Emits the result values for this filter found by the current filter query @@ -66,8 +67,8 @@ export class SearchFacetFilterComponent implements OnInit, OnDestroy { /** * Emits the active values for this filter */ - selectedValues$: Observable; - private collapseNextUpdate = true; + selectedValues$: Observable; + protected collapseNextUpdate = true; /** * State of the requested facets used to time the animation @@ -81,9 +82,9 @@ export class SearchFacetFilterComponent implements OnInit, OnDestroy { constructor(protected searchService: SearchService, protected filterService: SearchFilterService, - protected searchConfigService: SearchConfigurationService, protected rdbs: RemoteDataBuildService, protected router: Router, + @Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService, @Inject(FILTER_CONFIG) public filterConfig: SearchFilterConfig) { } @@ -94,10 +95,9 @@ export class SearchFacetFilterComponent implements OnInit, OnDestroy { this.filterValues$ = new BehaviorSubject(new RemoteData(true, false, undefined, undefined, undefined)); this.currentPage = this.getCurrentPage().pipe(distinctUntilChanged()); - this.selectedValues$ = this.filterService.getSelectedValuesForFilter(this.filterConfig); this.searchOptions$ = this.searchConfigService.searchOptions; this.subs.push(this.searchOptions$.subscribe(() => this.updateFilterValueList())); - const facetValues = observableCombineLatest(this.searchOptions$, this.currentPage).pipe( + const facetValues$ = observableCombineLatest(this.searchOptions$, this.currentPage).pipe( map(([options, page]) => { return { options, page } }), @@ -115,8 +115,17 @@ export class SearchFacetFilterComponent implements OnInit, OnDestroy { ) }) ); + + this.selectedValues$ = observableCombineLatest( + this.filterService.getSelectedValuesForFilter(this.filterConfig), + facetValues$.pipe(flatMap((facetValues) => facetValues.values))).pipe( + map(([selectedValues, facetValues]) => { + return facetValues.payload.page.filter((facetValue) => selectedValues.includes(this.getFacetValue(facetValue))) + }) + ); + let filterValues = []; - this.subs.push(facetValues.subscribe((facetOutcome) => { + this.subs.push(facetValues$.subscribe((facetOutcome) => { const newValues$ = facetOutcome.values; if (this.collapseNextUpdate) { @@ -201,7 +210,10 @@ export class SearchFacetFilterComponent implements OnInit, OnDestroy { if (isNotEmpty(data)) { this.router.navigate([this.getSearchLink()], { queryParams: - { [this.filterConfig.paramName]: [...selectedValues, data] }, + { [this.filterConfig.paramName]: [ + ...selectedValues.map((facet) => this.getFacetValue(facet)), + data + ] }, queryParamsHandling: 'merge' }); this.filter = ''; @@ -252,7 +264,7 @@ export class SearchFacetFilterComponent implements OnInit, OnDestroy { return rd.payload.page.map((facet) => { return { displayValue: this.getDisplayValue(facet, data), - value: facet.value + value: this.getFacetValue(facet) } }) } @@ -264,6 +276,13 @@ export class SearchFacetFilterComponent implements OnInit, OnDestroy { } } + /** + * Retrieve facet value + */ + protected getFacetValue(facet: FacetValue): string { + return facet.value; + } + /** * Transforms the facet value string, so if the query matches part of the value, it's emphasized in the value * @param {FacetValue} facet The value of the facet as returned by the server diff --git a/src/app/+search-page/search-filters/search-filter/search-filter.component.html b/src/app/+search-page/search-filters/search-filter/search-filter.component.html index 5c4db44d24..83320770b8 100644 --- a/src/app/+search-page/search-filters/search-filter/search-filter.component.html +++ b/src/app/+search-page/search-filters/search-filter/search-filter.component.html @@ -4,4 +4,4 @@ - \ No newline at end of file + diff --git a/src/app/+search-page/search-filters/search-filter/search-filter.component.spec.ts b/src/app/+search-page/search-filters/search-filter/search-filter.component.spec.ts index 30ef349675..23c4ab3b53 100644 --- a/src/app/+search-page/search-filters/search-filter/search-filter.component.spec.ts +++ b/src/app/+search-page/search-filters/search-filter/search-filter.component.spec.ts @@ -11,6 +11,8 @@ import { SearchFilterComponent } from './search-filter.component'; import { SearchFilterConfig } from '../../search-service/search-filter-config.model'; import { FilterType } from '../../search-service/filter-type.model'; import { SearchConfigurationService } from '../../search-service/search-configuration.service'; +import { SearchConfigurationServiceStub } from '../../../shared/testing/search-configuration-service-stub'; +import { SEARCH_CONFIG_SERVICE } from '../../../+my-dspace-page/my-dspace-page.component'; describe('SearchFilterComponent', () => { let comp: SearchFilterComponent; @@ -54,8 +56,6 @@ describe('SearchFilterComponent', () => { getFacetValuesFor: (filter) => mockResults }; - const searchConfigServiceStub = {}; - beforeEach(async(() => { TestBed.configureTestingModule({ imports: [TranslateModule.forRoot(), RouterTestingModule.withRoutes([]), NoopAnimationsModule], @@ -66,7 +66,7 @@ describe('SearchFilterComponent', () => { provide: SearchFilterService, useValue: mockFilterService }, - { provide: SearchConfigurationService, useValue: searchConfigServiceStub }, + { provide: SEARCH_CONFIG_SERVICE, useValue: new SearchConfigurationServiceStub() } ], schemas: [NO_ERRORS_SCHEMA] }).overrideComponent(SearchFilterComponent, { diff --git a/src/app/+search-page/search-filters/search-filter/search-filter.component.ts b/src/app/+search-page/search-filters/search-filter/search-filter.component.ts index 14ba8f0b76..5c6973bd98 100644 --- a/src/app/+search-page/search-filters/search-filter/search-filter.component.ts +++ b/src/app/+search-page/search-filters/search-filter/search-filter.component.ts @@ -1,12 +1,15 @@ +import { Component, Inject, Input, OnInit } from '@angular/core'; + +import { Observable, of as observableOf } from 'rxjs'; import { filter, first, map, startWith, switchMap, take } from 'rxjs/operators'; -import { Component, Input, OnInit } from '@angular/core'; + import { SearchFilterConfig } from '../../search-service/search-filter-config.model'; import { SearchFilterService } from './search-filter.service'; -import { BehaviorSubject, Observable, of as observableOf } from 'rxjs'; import { slide } from '../../../shared/animations/slide'; import { isNotEmpty } from '../../../shared/empty.util'; import { SearchService } from '../../search-service/search.service'; import { SearchConfigurationService } from '../../search-service/search-configuration.service'; +import { SEARCH_CONFIG_SERVICE } from '../../../+my-dspace-page/my-dspace-page.component'; @Component({ selector: 'ds-search-filter', @@ -44,7 +47,10 @@ export class SearchFilterComponent implements OnInit { */ active$: Observable; - constructor(private filterService: SearchFilterService, private searchService: SearchService, private searchConfigService: SearchConfigurationService) { + constructor( + private filterService: SearchFilterService, + private searchService: SearchService, + @Inject(SEARCH_CONFIG_SERVICE) private searchConfigService: SearchConfigurationService) { } /** diff --git a/src/app/+search-page/search-filters/search-filter/search-filter.reducer.ts b/src/app/+search-page/search-filters/search-filter/search-filter.reducer.ts index 187bcd50d0..7102c8c9bc 100644 --- a/src/app/+search-page/search-filters/search-filter/search-filter.reducer.ts +++ b/src/app/+search-page/search-filters/search-filter/search-filter.reducer.ts @@ -1,9 +1,4 @@ -import { - SearchFilterAction, - SearchFilterActionTypes, - SearchFilterInitializeAction -} from './search-filter.actions'; -import { isEmpty, isNotUndefined } from '../../../shared/empty.util'; +import { SearchFilterAction, SearchFilterActionTypes, SearchFilterInitializeAction } from './search-filter.actions'; /** * Interface that represents the state for a single filters diff --git a/src/app/+search-page/search-filters/search-filter/search-range-filter/search-range-filter.component.spec.ts b/src/app/+search-page/search-filters/search-filter/search-range-filter/search-range-filter.component.spec.ts index 930ea8c9fb..4fc3222600 100644 --- a/src/app/+search-page/search-filters/search-filter/search-range-filter/search-range-filter.component.spec.ts +++ b/src/app/+search-page/search-filters/search-filter/search-range-filter/search-range-filter.component.spec.ts @@ -19,6 +19,8 @@ import { SearchRangeFilterComponent } from './search-range-filter.component'; import { RouteService } from '../../../../shared/services/route.service'; import { RemoteDataBuildService } from '../../../../core/cache/builders/remote-data-build.service'; import { SearchConfigurationService } from '../../../search-service/search-configuration.service'; +import { SEARCH_CONFIG_SERVICE } from '../../../../+my-dspace-page/my-dspace-page.component'; +import { SearchConfigurationServiceStub } from '../../../../shared/testing/search-configuration-service-stub'; describe('SearchRangeFilterComponent', () => { let comp: SearchRangeFilterComponent; @@ -41,14 +43,17 @@ describe('SearchRangeFilterComponent', () => { }); const values: FacetValue[] = [ { + label: value1, value: value1, count: 52, search: '' }, { + label: value2, value: value2, count: 20, search: '' }, { + label: value3, value: value3, count: 5, search: '' @@ -73,9 +78,7 @@ describe('SearchRangeFilterComponent', () => { { provide: FILTER_CONFIG, useValue: mockFilterConfig }, { provide: RemoteDataBuildService, useValue: {aggregate: () => observableOf({})} }, { provide: RouteService, useValue: {getQueryParameterValue: () => observableOf({})} }, - { provide: SearchConfigurationService, useValue: { - searchOptions: observableOf({}) } - }, + { provide: SEARCH_CONFIG_SERVICE, useValue: new SearchConfigurationServiceStub() }, { provide: SearchFilterService, useValue: { getSelectedValuesForFilter: () => selectedValues, diff --git a/src/app/+search-page/search-filters/search-filter/search-range-filter/search-range-filter.component.ts b/src/app/+search-page/search-filters/search-filter/search-range-filter/search-range-filter.component.ts index ebdb797500..60eaaa058e 100644 --- a/src/app/+search-page/search-filters/search-filter/search-range-filter/search-range-filter.component.ts +++ b/src/app/+search-page/search-filters/search-filter/search-range-filter/search-range-filter.component.ts @@ -17,6 +17,7 @@ import * as moment from 'moment'; import { RouteService } from '../../../../shared/services/route.service'; import { hasValue } from '../../../../shared/empty.util'; import { SearchConfigurationService } from '../../../search-service/search-configuration.service'; +import { SEARCH_CONFIG_SERVICE } from '../../../../+my-dspace-page/my-dspace-page.component'; /** * The suffix for a range filters' minimum in the frontend URL @@ -72,13 +73,13 @@ export class SearchRangeFilterComponent extends SearchFacetFilterComponent imple constructor(protected searchService: SearchService, protected filterService: SearchFilterService, - protected searchConfigService: SearchConfigurationService, protected router: Router, protected rdbs: RemoteDataBuildService, + @Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService, @Inject(FILTER_CONFIG) public filterConfig: SearchFilterConfig, @Inject(PLATFORM_ID) private platformId: any, private route: RouteService) { - super(searchService, filterService, searchConfigService, rdbs, router, filterConfig); + super(searchService, filterService, rdbs, router, searchConfigService, filterConfig); } diff --git a/src/app/+search-page/search-filters/search-filters.component.html b/src/app/+search-page/search-filters/search-filters.component.html index 895765f6ac..23e2b6918c 100644 --- a/src/app/+search-page/search-filters/search-filters.component.html +++ b/src/app/+search-page/search-filters/search-filters.component.html @@ -4,4 +4,4 @@ -{{"search.filters.reset" | translate}} \ No newline at end of file +{{"search.filters.reset" | translate}} diff --git a/src/app/+search-page/search-filters/search-filters.component.spec.ts b/src/app/+search-page/search-filters/search-filters.component.spec.ts index db21fc8a69..dc883cd290 100644 --- a/src/app/+search-page/search-filters/search-filters.component.spec.ts +++ b/src/app/+search-page/search-filters/search-filters.component.spec.ts @@ -7,13 +7,15 @@ import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { SearchFilterService } from './search-filter/search-filter.service'; import { SearchFiltersComponent } from './search-filters.component'; import { SearchService } from '../search-service/search.service'; -import { SearchConfigurationService } from '../search-service/search-configuration.service'; import { of as observableOf } from 'rxjs'; +import { SEARCH_CONFIG_SERVICE } from '../../+my-dspace-page/my-dspace-page.component'; +import { SearchConfigurationServiceStub } from '../../shared/testing/search-configuration-service-stub'; describe('SearchFiltersComponent', () => { let comp: SearchFiltersComponent; let fixture: ComponentFixture; let searchService: SearchService; + const searchServiceStub = { /* tslint:disable:no-empty */ getConfig: () => @@ -30,17 +32,13 @@ describe('SearchFiltersComponent', () => { [] }; - const searchConfigServiceStub = jasmine.createSpyObj('SearchConfigurationService', { - getCurrentFrontendFilters: observableOf({}) - }); - beforeEach(async(() => { TestBed.configureTestingModule({ imports: [TranslateModule.forRoot(), RouterTestingModule.withRoutes([]), NoopAnimationsModule], declarations: [SearchFiltersComponent], providers: [ { provide: SearchService, useValue: searchServiceStub }, - { provide: SearchConfigurationService, useValue: searchConfigServiceStub }, + { provide: SEARCH_CONFIG_SERVICE, useValue: new SearchConfigurationServiceStub() }, { provide: SearchFilterService, useValue: searchFiltersStub }, ], diff --git a/src/app/+search-page/search-filters/search-filters.component.ts b/src/app/+search-page/search-filters/search-filters.component.ts index 1dd747e908..9c235b2f58 100644 --- a/src/app/+search-page/search-filters/search-filters.component.ts +++ b/src/app/+search-page/search-filters/search-filters.component.ts @@ -1,13 +1,15 @@ -import { Observable } from 'rxjs'; +import { Component, Inject, OnInit } from '@angular/core'; + +import { Observable } from 'rxjs'; +import { map, switchMap } from 'rxjs/operators'; -import { map } from 'rxjs/operators'; -import { Component } from '@angular/core'; import { SearchService } from '../search-service/search.service'; import { RemoteData } from '../../core/data/remote-data'; import { SearchFilterConfig } from '../search-service/search-filter-config.model'; import { SearchConfigurationService } from '../search-service/search-configuration.service'; import { SearchFilterService } from './search-filter/search-filter.service'; import { getSucceededRemoteData } from '../../core/shared/operators'; +import { SEARCH_CONFIG_SERVICE } from '../../+my-dspace-page/my-dspace-page.component'; @Component({ selector: 'ds-search-filters', @@ -18,7 +20,7 @@ import { getSucceededRemoteData } from '../../core/shared/operators'; /** * This component represents the part of the search sidebar that contains filters. */ -export class SearchFiltersComponent { +export class SearchFiltersComponent implements OnInit { /** * An observable containing configuration about which filters are shown and how they are shown */ @@ -36,9 +38,20 @@ export class SearchFiltersComponent { * @param {SearchConfigurationService} searchConfigService * @param {SearchFilterService} filterService */ - constructor(private searchService: SearchService, private searchConfigService: SearchConfigurationService, private filterService: SearchFilterService) { - this.filters = searchService.getConfig().pipe(getSucceededRemoteData()); - this.clearParams = searchConfigService.getCurrentFrontendFilters().pipe(map((filters) => { + constructor( + private searchService: SearchService, + private filterService: SearchFilterService, + @Inject(SEARCH_CONFIG_SERVICE) private searchConfigService: SearchConfigurationService) { + + } + + ngOnInit(): void { + + this.filters = this.searchConfigService.searchOptions.pipe( + switchMap((options) => this.searchService.getConfig(options.scope, options.configuration).pipe(getSucceededRemoteData())) + ); + + this.clearParams = this.searchConfigService.getCurrentFrontendFilters().pipe(map((filters) => { Object.keys(filters).forEach((f) => filters[f] = null); return filters; })); @@ -57,4 +70,5 @@ export class SearchFiltersComponent { trackUpdate(index, config: SearchFilterConfig) { return config ? config.name : undefined; } + } diff --git a/src/app/+search-page/search-labels/search-labels.component.html b/src/app/+search-page/search-labels/search-labels.component.html index 61a5618dad..cac81e8717 100644 --- a/src/app/+search-page/search-labels/search-labels.component.html +++ b/src/app/+search-page/search-labels/search-labels.component.html @@ -2,11 +2,11 @@ - {{('search.filters.applied.' + key) | translate}}: {{values}} - × + {{('search.filters.applied.' + key) | translate}}: {{normalizeFilterValue(values)}} + × diff --git a/src/app/+search-page/search-labels/search-labels.component.spec.ts b/src/app/+search-page/search-labels/search-labels.component.spec.ts index 81fa5b5df8..d28698764c 100644 --- a/src/app/+search-page/search-labels/search-labels.component.spec.ts +++ b/src/app/+search-page/search-labels/search-labels.component.spec.ts @@ -9,7 +9,8 @@ import { SearchServiceStub } from '../../shared/testing/search-service-stub'; import { Observable, of as observableOf } from 'rxjs'; import { Params } from '@angular/router'; import { ObjectKeysPipe } from '../../shared/utils/object-keys-pipe'; -import { SearchConfigurationService } from '../search-service/search-configuration.service'; +import { SEARCH_CONFIG_SERVICE } from '../../+my-dspace-page/my-dspace-page.component'; +import { SearchConfigurationServiceStub } from '../../shared/testing/search-configuration-service-stub'; describe('SearchLabelsComponent', () => { let comp: SearchLabelsComponent; @@ -20,8 +21,11 @@ describe('SearchLabelsComponent', () => { const field1 = 'author'; const field2 = 'subject'; - const value1 = 'TestAuthor'; + const value1 = 'Test, Author'; + const normValue1 = 'Test, Author'; const value2 = 'TestSubject'; + const value3 = 'Test, Authority,authority'; + const normValue3 = 'Test, Authority'; const filter1 = [field1, value1]; const filter2 = [field2, value2]; const mockFilters = [ @@ -35,7 +39,8 @@ describe('SearchLabelsComponent', () => { declarations: [SearchLabelsComponent, ObjectKeysPipe], providers: [ { provide: SearchService, useValue: new SearchServiceStub(searchLink) }, - { provide: SearchConfigurationService, useValue: {getCurrentFrontendFilters : () => observableOf({})} } + { provide: SEARCH_CONFIG_SERVICE, useValue: new SearchConfigurationServiceStub() } + // { provide: SearchConfigurationService, useValue: {getCurrentFrontendFilters : () => observableOf({})} } ], schemas: [NO_ERRORS_SCHEMA] }).overrideComponent(SearchLabelsComponent, { @@ -65,4 +70,16 @@ describe('SearchLabelsComponent', () => { }); }) }); + + describe('when normalizeFilterValue is called', () => { + it('should return properly filter value', () => { + let result: string; + + result = comp.normalizeFilterValue(value1); + expect(result).toBe(normValue1); + + result = comp.normalizeFilterValue(value3); + expect(result).toBe(normValue3); + }) + }); }); diff --git a/src/app/+search-page/search-labels/search-labels.component.ts b/src/app/+search-page/search-labels/search-labels.component.ts index 08e07cce3d..1f12311210 100644 --- a/src/app/+search-page/search-labels/search-labels.component.ts +++ b/src/app/+search-page/search-labels/search-labels.component.ts @@ -1,10 +1,11 @@ -import { Component } from '@angular/core'; +import { Component, Inject } from '@angular/core'; import { SearchService } from '../search-service/search.service'; import { Observable } from 'rxjs'; import { Params } from '@angular/router'; import { map } from 'rxjs/operators'; import { hasValue, isNotEmpty } from '../../shared/empty.util'; import { SearchConfigurationService } from '../search-service/search-configuration.service'; +import { SEARCH_CONFIG_SERVICE } from '../../+my-dspace-page/my-dspace-page.component'; @Component({ selector: 'ds-search-labels', @@ -24,7 +25,9 @@ export class SearchLabelsComponent { /** * Initialize the instance variable */ - constructor(private searchService: SearchService, private searchConfigService: SearchConfigurationService) { + constructor( + private searchService: SearchService, + @Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService) { this.appliedFilters = this.searchConfigService.getCurrentFrontendFilters(); } @@ -53,4 +56,17 @@ export class SearchLabelsComponent { getSearchLink() { return this.searchService.getSearchLink(); } + + /** + * TODO to review after https://github.com/DSpace/dspace-angular/issues/368 is resolved + * Strips authority operator from filter value + * e.g. 'test ,authority' => 'test' + * + * @param value + */ + normalizeFilterValue(value: string) { + // const pattern = /,[^,]*$/g; + const pattern = /,authority*$/g; + return value.replace(pattern, ''); + } } diff --git a/src/app/+search-page/search-options.model.ts b/src/app/+search-page/search-options.model.ts index 69309bed66..2b18854e1e 100644 --- a/src/app/+search-page/search-options.model.ts +++ b/src/app/+search-page/search-options.model.ts @@ -9,6 +9,7 @@ import { SetViewMode } from '../shared/view-mode'; * This model class represents all parameters needed to request information about a certain search request */ export class SearchOptions { + configuration?: string; view?: SetViewMode = SetViewMode.List; scope?: string; query?: string; @@ -16,7 +17,8 @@ export class SearchOptions { filters?: any; fixedFilter?: any; - constructor(options: {scope?: string, query?: string, dsoType?: DSpaceObjectType, filters?: SearchFilter[], fixedFilter?: any}) { + constructor(options: {configuration?: string, scope?: string, query?: string, dsoType?: DSpaceObjectType, filters?: SearchFilter[], fixedFilter?: any}) { + this.configuration = options.configuration; this.scope = options.scope; this.query = options.query; this.dsoType = options.dsoType; @@ -31,6 +33,9 @@ export class SearchOptions { * @returns {string} URL with all search options and passed arguments as query parameters */ toRestUrl(url: string, args: string[] = []): string { + if (isNotEmpty(this.configuration)) { + args.push(`configuration=${this.configuration}`); + } if (isNotEmpty(this.fixedFilter)) { args.push(this.fixedFilter); } @@ -45,7 +50,10 @@ export class SearchOptions { } if (isNotEmpty(this.filters)) { this.filters.forEach((filter: SearchFilter) => { - filter.values.forEach((value) => args.push(`${filter.key}=${value},${filter.operator}`)); + filter.values.forEach((value) => { + const filterValue = value.includes(',') ? `${value}` : `${value},${filter.operator}`; + args.push(`${filter.key}=${filterValue}`) + }); }); } if (isNotEmpty(args)) { diff --git a/src/app/+search-page/search-page.component.spec.ts b/src/app/+search-page/search-page.component.spec.ts index 68a0dc6352..2393d3d1e7 100644 --- a/src/app/+search-page/search-page.component.spec.ts +++ b/src/app/+search-page/search-page.component.spec.ts @@ -20,11 +20,15 @@ import { SearchSidebarService } from './search-sidebar/search-sidebar.service'; import { SearchFilterService } from './search-filters/search-filter/search-filter.service'; import { SearchConfigurationService } from './search-service/search-configuration.service'; import { RemoteData } from '../core/data/remote-data'; +import { SEARCH_CONFIG_SERVICE } from '../+my-dspace-page/my-dspace-page.component'; import { RouteService } from '../shared/services/route.service'; +import { SearchConfigurationServiceStub } from '../shared/testing/search-configuration-service-stub'; +import { PaginatedSearchOptions } from './paginated-search-options.model'; let comp: SearchPageComponent; let fixture: ComponentFixture; let searchServiceObject: SearchService; +let searchConfigurationServiceObject: SearchConfigurationService; const store: Store = jasmine.createSpyObj('store', { /* tslint:disable:no-empty */ dispatch: {}, @@ -42,17 +46,25 @@ const searchServiceStub = jasmine.createSpyObj('SearchService', { getSearchLink: '/search', getScopes: observableOf(['test-scope']) }); +const configurationParam = 'default'; const queryParam = 'test query'; const scopeParam = '7669c72a-3f2a-451f-a3b9-9210e7a4c02f'; const fixedFilter = 'fixed filter'; -const paginatedSearchOptions = { +const paginatedSearchOptions = new PaginatedSearchOptions({ + configuration: configurationParam, query: queryParam, scope: scopeParam, fixedFilter: fixedFilter, pagination, sort -}; +}); const activatedRouteStub = { + snapshot: { + queryParamMap: new Map([ + ['query', queryParam], + ['scope', scopeParam] + ]) + }, queryParams: observableOf({ query: queryParam, scope: scopeParam @@ -81,6 +93,7 @@ export function configureSearchComponentTestingModule(compType) { useValue: jasmine.createSpyObj('communityService', ['findById', 'findAll']) }, { provide: ActivatedRoute, useValue: activatedRouteStub }, + { provide: RouteService, useValue: routeServiceStub }, { provide: Store, useValue: store }, @@ -114,9 +127,9 @@ export function configureSearchComponentTestingModule(compType) { } }, { - provide: RouteService, - useValue: routeServiceStub - } + provide: SEARCH_CONFIG_SERVICE, + useValue: new SearchConfigurationServiceStub() + }, ], schemas: [NO_ERRORS_SCHEMA] }).overrideComponent(compType, { @@ -125,7 +138,6 @@ export function configureSearchComponentTestingModule(compType) { } describe('SearchPageComponent', () => { - beforeEach(async(() => { configureSearchComponentTestingModule(SearchPageComponent); })); @@ -135,25 +147,21 @@ describe('SearchPageComponent', () => { comp = fixture.componentInstance; // SearchPageComponent test instance fixture.detectChanges(); searchServiceObject = (comp as any).service; + searchConfigurationServiceObject = (comp as any).searchConfigService; + }); + + afterEach(() => { + comp = null; + searchServiceObject = null; + searchConfigurationServiceObject = null; }); it('should get the scope and query from the route parameters', () => { + + searchConfigurationServiceObject.paginatedSearchOptions.next(paginatedSearchOptions); expect(comp.searchOptions$).toBeObservable(cold('b', { b: paginatedSearchOptions })); - }); - - describe('when the closeSidebar event is emitted clicked in mobile view', () => { - - beforeEach(() => { - spyOn(comp, 'closeSidebar'); - const closeSidebarButton = fixture.debugElement.query(By.css('#search-sidebar-sm')); - closeSidebarButton.triggerEventHandler('toggleSidebar', null); - }); - - it('should trigger the closeSidebar function', () => { - expect(comp.closeSidebar).toHaveBeenCalled(); - }); }); diff --git a/src/app/+search-page/search-page.component.ts b/src/app/+search-page/search-page.component.ts index b94eb39f9b..f81140dfa7 100644 --- a/src/app/+search-page/search-page.component.ts +++ b/src/app/+search-page/search-page.component.ts @@ -1,4 +1,4 @@ -import { ChangeDetectionStrategy, Component, Input, OnInit } from '@angular/core'; +import { ChangeDetectionStrategy, Component, Inject, Input, OnInit } from '@angular/core'; import { Observable , Subscription , BehaviorSubject } from 'rxjs'; import { switchMap, } from 'rxjs/operators'; import { PaginatedList } from '../core/data/paginated-list'; @@ -7,7 +7,6 @@ import { DSpaceObject } from '../core/shared/dspace-object.model'; import { pushInOut } from '../shared/animations/push'; import { HostWindowService } from '../shared/host-window.service'; import { PaginatedSearchOptions } from './paginated-search-options.model'; -import { SearchFilterService } from './search-filters/search-filter/search-filter.service'; import { SearchResult } from './search-result.model'; import { SearchService } from './search-service/search.service'; import { SearchSidebarService } from './search-sidebar/search-sidebar.service'; @@ -15,13 +14,28 @@ import { hasValue, isNotEmpty } from '../shared/empty.util'; import { SearchConfigurationService } from './search-service/search-configuration.service'; import { getSucceededRemoteData } from '../core/shared/operators'; import { RouteService } from '../shared/services/route.service'; +import { SEARCH_CONFIG_SERVICE } from '../+my-dspace-page/my-dspace-page.component'; + +export const SEARCH_ROUTE = '/search'; + +/** + * This component renders a simple item page. + * The route parameter 'id' is used to request the item it represents. + * All fields of the item that should be displayed, are defined in its template. + */ @Component({ selector: 'ds-search-page', styleUrls: ['./search-page.component.scss'], templateUrl: './search-page.component.html', changeDetection: ChangeDetectionStrategy.OnPush, - animations: [pushInOut] + animations: [pushInOut], + providers: [ + { + provide: SEARCH_CONFIG_SERVICE, + useClass: SearchConfigurationService + } + ] }) /** @@ -76,7 +90,7 @@ export class SearchPageComponent implements OnInit { constructor(protected service: SearchService, protected sidebarService: SearchSidebarService, protected windowService: HostWindowService, - protected searchConfigService: SearchConfigurationService, + @Inject(SEARCH_CONFIG_SERVICE) public searchConfigService: SearchConfigurationService, protected routeService: RouteService) { this.isXsOrSm$ = this.windowService.isXsOrSm(); } diff --git a/src/app/+search-page/search-page.module.ts b/src/app/+search-page/search-page.module.ts index 2b2ee861da..65558eae17 100644 --- a/src/app/+search-page/search-page.module.ts +++ b/src/app/+search-page/search-page.module.ts @@ -5,9 +5,6 @@ import { SharedModule } from '../shared/shared.module'; import { SearchPageRoutingModule } from './search-page-routing.module'; import { SearchPageComponent } from './search-page.component'; import { SearchResultsComponent } from './search-results/search-results.component'; -import { ItemSearchResultListElementComponent } from '../shared/object-list/search-result-list-element/item-search-result/item-search-result-list-element.component'; -import { CollectionSearchResultListElementComponent } from '../shared/object-list/search-result-list-element/collection-search-result/collection-search-result-list-element.component'; -import { CommunitySearchResultListElementComponent } from '../shared/object-list/search-result-list-element/community-search-result/community-search-result-list-element.component'; import { ItemSearchResultGridElementComponent } from '../shared/object-grid/search-result-grid-element/item-search-result/item-search-result-grid-element.component'; import { CommunitySearchResultGridElementComponent } from '../shared/object-grid/search-result-grid-element/community-search-result/community-search-result-grid-element.component' import { CollectionSearchResultGridElementComponent } from '../shared/object-grid/search-result-grid-element/collection-search-result/collection-search-result-grid-element.component'; @@ -33,11 +30,39 @@ import { SearchConfigurationService } from './search-service/search-configuratio import { SearchFacetOptionComponent } from './search-filters/search-filter/search-facet-filter-options/search-facet-option/search-facet-option.component'; import { SearchFacetSelectedOptionComponent } from './search-filters/search-filter/search-facet-filter-options/search-facet-selected-option/search-facet-selected-option.component'; import { SearchFacetRangeOptionComponent } from './search-filters/search-filter/search-facet-filter-options/search-facet-range-option/search-facet-range-option.component'; +import { SearchSwitchConfigurationComponent } from './search-switch-configuration/search-switch-configuration.component'; +import { SearchAuthorityFilterComponent } from './search-filters/search-filter/search-authority-filter/search-authority-filter.component'; const effects = [ SearchSidebarEffects ]; +const components = [ + SearchPageComponent, + SearchResultsComponent, + SearchSidebarComponent, + SearchSettingsComponent, + ItemSearchResultGridElementComponent, + CollectionSearchResultGridElementComponent, + CommunitySearchResultGridElementComponent, + SearchFiltersComponent, + SearchFilterComponent, + SearchFacetFilterComponent, + SearchLabelsComponent, + SearchFacetFilterComponent, + SearchFacetFilterWrapperComponent, + SearchRangeFilterComponent, + SearchTextFilterComponent, + SearchHierarchyFilterComponent, + SearchBooleanFilterComponent, + SearchFacetOptionComponent, + SearchFacetSelectedOptionComponent, + SearchFacetRangeOptionComponent, + SearchSwitchConfigurationComponent, + SearchAuthorityFilterComponent, + FilteredSearchPageComponent +]; + @NgModule({ imports: [ SearchPageRoutingModule, @@ -46,29 +71,7 @@ const effects = [ EffectsModule.forFeature(effects), CoreModule.forRoot() ], - declarations: [ - SearchPageComponent, - FilteredSearchPageComponent, - SearchResultsComponent, - SearchSidebarComponent, - SearchSettingsComponent, - ItemSearchResultGridElementComponent, - CollectionSearchResultGridElementComponent, - CommunitySearchResultGridElementComponent, - SearchFiltersComponent, - SearchFilterComponent, - SearchFacetFilterComponent, - SearchLabelsComponent, - SearchFacetFilterComponent, - SearchFacetFilterWrapperComponent, - SearchRangeFilterComponent, - SearchTextFilterComponent, - SearchHierarchyFilterComponent, - SearchBooleanFilterComponent, - SearchFacetOptionComponent, - SearchFacetSelectedOptionComponent, - SearchFacetRangeOptionComponent - ], + declarations: components, providers: [ SearchSidebarService, SearchFilterService, @@ -78,9 +81,6 @@ const effects = [ SearchConfigurationService ], entryComponents: [ - ItemSearchResultListElementComponent, - CollectionSearchResultListElementComponent, - CommunitySearchResultListElementComponent, ItemSearchResultGridElementComponent, CollectionSearchResultGridElementComponent, CommunitySearchResultGridElementComponent, @@ -91,11 +91,10 @@ const effects = [ SearchBooleanFilterComponent, SearchFacetOptionComponent, SearchFacetSelectedOptionComponent, - SearchFacetRangeOptionComponent + SearchFacetRangeOptionComponent, + SearchAuthorityFilterComponent ], - exports: [ - FilteredSearchPageComponent, - ] + exports: components }) /** diff --git a/src/app/+search-page/search-result.model.ts b/src/app/+search-page/search-result.model.ts index ff865610c6..0354edbc6b 100644 --- a/src/app/+search-page/search-result.model.ts +++ b/src/app/+search-page/search-result.model.ts @@ -9,7 +9,7 @@ export class SearchResult implements ListableObject { /** * The DSpaceObject that was found */ - dspaceObject: T; + indexableObject: T; /** * The metadata that was used to find this item, hithighlighted diff --git a/src/app/+search-page/search-service/facet-value.model.ts b/src/app/+search-page/search-service/facet-value.model.ts index 0f673f3485..d2cc521356 100644 --- a/src/app/+search-page/search-service/facet-value.model.ts +++ b/src/app/+search-page/search-service/facet-value.model.ts @@ -5,7 +5,13 @@ import { autoserialize, autoserializeAs } from 'cerialize'; */ export class FacetValue { /** - * The display value of the facet value + * The display label of the facet value + */ + @autoserialize + label: string; + + /** + * The value of the facet value */ @autoserializeAs(String, 'label') value: string; diff --git a/src/app/+search-page/search-service/filter-type.model.ts b/src/app/+search-page/search-service/filter-type.model.ts index d9b9629347..d5a338de6d 100644 --- a/src/app/+search-page/search-service/filter-type.model.ts +++ b/src/app/+search-page/search-service/filter-type.model.ts @@ -2,6 +2,11 @@ * Enumeration containing all possible types for filters */ export enum FilterType { + /** + * Represents authority facets + */ + authority = 'authority', + /** * Represents simple text facets */ diff --git a/src/app/+search-page/search-service/search-configuration.service.spec.ts b/src/app/+search-page/search-service/search-configuration.service.spec.ts index 88fd784f0b..79932805c1 100644 --- a/src/app/+search-page/search-service/search-configuration.service.spec.ts +++ b/src/app/+search-page/search-service/search-configuration.service.spec.ts @@ -17,6 +17,7 @@ describe('SearchConfigurationService', () => { const defaults = new PaginatedSearchOptions({ pagination: Object.assign(new PaginationComponentOptions(), { currentPage: 1, pageSize: 20 }), sort: new SortOptions('score', SortDirection.DESC), + configuration: 'default', query: '', scope: '' }); @@ -47,6 +48,15 @@ describe('SearchConfigurationService', () => { }); }); + describe('when getCurrentConfiguration is called', () => { + beforeEach(() => { + service.getCurrentConfiguration(''); + }); + it('should call getQueryParameterValue on the routeService with parameter name \'configuration\'', () => { + expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('configuration'); + }); + }); + describe('when getCurrentQuery is called', () => { beforeEach(() => { service.getCurrentQuery(''); @@ -98,6 +108,7 @@ describe('SearchConfigurationService', () => { expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('sortField'); }); }); + describe('when getCurrentPagination is called', () => { beforeEach(() => { service.getCurrentPagination({ currentPage: 1, pageSize: 10 } as any); @@ -109,11 +120,13 @@ describe('SearchConfigurationService', () => { expect((service as any).routeService.getQueryParameterValue).toHaveBeenCalledWith('pageSize'); }); }); + describe('when subscribeToSearchOptions or subscribeToPaginatedSearchOptions is called', () => { beforeEach(() => { spyOn(service, 'getCurrentPagination').and.callThrough(); spyOn(service, 'getCurrentSort').and.callThrough(); spyOn(service, 'getCurrentScope').and.callThrough(); + spyOn(service, 'getCurrentConfiguration').and.callThrough(); spyOn(service, 'getCurrentQuery').and.callThrough(); spyOn(service, 'getCurrentDSOType').and.callThrough(); spyOn(service, 'getCurrentFilters').and.callThrough(); @@ -127,6 +140,7 @@ describe('SearchConfigurationService', () => { expect(service.getCurrentPagination).not.toHaveBeenCalled(); expect(service.getCurrentSort).not.toHaveBeenCalled(); expect(service.getCurrentScope).toHaveBeenCalled(); + expect(service.getCurrentConfiguration).toHaveBeenCalled(); expect(service.getCurrentQuery).toHaveBeenCalled(); expect(service.getCurrentDSOType).toHaveBeenCalled(); expect(service.getCurrentFilters).toHaveBeenCalled(); @@ -141,6 +155,7 @@ describe('SearchConfigurationService', () => { expect(service.getCurrentPagination).toHaveBeenCalled(); expect(service.getCurrentSort).toHaveBeenCalled(); expect(service.getCurrentScope).toHaveBeenCalled(); + expect(service.getCurrentConfiguration).toHaveBeenCalled(); expect(service.getCurrentQuery).toHaveBeenCalled(); expect(service.getCurrentDSOType).toHaveBeenCalled(); expect(service.getCurrentFilters).toHaveBeenCalled(); diff --git a/src/app/+search-page/search-service/search-configuration.service.ts b/src/app/+search-page/search-service/search-configuration.service.ts index 0cbf1ba6f8..39acd19ccd 100644 --- a/src/app/+search-page/search-service/search-configuration.service.ts +++ b/src/app/+search-page/search-service/search-configuration.service.ts @@ -1,3 +1,6 @@ +import { Injectable, OnDestroy } from '@angular/core'; +import { ActivatedRoute, Params } from '@angular/router'; + import { BehaviorSubject, combineLatest as observableCombineLatest, @@ -10,9 +13,7 @@ import { filter, flatMap, map } from 'rxjs/operators'; import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model'; import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model'; import { SearchOptions } from '../search-options.model'; -import { ActivatedRoute, Params } from '@angular/router'; import { PaginatedSearchOptions } from '../paginated-search-options.model'; -import { Injectable, OnDestroy } from '@angular/core'; import { RouteService } from '../../shared/services/route.service'; import { hasNoValue, hasValue, isNotEmpty, isNotEmptyOperator } from '../../shared/empty.util'; import { RemoteData } from '../../core/data/remote-data'; @@ -29,7 +30,7 @@ export class SearchConfigurationService implements OnDestroy { /** * Default pagination settings */ - private defaultPagination = Object.assign(new PaginationComponentOptions(), { + protected defaultPagination = Object.assign(new PaginationComponentOptions(), { id: 'search-page-configuration', pageSize: 10, currentPage: 1 @@ -38,22 +39,27 @@ export class SearchConfigurationService implements OnDestroy { /** * Default sort settings */ - private defaultSort = new SortOptions('score', SortDirection.DESC); + protected defaultSort = new SortOptions('score', SortDirection.DESC); + + /** + * Default configuration parameter setting + */ + protected defaultConfiguration = 'default'; /** * Default scope setting */ - private defaultScope = ''; + protected defaultScope = ''; /** * Default query setting */ - private defaultQuery = ''; + protected defaultQuery = ''; /** * Emits the current default values */ - private _defaults: Observable>; + protected _defaults: Observable>; /** * Emits the current search options @@ -68,7 +74,7 @@ export class SearchConfigurationService implements OnDestroy { /** * List of subscriptions to unsubscribe from on destroy */ - private subs: Subscription[] = new Array(); + protected subs: Subscription[] = new Array(); /** * Initialize the search options @@ -76,22 +82,40 @@ export class SearchConfigurationService implements OnDestroy { * @param {SearchFixedFilterService} fixedFilterService * @param {ActivatedRoute} route */ - constructor(private routeService: RouteService, - private fixedFilterService: SearchFixedFilterService, - private route: ActivatedRoute) { + constructor(protected routeService: RouteService, + protected fixedFilterService: SearchFixedFilterService, + protected route: ActivatedRoute) { + + this.initDefaults(); + } + + /** + * Initialize the search options + */ + protected initDefaults() { this.defaults .pipe(getSucceededRemoteData()) .subscribe((defRD) => { const defs = defRD.payload; - this.paginatedSearchOptions = new BehaviorSubject(defs); - this.searchOptions = new BehaviorSubject(defs); + this.paginatedSearchOptions = new BehaviorSubject(defs); + this.searchOptions = new BehaviorSubject(defs); this.subs.push(this.subscribeToSearchOptions(defs)); this.subs.push(this.subscribeToPaginatedSearchOptions(defs)); + } ) } + /** + * @returns {Observable} Emits the current configuration string + */ + getCurrentConfiguration(defaultConfiguration: string) { + return this.routeService.getQueryParameterValue('configuration').pipe(map((configuration) => { + return configuration || defaultConfiguration; + })); + } + /** * @returns {Observable} Emits the current scope's identifier */ @@ -115,7 +139,7 @@ export class SearchConfigurationService implements OnDestroy { */ getCurrentDSOType(): Observable { return this.routeService.getQueryParameterValue('dsoType').pipe( - filter((type) => hasValue(type) && hasValue(DSpaceObjectType[type.toUpperCase()])), + filter((type) => isNotEmpty(type) && hasValue(DSpaceObjectType[type.toUpperCase()])), map((type) => DSpaceObjectType[type.toUpperCase()]),); } @@ -200,6 +224,7 @@ export class SearchConfigurationService implements OnDestroy { */ private subscribeToSearchOptions(defaults: SearchOptions): Subscription { return observableMerge( + this.getConfigurationPart(defaults.configuration), this.getScopePart(defaults.scope), this.getQueryPart(defaults.query), this.getDSOTypePart(), @@ -221,6 +246,7 @@ export class SearchConfigurationService implements OnDestroy { return observableMerge( this.getPaginationPart(defaults.pagination), this.getSortPart(defaults.sort), + this.getConfigurationPart(defaults.configuration), this.getScopePart(defaults.scope), this.getQueryPart(defaults.query), this.getDSOTypePart(), @@ -240,6 +266,7 @@ export class SearchConfigurationService implements OnDestroy { if (hasNoValue(this._defaults)) { const options = new PaginatedSearchOptions({ pagination: this.defaultPagination, + configuration: this.defaultConfiguration, sort: this.defaultSort, scope: this.defaultScope, query: this.defaultQuery @@ -256,6 +283,16 @@ export class SearchConfigurationService implements OnDestroy { this.subs.forEach((sub) => { sub.unsubscribe(); }); + this.subs = []; + } + + /** + * @returns {Observable} Emits the current configuration settings as a partial SearchOptions object + */ + private getConfigurationPart(defaultConfiguration: string): Observable { + return this.getCurrentConfiguration(defaultConfiguration).pipe(map((configuration) => { + return { configuration } + })); } /** diff --git a/src/app/+search-page/search-service/search-query-response.model.ts b/src/app/+search-page/search-service/search-query-response.model.ts index ac1d8b7df3..bca6e644fc 100644 --- a/src/app/+search-page/search-service/search-query-response.model.ts +++ b/src/app/+search-page/search-service/search-query-response.model.ts @@ -34,7 +34,7 @@ export class SearchQueryResponse { * The sort parameters used in the search request */ @autoserialize - configurationName: string; + configuration: string; /** * The sort parameters used in the search request diff --git a/src/app/+search-page/search-service/search-result-element-decorator.ts b/src/app/+search-page/search-service/search-result-element-decorator.ts index 348cf7f592..59446480a3 100644 --- a/src/app/+search-page/search-service/search-result-element-decorator.ts +++ b/src/app/+search-page/search-service/search-result-element-decorator.ts @@ -1,5 +1,6 @@ import { GenericConstructor } from '../../core/shared/generic-constructor'; import { ListableObject } from '../../shared/object-collection/shared/listable-object.model'; +import { isNull } from '../../shared/empty.util'; /** * Contains the mapping between a search result component and a DSpaceObject @@ -11,12 +12,19 @@ const searchResultMap = new Map(); * @param {GenericConstructor} domainConstructor The constructor of the DSpaceObject * @returns Decorator function that performs the actual mapping on initialization of the component */ -export function searchResultFor(domainConstructor: GenericConstructor) { +export function searchResultFor(domainConstructor: GenericConstructor, configuration: string = null) { return function decorator(searchResult: any) { if (!searchResult) { return; } - searchResultMap.set(domainConstructor, searchResult); + if (isNull(configuration)) { + searchResultMap.set(domainConstructor, searchResult); + } else { + if (!searchResultMap.get(configuration)) { + searchResultMap.set(configuration, new Map()); + } + searchResultMap.get(configuration).set(domainConstructor, searchResult); + } }; } @@ -25,6 +33,10 @@ export function searchResultFor(domainConstructor: GenericConstructor} domainConstructor The DSpaceObject's constructor for which the search result component is requested * @returns The component's constructor that matches the given DSpaceObject */ -export function getSearchResultFor(domainConstructor: GenericConstructor) { - return searchResultMap.get(domainConstructor); +export function getSearchResultFor(domainConstructor: GenericConstructor, configuration: string = null) { + if (isNull(configuration) || configuration === 'default') { + return searchResultMap.get(domainConstructor); + } else { + return searchResultMap.get(configuration).get(domainConstructor); + } } diff --git a/src/app/+search-page/search-service/search.service.spec.ts b/src/app/+search-page/search-service/search.service.spec.ts index ee41d3d9aa..9ec5bc35f2 100644 --- a/src/app/+search-page/search-service/search.service.spec.ts +++ b/src/app/+search-page/search-service/search.service.spec.ts @@ -9,27 +9,25 @@ import { ItemDataService } from './../../core/data/item-data.service'; import { SetViewMode } from '../../shared/view-mode'; import { GLOBAL_CONFIG } from '../../../config'; import { RemoteDataBuildService } from '../../core/cache/builders/remote-data-build.service'; -import { ActivatedRoute, Router, UrlTree } from '@angular/router'; +import { Router, UrlTree } from '@angular/router'; import { RequestService } from '../../core/data/request.service'; import { ActivatedRouteStub } from '../../shared/testing/active-router-stub'; import { RouterStub } from '../../shared/testing/router-stub'; import { HALEndpointService } from '../../core/shared/hal-endpoint.service'; -import { Observable, combineLatest as observableCombineLatest } from 'rxjs'; +import { combineLatest as observableCombineLatest, Observable, of as observableOf } from 'rxjs'; import { PaginatedSearchOptions } from '../paginated-search-options.model'; import { RemoteData } from '../../core/data/remote-data'; import { RequestEntry } from '../../core/data/request.reducer'; import { getMockRequestService } from '../../shared/mocks/mock-request.service'; -import { - FacetConfigSuccessResponse, - SearchSuccessResponse -} from '../../core/cache/response.models'; +import { FacetConfigSuccessResponse, SearchSuccessResponse } from '../../core/cache/response.models'; import { SearchQueryResponse } from './search-query-response.model'; import { SearchFilterConfig } from './search-filter-config.model'; import { CommunityDataService } from '../../core/data/community-data.service'; import { ViewMode } from '../../core/shared/view-mode.model'; import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service'; -import { of as observableOf } from 'rxjs'; import { map } from 'rxjs/operators'; +import { RouteService } from '../../shared/services/route.service'; +import { routeServiceStub } from '../../shared/testing/route-service-stub'; @Component({ template: '' }) class DummyComponent { @@ -53,7 +51,7 @@ describe('SearchService', () => { ], providers: [ { provide: Router, useValue: router }, - { provide: ActivatedRoute, useValue: route }, + { provide: RouteService, useValue: routeServiceStub }, { provide: RequestService, useValue: getMockRequestService() }, { provide: RemoteDataBuildService, useValue: {} }, { provide: HALEndpointService, useValue: {} }, @@ -74,7 +72,7 @@ describe('SearchService', () => { describe('', () => { let searchService: SearchService; const router = new RouterStub(); - const route = new ActivatedRouteStub(); + let routeService; const halService = { /* tslint:disable:no-empty */ @@ -110,7 +108,7 @@ describe('SearchService', () => { ], providers: [ { provide: Router, useValue: router }, - { provide: ActivatedRoute, useValue: route }, + { provide: RouteService, useValue: routeServiceStub }, { provide: RequestService, useValue: getMockRequestService() }, { provide: RemoteDataBuildService, useValue: remoteDataBuildService }, { provide: HALEndpointService, useValue: halService }, @@ -120,6 +118,7 @@ describe('SearchService', () => { ], }); searchService = TestBed.get(SearchService); + routeService = TestBed.get(RouteService); const urlTree = Object.assign(new UrlTree(), { root: { children: { primary: 'search' } } }); router.parseUrl.and.returnValue(urlTree); }); @@ -127,7 +126,7 @@ describe('SearchService', () => { it('should call the navigate method on the Router with view mode list parameter as a parameter when setViewMode is called', () => { searchService.setViewMode(ViewMode.List); expect(router.navigate).toHaveBeenCalledWith(['/search'], { - queryParams: { view: ViewMode.List }, + queryParams: { view: ViewMode.List, page: 1 }, queryParamsHandling: 'merge' }); }); @@ -135,21 +134,26 @@ describe('SearchService', () => { it('should call the navigate method on the Router with view mode grid parameter as a parameter when setViewMode is called', () => { searchService.setViewMode(ViewMode.Grid); expect(router.navigate).toHaveBeenCalledWith(['/search'], { - queryParams: { view: ViewMode.Grid }, + queryParams: { view: ViewMode.Grid, page: 1 }, queryParamsHandling: 'merge' }); }); it('should return ViewMode.List when the viewMode is set to ViewMode.List in the ActivatedRoute', () => { let viewMode = ViewMode.Grid; - route.testParams = { view: ViewMode.List }; + spyOn(routeService, 'getQueryParamMap').and.returnValue(observableOf(new Map([ + [ 'view', ViewMode.List ], + ]))); + searchService.getViewMode().subscribe((mode) => viewMode = mode); expect(viewMode).toEqual(ViewMode.List); }); it('should return ViewMode.Grid when the viewMode is set to ViewMode.Grid in the ActivatedRoute', () => { let viewMode = ViewMode.List; - route.testParams = { view: ViewMode.Grid }; + spyOn(routeService, 'getQueryParamMap').and.returnValue(observableOf(new Map([ + [ 'view', ViewMode.Grid ], + ]))); searchService.getViewMode().subscribe((mode) => viewMode = mode); expect(viewMode).toEqual(ViewMode.Grid); }); diff --git a/src/app/+search-page/search-service/search.service.ts b/src/app/+search-page/search-service/search.service.ts index 2c0f1f4e55..ace98b024b 100644 --- a/src/app/+search-page/search-service/search.service.ts +++ b/src/app/+search-page/search-service/search.service.ts @@ -1,13 +1,7 @@ import { combineLatest as observableCombineLatest, Observable, of as observableOf } from 'rxjs'; import { Injectable, OnDestroy } from '@angular/core'; -import { - ActivatedRoute, - NavigationExtras, - PRIMARY_OUTLET, - Router, - UrlSegmentGroup -} from '@angular/router'; -import { map, switchMap, tap } from 'rxjs/operators'; +import { NavigationExtras, PRIMARY_OUTLET, Router, UrlSegmentGroup } from '@angular/router'; +import { first, map, switchMap } from 'rxjs/operators'; import { RemoteDataBuildService } from '../../core/cache/builders/remote-data-build.service'; import { FacetConfigSuccessResponse, @@ -23,12 +17,13 @@ import { DSpaceObject } from '../../core/shared/dspace-object.model'; import { GenericConstructor } from '../../core/shared/generic-constructor'; import { HALEndpointService } from '../../core/shared/hal-endpoint.service'; import { - configureRequest, filterSuccessfulResponses, + configureRequest, + filterSuccessfulResponses, getResponseFromEntry, getSucceededRemoteData } from '../../core/shared/operators'; import { URLCombiner } from '../../core/url-combiner/url-combiner'; -import { hasValue, isEmpty, isNotEmpty } from '../../shared/empty.util'; +import { hasValue, isEmpty, isNotEmpty, isNotUndefined } from '../../shared/empty.util'; import { NormalizedSearchResult } from '../normalized-search-result.model'; import { SearchOptions } from '../search-options.model'; import { SearchResult } from '../search-result.model'; @@ -47,6 +42,7 @@ import { CommunityDataService } from '../../core/data/community-data.service'; import { ViewMode } from '../../core/shared/view-mode.model'; import { ResourceType } from '../../core/shared/resource-type'; import { DSpaceObjectDataService } from '../../core/data/dspace-object-data.service'; +import { RouteService } from '../../shared/services/route.service'; /** * Service that performs all general actions that have to do with the search page @@ -63,13 +59,23 @@ export class SearchService implements OnDestroy { */ private facetLinkPathPrefix = 'discover/facets/'; + /** + * The ResponseParsingService constructor name + */ + private parser: GenericConstructor = SearchResponseParsingService; + + /** + * The RestRequest constructor name + */ + private request: GenericConstructor = GetRequest; + /** * Subscription to unsubscribe from */ private sub; constructor(private router: Router, - private route: ActivatedRoute, + private routeService: RouteService, protected requestService: RequestService, private rdb: RemoteDataBuildService, private halService: HALEndpointService, @@ -78,6 +84,20 @@ export class SearchService implements OnDestroy { ) { } + /** + * Method to set service options + * @param {GenericConstructor} parser The ResponseParsingService constructor name + * @param {boolean} request The RestRequest constructor name + */ + setServiceOptions(parser: GenericConstructor, request: GenericConstructor) { + if (parser) { + this.parser = parser; + } + if (request) { + this.request = request; + } + } + /** * Method to retrieve a paginated list of search results from the server * @param {PaginatedSearchOptions} searchOptions The configuration necessary to perform this search @@ -89,14 +109,17 @@ export class SearchService implements OnDestroy { if (hasValue(searchOptions)) { url = (searchOptions as PaginatedSearchOptions).toRestUrl(url); } - const request = new GetRequest(this.requestService.generateRequestId(), url); + const request = new this.request(this.requestService.generateRequestId(), url); + + const getResponseParserFn: () => GenericConstructor = () => { + return this.parser; + }; + return Object.assign(request, { - getResponseParser(): GenericConstructor { - return SearchResponseParsingService; - } + getResponseParser: getResponseParserFn }); }), - configureRequest(this.requestService) + configureRequest(this.requestService), ); const requestEntryObs = requestObs.pipe( switchMap((request: RestRequest) => this.requestService.getByHref(request.href)) @@ -112,8 +135,10 @@ export class SearchService implements OnDestroy { // Turn list of observable remote data DSO's into observable remote data object with list of DSO const dsoObs: Observable> = sqrObs.pipe( map((sqr: SearchQueryResponse) => { - return sqr.objects.map((nsr: NormalizedSearchResult) => { - return this.rdb.buildSingle(nsr.dspaceObject); + return sqr.objects + .filter((nsr: NormalizedSearchResult) => isNotUndefined(nsr.indexableObject)) + .map((nsr: NormalizedSearchResult) => { + return this.rdb.buildSingle(nsr.indexableObject); }) }), switchMap((input: Array>>) => this.rdb.aggregate(input)), @@ -126,9 +151,9 @@ export class SearchService implements OnDestroy { let co = DSpaceObject; if (dsos.payload[index]) { const constructor: GenericConstructor = dsos.payload[index].constructor as GenericConstructor; - co = getSearchResultFor(constructor); + co = getSearchResultFor(constructor, searchOptions.configuration); return Object.assign(new co(), object, { - dspaceObject: dsos.payload[index] + indexableObject: dsos.payload[index] }); } else { return undefined; @@ -154,9 +179,10 @@ export class SearchService implements OnDestroy { /** * Request the filter configuration for a given scope or the whole repository * @param {string} scope UUID of the object for which config the filter config is requested, when no scope is provided the configuration for the whole repository is loaded + * @param {string} configurationName the name of the configuration * @returns {Observable>} The found filter configuration */ - getConfig(scope?: string): Observable> { + getConfig(scope?: string, configurationName?: string): Observable> { const requestObs = this.halService.getEndpoint(this.facetLinkPathPrefix).pipe( map((url: string) => { const args: string[] = []; @@ -165,11 +191,15 @@ export class SearchService implements OnDestroy { args.push(`scope=${scope}`); } + if (isNotEmpty(configurationName)) { + args.push(`configuration=${configurationName}`); + } + if (isNotEmpty(args)) { url = new URLCombiner(url, `?${args.join('&')}`).toString(); } - const request = new GetRequest(this.requestService.generateRequestId(), url); + const request = new this.request(this.requestService.generateRequestId(), url); return Object.assign(request, { getResponseParser(): GenericConstructor { return FacetConfigResponseParsingService; @@ -212,14 +242,15 @@ export class SearchService implements OnDestroy { url = searchOptions.toRestUrl(url, args); } - const request = new GetRequest(this.requestService.generateRequestId(), url); + const request = new this.request(this.requestService.generateRequestId(), url); return Object.assign(request, { getResponseParser(): GenericConstructor { return FacetValueResponseParsingService; } }); }), - configureRequest(this.requestService) + configureRequest(this.requestService), + first() ); const requestEntryObs = requestObs.pipe( @@ -288,9 +319,9 @@ export class SearchService implements OnDestroy { * @returns {Observable} The current view mode */ getViewMode(): Observable { - return this.route.queryParams.pipe(map((params) => { - if (isNotEmpty(params.view) && hasValue(params.view)) { - return params.view; + return this.routeService.getQueryParamMap().pipe(map((params) => { + if (isNotEmpty(params.get('view')) && hasValue(params.get('view'))) { + return params.get('view'); } else { return ViewMode.List; } @@ -302,12 +333,21 @@ export class SearchService implements OnDestroy { * @param {ViewMode} viewMode Mode to switch to */ setViewMode(viewMode: ViewMode) { - const navigationExtras: NavigationExtras = { - queryParams: { view: viewMode }, - queryParamsHandling: 'merge' - }; + this.routeService.getQueryParameterValue('pageSize').pipe(first()) + .subscribe((pageSize) => { + let queryParams = { view: viewMode, page: 1 }; + if (viewMode === ViewMode.Detail) { + queryParams = Object.assign(queryParams, {pageSize: '1'}); + } else if (pageSize === '1') { + queryParams = Object.assign(queryParams, {pageSize: '10'}); + } + const navigationExtras: NavigationExtras = { + queryParams: queryParams, + queryParamsHandling: 'merge' + }; - this.router.navigate([this.getSearchLink()], navigationExtras); + this.router.navigate([this.getSearchLink()], navigationExtras); + }) } /** @@ -316,7 +356,8 @@ export class SearchService implements OnDestroy { getSearchLink(): string { const urlTree = this.router.parseUrl(this.router.url); const g: UrlSegmentGroup = urlTree.root.children[PRIMARY_OUTLET]; - return '/' + g.toString(); + const searchLink: any = '/' + g.toString(); + return (searchLink !== '/search' && searchLink !== '/mydspace') ? '/search' : searchLink; } /** diff --git a/src/app/+search-page/search-settings/search-settings.component.spec.ts b/src/app/+search-page/search-settings/search-settings.component.spec.ts index b1585c4347..b9b5c5a5eb 100644 --- a/src/app/+search-page/search-settings/search-settings.component.spec.ts +++ b/src/app/+search-page/search-settings/search-settings.component.spec.ts @@ -14,8 +14,8 @@ import { By } from '@angular/platform-browser'; import { SearchFilterService } from '../search-filters/search-filter/search-filter.service'; import { hot } from 'jasmine-marbles'; import { VarDirective } from '../../shared/utils/var.directive'; -import { SearchConfigurationService } from '../search-service/search-configuration.service'; import { first } from 'rxjs/operators'; +import { SEARCH_CONFIG_SERVICE } from '../../+my-dspace-page/my-dspace-page.component'; describe('SearchSettingsComponent', () => { @@ -73,7 +73,7 @@ describe('SearchSettingsComponent', () => { useValue: {} }, { - provide: SearchConfigurationService, + provide: SEARCH_CONFIG_SERVICE, useValue: { paginatedSearchOptions: hot('a', { a: paginatedSearchOptions diff --git a/src/app/+search-page/search-settings/search-settings.component.ts b/src/app/+search-page/search-settings/search-settings.component.ts index f25545eddf..d26545b7f1 100644 --- a/src/app/+search-page/search-settings/search-settings.component.ts +++ b/src/app/+search-page/search-settings/search-settings.component.ts @@ -1,10 +1,11 @@ -import { Component, OnInit } from '@angular/core'; +import { Component, Inject, OnInit } from '@angular/core'; import { SearchService } from '../search-service/search.service'; import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model'; import { ActivatedRoute, NavigationExtras, Router } from '@angular/router'; import { PaginatedSearchOptions } from '../paginated-search-options.model'; import { Observable } from 'rxjs'; import { SearchConfigurationService } from '../search-service/search-configuration.service'; +import { SEARCH_CONFIG_SERVICE } from '../../+my-dspace-page/my-dspace-page.component'; @Component({ selector: 'ds-search-settings', @@ -30,7 +31,7 @@ export class SearchSettingsComponent implements OnInit { constructor(private service: SearchService, private route: ActivatedRoute, private router: Router, - private searchConfigurationService: SearchConfigurationService) { + @Inject(SEARCH_CONFIG_SERVICE) public searchConfigurationService: SearchConfigurationService) { } /** diff --git a/src/app/+search-page/search-sidebar/search-sidebar.component.html b/src/app/+search-page/search-sidebar/search-sidebar.component.html index 5ff1e3c8fa..3934f8cdac 100644 --- a/src/app/+search-page/search-sidebar/search-sidebar.component.html +++ b/src/app/+search-page/search-sidebar/search-sidebar.component.html @@ -8,8 +8,9 @@ - + + diff --git a/src/app/+search-page/search-sidebar/search-sidebar.component.scss b/src/app/+search-page/search-sidebar/search-sidebar.component.scss index b5bd6dd30d..35ce5eebce 100644 --- a/src/app/+search-page/search-sidebar/search-sidebar.component.scss +++ b/src/app/+search-page/search-sidebar/search-sidebar.component.scss @@ -8,8 +8,12 @@ ds-view-mode-switch { margin-bottom: $spacer; } - .sidebar-content > *:not(:last-child) { + .sidebar-content > *:not(:last-child):not(ds-search-switch-configuration) { margin-bottom: 4*$spacer; display: block; } + ds-search-switch-configuration { + margin-bottom: 2*$spacer; + display: block; + } } diff --git a/src/app/+search-page/search-sidebar/search-sidebar.component.ts b/src/app/+search-page/search-sidebar/search-sidebar.component.ts index 8b68cda793..9abcf71dcb 100644 --- a/src/app/+search-page/search-sidebar/search-sidebar.component.ts +++ b/src/app/+search-page/search-sidebar/search-sidebar.component.ts @@ -1,5 +1,7 @@ import { Component, EventEmitter, Input, Output } from '@angular/core'; +import { SearchConfigurationOption } from '../search-switch-configuration/search-configuration-option.model'; + /** * This component renders a simple item page. * The route parameter 'id' is used to request the item it represents. @@ -17,11 +19,21 @@ import { Component, EventEmitter, Input, Output } from '@angular/core'; */ export class SearchSidebarComponent { + /** + * The list of available configuration options + */ + @Input() configurationList: SearchConfigurationOption[]; + /** * The total amount of results */ @Input() resultCount; + /** + * The list of available view mode options + */ + @Input() viewModeList; + /** * Emits event when the user clicks a button to open or close the sidebar */ diff --git a/src/app/+search-page/search-switch-configuration/search-configuration-option.model.ts b/src/app/+search-page/search-switch-configuration/search-configuration-option.model.ts new file mode 100644 index 0000000000..6f9a72da48 --- /dev/null +++ b/src/app/+search-page/search-switch-configuration/search-configuration-option.model.ts @@ -0,0 +1,15 @@ +/** + * Represents a search configuration select option + */ +export interface SearchConfigurationOption { + + /** + * The select option value + */ + value: string; + + /** + * The select option label + */ + label: string; +} diff --git a/src/app/+search-page/search-switch-configuration/search-switch-configuration.component.html b/src/app/+search-page/search-switch-configuration/search-switch-configuration.component.html new file mode 100644 index 0000000000..8df37214d1 --- /dev/null +++ b/src/app/+search-page/search-switch-configuration/search-switch-configuration.component.html @@ -0,0 +1,13 @@ + 1" class="search-switch-configuration"> + {{ 'search.switch-configuration.title' | translate}} + + + + {{option.label | translate}} + + + + diff --git a/src/app/+search-page/search-switch-configuration/search-switch-configuration.component.scss b/src/app/+search-page/search-switch-configuration/search-switch-configuration.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/+search-page/search-switch-configuration/search-switch-configuration.component.spec.ts b/src/app/+search-page/search-switch-configuration/search-switch-configuration.component.spec.ts new file mode 100644 index 0000000000..b3efc240e1 --- /dev/null +++ b/src/app/+search-page/search-switch-configuration/search-switch-configuration.component.spec.ts @@ -0,0 +1,109 @@ +import { NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { By } from '@angular/platform-browser'; + +import { of as observableOf } from 'rxjs'; +import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; + +import { SearchSwitchConfigurationComponent } from './search-switch-configuration.component'; +import { MYDSPACE_ROUTE, SEARCH_CONFIG_SERVICE } from '../../+my-dspace-page/my-dspace-page.component'; +import { SearchConfigurationServiceStub } from '../../shared/testing/search-configuration-service-stub'; +import { MockTranslateLoader } from '../../shared/mocks/mock-translate-loader'; +import { NavigationExtras, Router } from '@angular/router'; +import { RouterStub } from '../../shared/testing/router-stub'; +import { MyDSpaceConfigurationValueType } from '../../+my-dspace-page/my-dspace-configuration-value-type'; +import { SearchService } from '../search-service/search.service'; + +describe('SearchSwitchConfigurationComponent', () => { + + let comp: SearchSwitchConfigurationComponent; + let fixture: ComponentFixture; + let searchConfService: SearchConfigurationServiceStub; + let select: any; + + const searchServiceStub = jasmine.createSpyObj('SearchService', { + getSearchLink: jasmine.createSpy('getSearchLink') + }); + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }) + ], + declarations: [ SearchSwitchConfigurationComponent ], + providers: [ + { provide: Router, useValue: new RouterStub() }, + { provide: SearchService, useValue: searchServiceStub }, + { provide: SEARCH_CONFIG_SERVICE, useValue: new SearchConfigurationServiceStub() }, + ], + schemas: [ NO_ERRORS_SCHEMA ] + }).compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(SearchSwitchConfigurationComponent); + comp = fixture.componentInstance; + searchConfService = TestBed.get(SEARCH_CONFIG_SERVICE); + + spyOn(searchConfService, 'getCurrentConfiguration').and.returnValue(observableOf(MyDSpaceConfigurationValueType.Workspace)); + + comp.configurationList = [ + { + value: MyDSpaceConfigurationValueType.Workspace, + label: 'workspace' + }, + { + value: MyDSpaceConfigurationValueType.Workflow, + label: 'workflow' + }, + ]; + + // SearchSwitchConfigurationComponent test instance + fixture.detectChanges(); + + }); + + it('should init the current configuration name', () => { + expect(comp.selectedOption).toBe(MyDSpaceConfigurationValueType.Workspace); + }); + + it('should display select field properly', () => { + const selectField = fixture.debugElement.query(By.css('.form-control')); + expect(selectField).toBeDefined(); + + const childElements = selectField.children; + expect(childElements.length).toEqual(comp.configurationList.length); + }); + + it('should call onSelect method when selecting an option', () => { + fixture.whenStable().then(() => { + spyOn(comp, 'onSelect'); + select = fixture.debugElement.query(By.css('select')); + const selectEl = select.nativeElement; + selectEl.value = selectEl.options[1].value; // <-- select a new value + selectEl.dispatchEvent(new Event('change')); + fixture.detectChanges(); + expect(comp.onSelect).toHaveBeenCalled(); + }); + + }); + + it('should navigate to the route when selecting an option', () => { + (comp as any).searchService.getSearchLink.and.returnValue(MYDSPACE_ROUTE); + comp.selectedOption = MyDSpaceConfigurationValueType.Workflow; + const navigationExtras: NavigationExtras = { + queryParams: {configuration: MyDSpaceConfigurationValueType.Workflow}, + }; + + fixture.detectChanges(); + + comp.onSelect(); + + expect((comp as any).router.navigate).toHaveBeenCalledWith([MYDSPACE_ROUTE], navigationExtras); + }); +}); diff --git a/src/app/+search-page/search-switch-configuration/search-switch-configuration.component.ts b/src/app/+search-page/search-switch-configuration/search-switch-configuration.component.ts new file mode 100644 index 0000000000..c34fe20303 --- /dev/null +++ b/src/app/+search-page/search-switch-configuration/search-switch-configuration.component.ts @@ -0,0 +1,80 @@ +import { Component, Inject, Input, OnDestroy, OnInit } from '@angular/core'; +import { NavigationExtras, Router } from '@angular/router'; + +import { Subscription } from 'rxjs'; + +import { hasValue } from '../../shared/empty.util'; +import { SEARCH_CONFIG_SERVICE } from '../../+my-dspace-page/my-dspace-page.component'; +import { SearchConfigurationService } from '../search-service/search-configuration.service'; +import { MyDSpaceConfigurationValueType } from '../../+my-dspace-page/my-dspace-configuration-value-type'; +import { SearchConfigurationOption } from './search-configuration-option.model'; +import { SearchService } from '../search-service/search.service'; + +@Component({ + selector: 'ds-search-switch-configuration', + styleUrls: ['./search-switch-configuration.component.scss'], + templateUrl: './search-switch-configuration.component.html', +}) +/** + * Represents a select that allow to switch over available search configurations + */ +export class SearchSwitchConfigurationComponent implements OnDestroy, OnInit { + + /** + * The list of available configuration options + */ + @Input() configurationList: SearchConfigurationOption[] = []; + + /** + * The selected option + */ + public selectedOption: string; + + /** + * Subscription to unsubscribe from + */ + private sub: Subscription; + + constructor(private router: Router, + private searchService: SearchService, + @Inject(SEARCH_CONFIG_SERVICE) private searchConfigService: SearchConfigurationService) { + } + + /** + * Init current configuration + */ + ngOnInit() { + this.searchConfigService.getCurrentConfiguration('default') + .subscribe((currentConfiguration) => this.selectedOption = currentConfiguration); + } + + /** + * Init current configuration + */ + onSelect() { + const navigationExtras: NavigationExtras = { + queryParams: {configuration: this.selectedOption}, + }; + + this.router.navigate([this.searchService.getSearchLink()], navigationExtras); + } + + /** + * Define the select 'compareWith' method to tell Angular how to compare the values + * + * @param item1 + * @param item2 + */ + compare(item1: MyDSpaceConfigurationValueType, item2: MyDSpaceConfigurationValueType) { + return item1 === item2; + } + + /** + * Make sure the subscription is unsubscribed from when this component is destroyed + */ + ngOnDestroy() { + if (hasValue(this.sub)) { + this.sub.unsubscribe(); + } + } +} diff --git a/src/app/app-routing.module.ts b/src/app/app-routing.module.ts index be956ee895..cb80d0165e 100644 --- a/src/app/app-routing.module.ts +++ b/src/app/app-routing.module.ts @@ -24,6 +24,7 @@ export function getCommunityModulePath() { { path: COMMUNITY_MODULE_PATH, loadChildren: './+community-page/community-page.module#CommunityPageModule' }, { path: COLLECTION_MODULE_PATH, loadChildren: './+collection-page/collection-page.module#CollectionPageModule' }, { path: ITEM_MODULE_PATH, loadChildren: './+item-page/item-page.module#ItemPageModule' }, + { path: 'mydspace', loadChildren: './+my-dspace-page/my-dspace-page.module#MyDSpacePageModule', canActivate: [AuthenticatedGuard] }, { path: 'search', loadChildren: './+search-page/search-page.module#SearchPageModule' }, { path: 'browse', loadChildren: './+browse-by/browse-by.module#BrowseByModule' }, { path: 'admin', loadChildren: './+admin/admin.module#AdminModule', canActivate: [AuthenticatedGuard] }, diff --git a/src/app/core/auth/auth-request.service.ts b/src/app/core/auth/auth-request.service.ts index 14784d1b55..cbabe5c3fd 100644 --- a/src/app/core/auth/auth-request.service.ts +++ b/src/app/core/auth/auth-request.service.ts @@ -6,18 +6,10 @@ import { RequestService } from '../data/request.service'; import { GLOBAL_CONFIG } from '../../../config'; import { GlobalConfig } from '../../../config/global-config.interface'; import { isNotEmpty } from '../../shared/empty.util'; -import { - AuthGetRequest, - AuthPostRequest, - GetRequest, - PostRequest, - RestRequest -} from '../data/request.models'; +import { AuthGetRequest, AuthPostRequest, GetRequest, PostRequest, RestRequest } from '../data/request.models'; import { AuthStatusResponse, ErrorResponse } from '../cache/response.models'; import { HttpOptions } from '../dspace-rest-v2/dspace-rest-v2.service'; -import { RequestEntry } from '../data/request.reducer'; import { getResponseFromEntry } from '../shared/operators'; -import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; @Injectable() export class AuthRequestService { diff --git a/src/app/core/auth/auth-response-parsing.service.ts b/src/app/core/auth/auth-response-parsing.service.ts index 1993f6d162..c736c3b22b 100644 --- a/src/app/core/auth/auth-response-parsing.service.ts +++ b/src/app/core/auth/auth-response-parsing.service.ts @@ -14,7 +14,6 @@ import { AuthType } from './auth-type'; import { AuthStatus } from './models/auth-status.model'; import { NormalizedAuthStatus } from './models/normalized-auth-status.model'; import { NormalizedObject } from '../cache/models/normalized-object.model'; -import { DSpaceObject } from '../shared/dspace-object.model'; @Injectable() export class AuthResponseParsingService extends BaseResponseParsingService implements ResponseParsingService { diff --git a/src/app/core/auth/auth.service.spec.ts b/src/app/core/auth/auth.service.spec.ts index ebb4026265..e766a45e48 100644 --- a/src/app/core/auth/auth.service.spec.ts +++ b/src/app/core/auth/auth.service.spec.ts @@ -43,7 +43,7 @@ describe('AuthService test', () => { pipe: observableOf(true) }); window = new NativeWindowRef(); - routerStub = new RouterStub() + routerStub = new RouterStub(); token = new AuthTokenInfo('test_token'); token.expires = Date.now() + (1000 * 60 * 60); authenticatedState = { diff --git a/src/app/core/auth/auth.service.ts b/src/app/core/auth/auth.service.ts index 7874eebea8..a01768e687 100644 --- a/src/app/core/auth/auth.service.ts +++ b/src/app/core/auth/auth.service.ts @@ -1,43 +1,27 @@ -import {Observable, of, of as observableOf} from 'rxjs'; -import { - distinctUntilChanged, - filter, - first, - map, - startWith, - switchMap, - take, - withLatestFrom -} from 'rxjs/operators'; import { Inject, Injectable, Optional } from '@angular/core'; import { PRIMARY_OUTLET, Router, UrlSegmentGroup, UrlTree } from '@angular/router'; import { HttpHeaders } from '@angular/common/http'; import { REQUEST, RESPONSE } from '@nguniversal/express-engine/tokens'; +import { Observable, of as observableOf } from 'rxjs'; +import { distinctUntilChanged, filter, map, startWith, switchMap, take, withLatestFrom } from 'rxjs/operators'; import { RouterReducerState } from '@ngrx/router-store'; import { select, Store } from '@ngrx/store'; import { CookieAttributes } from 'js-cookie'; import { EPerson } from '../eperson/models/eperson.model'; import { AuthRequestService } from './auth-request.service'; - import { HttpOptions } from '../dspace-rest-v2/dspace-rest-v2.service'; import { AuthStatus } from './models/auth-status.model'; import { AuthTokenInfo, TOKENITEM } from './models/auth-token-info.model'; import { isEmpty, isNotEmpty, isNotNull, isNotUndefined } from '../../shared/empty.util'; import { CookieService } from '../../shared/services/cookie.service'; -import { - getAuthenticationToken, - getRedirectUrl, - isAuthenticated, - isTokenRefreshing -} from './selectors'; +import { getAuthenticationToken, getRedirectUrl, isAuthenticated, isTokenRefreshing } from './selectors'; import { AppState, routerStateSelector } from '../../app.reducer'; import { ResetAuthenticationMessagesAction, SetRedirectUrlAction } from './auth.actions'; import { NativeWindowRef, NativeWindowService } from '../../shared/services/window.service'; import { Base64EncodeUrl } from '../../shared/utils/encode-decode.util'; import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; -import { NormalizedEPerson } from '../eperson/models/normalized-eperson.model'; export const LOGIN_ROUTE = '/login'; export const LOGOUT_ROUTE = '/logout'; diff --git a/src/app/core/auth/selectors.ts b/src/app/core/auth/selectors.ts index fa637981ae..8c88e0fce5 100644 --- a/src/app/core/auth/selectors.ts +++ b/src/app/core/auth/selectors.ts @@ -8,6 +8,7 @@ import { createSelector } from '@ngrx/store'; */ import { AuthState } from './auth.reducer'; import { AppState } from '../../app.reducer'; +import { EPerson } from '../eperson/models/eperson.model'; /** * Returns the user state. @@ -35,11 +36,12 @@ const _isAuthenticatedLoaded = (state: AuthState) => state.loaded; /** * Return the users state + * NOTE: when state is REHYDRATED user object lose prototype so return always a new EPerson object * @function _getAuthenticatedUser * @param {State} state - * @returns {User} + * @returns {EPerson} */ -const _getAuthenticatedUser = (state: AuthState) => state.user; +const _getAuthenticatedUser = (state: AuthState) => Object.assign(new EPerson(), state.user); /** * Returns the authentication error. diff --git a/src/app/core/cache/models/normalized-object-factory.ts b/src/app/core/cache/models/normalized-object-factory.ts index f4d575b8b2..aa1f6f2958 100644 --- a/src/app/core/cache/models/normalized-object-factory.ts +++ b/src/app/core/cache/models/normalized-object-factory.ts @@ -15,13 +15,14 @@ import { NormalizedWorkspaceItem } from '../../submission/models/normalized-work import { NormalizedEPerson } from '../../eperson/models/normalized-eperson.model'; import { NormalizedGroup } from '../../eperson/models/normalized-group.model'; import { NormalizedWorkflowItem } from '../../submission/models/normalized-workflowitem.model'; +import { NormalizedClaimedTask } from '../../tasks/models/normalized-claimed-task-object.model'; +import { NormalizedPoolTask } from '../../tasks/models/normalized-pool-task-object.model'; import { NormalizedBitstreamFormat } from './normalized-bitstream-format.model'; import { NormalizedMetadataSchema } from '../../metadata/normalized-metadata-schema.model'; import { CacheableObject } from '../object-cache.reducer'; import { NormalizedSubmissionDefinitionsModel } from '../../config/models/normalized-config-submission-definitions.model'; import { NormalizedSubmissionFormsModel } from '../../config/models/normalized-config-submission-forms.model'; import { NormalizedSubmissionSectionModel } from '../../config/models/normalized-config-submission-section.model'; -import { NormalizedAuthStatus } from '../../auth/models/normalized-auth-status.model'; export class NormalizedObjectFactory { public static getConstructor(type: ResourceType): GenericConstructor> { @@ -77,6 +78,12 @@ export class NormalizedObjectFactory { case ResourceType.Workflowitem: { return NormalizedWorkflowItem } + case ResourceType.ClaimedTask: { + return NormalizedClaimedTask + } + case ResourceType.PoolTask: { + return NormalizedPoolTask + } case ResourceType.SubmissionDefinition: case ResourceType.SubmissionDefinitions: { return NormalizedSubmissionDefinitionsModel diff --git a/src/app/core/cache/object-cache.service.spec.ts b/src/app/core/cache/object-cache.service.spec.ts index eae7c06be7..20e12108ad 100644 --- a/src/app/core/cache/object-cache.service.spec.ts +++ b/src/app/core/cache/object-cache.service.spec.ts @@ -1,18 +1,19 @@ +import * as ngrx from '@ngrx/store'; import { Store } from '@ngrx/store'; import { of as observableOf } from 'rxjs'; import { ObjectCacheService } from './object-cache.service'; import { AddPatchObjectCacheAction, - AddToObjectCacheAction, ApplyPatchObjectCacheAction, + AddToObjectCacheAction, + ApplyPatchObjectCacheAction, RemoveFromObjectCacheAction } from './object-cache.actions'; import { CoreState } from '../core.reducers'; import { ResourceType } from '../shared/resource-type'; import { NormalizedItem } from './models/normalized-item.model'; import { first } from 'rxjs/operators'; -import * as ngrx from '@ngrx/store'; -import { Operation } from '../../../../node_modules/fast-json-patch'; +import { Operation } from 'fast-json-patch'; import { RestRequestMethod } from '../data/rest-request-method'; import { AddToSSBAction } from './server-sync-buffer.actions'; import { Patch } from './object-cache.reducer'; diff --git a/src/app/core/cache/object-cache.service.ts b/src/app/core/cache/object-cache.service.ts index 483de65b98..e6384571c3 100644 --- a/src/app/core/cache/object-cache.service.ts +++ b/src/app/core/cache/object-cache.service.ts @@ -4,7 +4,7 @@ import { applyPatch, Operation } from 'fast-json-patch'; import { combineLatest as observableCombineLatest, Observable } from 'rxjs'; import { distinctUntilChanged, filter, map, mergeMap, take, } from 'rxjs/operators'; -import { hasNoValue, hasValue, isNotEmpty } from '../../shared/empty.util'; +import { hasNoValue, isNotEmpty } from '../../shared/empty.util'; import { CoreState } from '../core.reducers'; import { coreSelector } from '../core.selectors'; import { RestRequestMethod } from '../data/rest-request-method'; diff --git a/src/app/core/cache/response.models.ts b/src/app/core/cache/response.models.ts index 52bf9a9275..b3523addc5 100644 --- a/src/app/core/cache/response.models.ts +++ b/src/app/core/cache/response.models.ts @@ -8,7 +8,6 @@ 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 { AuthStatus } from '../auth/models/auth-status.model'; import { MetadataSchema } from '../metadata/metadataschema.model'; import { MetadataField } from '../metadata/metadatafield.model'; import { PaginatedList } from '../data/paginated-list'; @@ -255,6 +254,30 @@ export class EpersonSuccessResponse extends RestResponse { } } +export class MessageResponse extends RestResponse { + public toCache = false; + + constructor( + public statusCode: number, + public statusText: string, + public pageInfo?: PageInfo + ) { + super(true, statusCode, statusText); + } +} + +export class TaskResponse extends RestResponse { + public toCache = false; + + constructor( + public statusCode: number, + public statusText: string, + public pageInfo?: PageInfo + ) { + super(true, statusCode, statusText); + } +} + export class FilteredDiscoveryQueryResponse extends RestResponse { constructor( public filterQuery: string, diff --git a/src/app/core/core.module.ts b/src/app/core/core.module.ts index 20ae0401cc..6550435aa3 100644 --- a/src/app/core/core.module.ts +++ b/src/app/core/core.module.ts @@ -81,6 +81,12 @@ import { DSOChangeAnalyzer } from './data/dso-change-analyzer.service'; import { ObjectUpdatesService } from './data/object-updates/object-updates.service'; import { DefaultChangeAnalyzer } from './data/default-change-analyzer.service'; import { SearchService } from '../+search-page/search-service/search.service'; +import { RoleService } from './roles/role.service'; +import { MyDSpaceGuard } from '../+my-dspace-page/my-dspace.guard'; +import { MyDSpaceResponseParsingService } from './data/mydspace-response-parsing.service'; +import { ClaimedTaskDataService } from './tasks/claimed-task-data.service'; +import { PoolTaskDataService } from './tasks/pool-task-data.service'; +import { TaskResponseParsingService } from './tasks/task-response-parsing.service'; const IMPORTS = [ CommonModule, @@ -132,6 +138,7 @@ const PROVIDERS = [ RegistryBitstreamformatsResponseParsingService, DebugResponseParsingService, SearchResponseParsingService, + MyDSpaceResponseParsingService, ServerResponseService, BrowseResponseParsingService, BrowseEntriesResponseParsingService, @@ -163,6 +170,11 @@ const PROVIDERS = [ MenuService, ObjectUpdatesService, SearchService, + MyDSpaceGuard, + RoleService, + TaskResponseParsingService, + ClaimedTaskDataService, + PoolTaskDataService, // register AuthInterceptor as HttpInterceptor { provide: HTTP_INTERCEPTORS, diff --git a/src/app/core/data/base-response-parsing.service.ts b/src/app/core/data/base-response-parsing.service.ts index 1b804701d3..4ede02778c 100644 --- a/src/app/core/data/base-response-parsing.service.ts +++ b/src/app/core/data/base-response-parsing.service.ts @@ -6,9 +6,8 @@ import { ObjectCacheService } from '../cache/object-cache.service'; import { GlobalConfig } from '../../../config/global-config.interface'; import { GenericConstructor } from '../shared/generic-constructor'; import { PaginatedList } from './paginated-list'; -import { ResourceType } from '../shared/resource-type'; -import { RESTURLCombiner } from '../url-combiner/rest-url-combiner'; import { isRestDataObject, isRestPaginatedList } from '../cache/builders/normalized-object-build.service'; + /* tslint:disable:max-classes-per-file */ export abstract class BaseResponseParsingService { @@ -142,4 +141,8 @@ export abstract class BaseResponseParsingService { protected retrieveObjectOrUrl(obj: any): any { return this.toCache ? obj.self : obj; } + + protected isSuccessStatus(statusCode: number) { + return statusCode >= 200 && statusCode < 300; + } } diff --git a/src/app/core/data/collection-data.service.ts b/src/app/core/data/collection-data.service.ts index 3d03b9397d..993954a360 100644 --- a/src/app/core/data/collection-data.service.ts +++ b/src/app/core/data/collection-data.service.ts @@ -1,7 +1,9 @@ import { Injectable } from '@angular/core'; + +import { filter, map, take } from 'rxjs/operators'; import { Store } from '@ngrx/store'; + import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; -import { NormalizedCollection } from '../cache/models/normalized-collection.model'; import { ObjectCacheService } from '../cache/object-cache.service'; import { CoreState } from '../core.reducers'; import { Collection } from '../shared/collection.model'; @@ -13,6 +15,10 @@ import { NotificationsService } from '../../shared/notifications/notifications.s import { HttpClient } from '@angular/common/http'; import { NormalizedObjectBuildService } from '../cache/builders/normalized-object-build.service'; import { DSOChangeAnalyzer } from './dso-change-analyzer.service'; +import { Observable } from 'rxjs/internal/Observable'; +import { FindAllOptions } from './request.models'; +import { RemoteData } from './remote-data'; +import { PaginatedList } from './paginated-list'; @Injectable() export class CollectionDataService extends ComColDataService { @@ -34,4 +40,21 @@ export class CollectionDataService extends ComColDataService { super(); } + /** + * Find whether there is a collection whom user has authorization to submit to + * + * @return boolean + * true if the user has at least one collection to submit to + */ + hasAuthorizedCollection(): Observable { + const searchHref = 'findAuthorized'; + const options = new FindAllOptions(); + options.elementsPerPage = 1; + + return this.searchBy(searchHref, options).pipe( + filter((collections: RemoteData>) => !collections.isResponsePending), + take(1), + map((collections: RemoteData>) => collections.payload.totalElements > 0) + ); + } } diff --git a/src/app/core/data/community-data.service.ts b/src/app/core/data/community-data.service.ts index 75ef58b06b..8db4d762eb 100644 --- a/src/app/core/data/community-data.service.ts +++ b/src/app/core/data/community-data.service.ts @@ -1,9 +1,8 @@ -import { filter, mergeMap, take } from 'rxjs/operators'; +import { filter, take } from 'rxjs/operators'; import { Injectable } from '@angular/core'; import { Store } from '@ngrx/store'; import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; -import { NormalizedCommunity } from '../cache/models/normalized-community.model'; import { ObjectCacheService } from '../cache/object-cache.service'; import { CoreState } from '../core.reducers'; import { Community } from '../shared/community.model'; @@ -12,7 +11,7 @@ import { RequestService } from './request.service'; import { HALEndpointService } from '../shared/hal-endpoint.service'; import { FindAllOptions, FindAllRequest } from './request.models'; import { RemoteData } from './remote-data'; -import { hasValue, isNotEmpty } from '../../shared/empty.util'; +import { hasValue } from '../../shared/empty.util'; import { Observable } from 'rxjs'; import { PaginatedList } from './paginated-list'; import { NotificationsService } from '../../shared/notifications/notifications.service'; diff --git a/src/app/core/data/data.service.spec.ts b/src/app/core/data/data.service.spec.ts index 4a244db24f..dede6f8ae2 100644 --- a/src/app/core/data/data.service.spec.ts +++ b/src/app/core/data/data.service.spec.ts @@ -9,13 +9,12 @@ import { Observable, of as observableOf } from 'rxjs'; import { FindAllOptions } from './request.models'; import { SortDirection, SortOptions } from '../cache/models/sort-options.model'; import { ObjectCacheService } from '../cache/object-cache.service'; -import { Operation } from '../../../../node_modules/fast-json-patch'; +import { compare, Operation } from 'fast-json-patch'; import { DSpaceObject } from '../shared/dspace-object.model'; import { ChangeAnalyzer } from './change-analyzer'; import { HttpClient } from '@angular/common/http'; import { NormalizedObjectBuildService } from '../cache/builders/normalized-object-build.service'; import { NotificationsService } from '../../shared/notifications/notifications.service'; -import { compare } from 'fast-json-patch'; import { Item } from '../shared/item.model'; const endpoint = 'https://rest.api/core'; diff --git a/src/app/core/data/default-change-analyzer.service.ts b/src/app/core/data/default-change-analyzer.service.ts index 1fd207d2bf..cd30479f6d 100644 --- a/src/app/core/data/default-change-analyzer.service.ts +++ b/src/app/core/data/default-change-analyzer.service.ts @@ -1,9 +1,7 @@ import { Operation } from 'fast-json-patch/lib/core'; import { compare } from 'fast-json-patch'; import { ChangeAnalyzer } from './change-analyzer'; -import { NormalizedDSpaceObject } from '../cache/models/normalized-dspace-object.model'; import { Injectable } from '@angular/core'; -import { DSpaceObject } from '../shared/dspace-object.model'; import { CacheableObject } from '../cache/object-cache.reducer'; import { NormalizedObject } from '../cache/models/normalized-object.model'; diff --git a/src/app/core/data/mydspace-response-parsing.service.ts b/src/app/core/data/mydspace-response-parsing.service.ts new file mode 100644 index 0000000000..a6945e27b4 --- /dev/null +++ b/src/app/core/data/mydspace-response-parsing.service.ts @@ -0,0 +1,82 @@ +import { Injectable } from '@angular/core'; +import { RestResponse, SearchSuccessResponse } from '../cache/response.models'; +import { DSOResponseParsingService } from './dso-response-parsing.service'; +import { ResponseParsingService } from './parsing.service'; +import { RestRequest } from './request.models'; +import { DSpaceRESTV2Response } from '../dspace-rest-v2/dspace-rest-v2-response.model'; +import { DSpaceRESTv2Serializer } from '../dspace-rest-v2/dspace-rest-v2.serializer'; +import { hasValue } from '../../shared/empty.util'; +import { SearchQueryResponse } from '../../+search-page/search-service/search-query-response.model'; +import { MetadataMap, MetadataValue } from '../shared/metadata.models'; + +@Injectable() +export class MyDSpaceResponseParsingService implements ResponseParsingService { + constructor(private dsoParser: DSOResponseParsingService) { + } + + parse(request: RestRequest, data: DSpaceRESTV2Response): RestResponse { + // fallback for unexpected empty response + const emptyPayload = { + _embedded: { + objects: [] + } + }; + const payload = data.payload._embedded.searchResult || emptyPayload; + const hitHighlights: MetadataMap[] = payload._embedded.objects + .map((object) => object.hitHighlights) + .map((hhObject) => { + const mdMap: MetadataMap = {}; + if (hhObject) { + for (const key of Object.keys(hhObject)) { + const value: MetadataValue = Object.assign(new MetadataValue(), { + value: hhObject[key].join('...'), + language: null + }); + mdMap[key] = [value]; + } + } + return mdMap; + }); + + const dsoSelfLinks = payload._embedded.objects + .filter((object) => hasValue(object._embedded)) + .map((object) => object._embedded.indexableObject) + .map((dso) => this.dsoParser.parse(request, { + payload: dso, + statusCode: data.statusCode, + statusText: data.statusText + })) + .map((obj) => obj.resourceSelfLinks) + .reduce((combined, thisElement) => [...combined, ...thisElement], []); + + const objects = payload._embedded.objects + .filter((object) => hasValue(object._embedded)) + .map((object, index) => Object.assign({}, object, { + indexableObject: dsoSelfLinks[index], + hitHighlights: hitHighlights[index], + _embedded: this.filterEmbeddedObjects(object) + })); + payload.objects = objects; + const deserialized = new DSpaceRESTv2Serializer(SearchQueryResponse).deserialize(payload); + return new SearchSuccessResponse(deserialized, data.statusCode, data.statusText, this.dsoParser.processPageInfo(payload)); + } + + protected filterEmbeddedObjects(object) { + const allowedEmbeddedKeys = ['submitter', 'item', 'workspaceitem', 'workflowitem']; + if (object._embedded.indexableObject && object._embedded.indexableObject._embedded) { + return Object.assign({}, object._embedded, { + indexableObject: Object.assign({}, object._embedded.indexableObject, { + _embedded: Object.keys(object._embedded.indexableObject._embedded) + .filter((key) => allowedEmbeddedKeys.includes(key)) + .reduce((obj, key) => { + obj[key] = object._embedded.indexableObject._embedded[key]; + return obj; + }, {}) + }) + }); + } else { + return object; + } + + } +} 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 a13fb9487b..22d5fd3e77 100644 --- a/src/app/core/data/object-updates/object-updates.service.ts +++ b/src/app/core/data/object-updates/object-updates.service.ts @@ -5,7 +5,8 @@ import { coreSelector } from '../../core.selectors'; import { FieldState, FieldUpdates, - Identifiable, OBJECT_UPDATES_TRASH_PATH, + Identifiable, + OBJECT_UPDATES_TRASH_PATH, ObjectUpdatesEntry, ObjectUpdatesState } from './object-updates.reducer'; @@ -17,9 +18,10 @@ import { InitializeFieldsAction, ReinstateObjectUpdatesAction, RemoveFieldUpdateAction, - SetEditableFieldUpdateAction, SetValidFieldUpdateAction + SetEditableFieldUpdateAction, + SetValidFieldUpdateAction } from './object-updates.actions'; -import { distinctUntilChanged, filter, map, tap } from 'rxjs/operators'; +import { distinctUntilChanged, filter, map } from 'rxjs/operators'; import { hasNoValue, hasValue, isEmpty, isNotEmpty } from '../../../shared/empty.util'; import { INotification } from '../../../shared/notifications/models/notification.model'; @@ -212,6 +214,7 @@ export class ObjectUpdatesService { /** * Method to dispatch an RemoveFieldUpdateAction to the store * @param url The page's URL for which the changes should be removed + * @param uuid The UUID of the field that should be set */ removeSingleFieldUpdate(url: string, uuid) { this.store.dispatch(new RemoveFieldUpdateAction(url, uuid)); diff --git a/src/app/core/data/paginated-list.ts b/src/app/core/data/paginated-list.ts index faecd231bc..e1c1b22569 100644 --- a/src/app/core/data/paginated-list.ts +++ b/src/app/core/data/paginated-list.ts @@ -1,5 +1,5 @@ import { PageInfo } from '../shared/page-info.model'; -import { hasNoValue, hasValue } from '../../shared/empty.util'; +import { hasValue } from '../../shared/empty.util'; export class PaginatedList { @@ -11,7 +11,7 @@ export class PaginatedList { if (hasValue(this.pageInfo) && hasValue(this.pageInfo.elementsPerPage)) { return this.pageInfo.elementsPerPage; } - return this.page.length; + return this.getPageLength(); } set elementsPerPage(value: number) { @@ -22,10 +22,7 @@ export class PaginatedList { if (hasValue(this.pageInfo) && hasValue(this.pageInfo.totalElements)) { return this.pageInfo.totalElements; } - if (hasNoValue(this.page)) { - return 0; - } - return this.page.length; + return this.getPageLength(); } set totalElements(value: number) { @@ -92,4 +89,8 @@ export class PaginatedList { set self(self: string) { this.pageInfo.self = self; } + + protected getPageLength() { + return (Array.isArray(this.page)) ? this.page.length : 0; + } } diff --git a/src/app/core/data/request.models.ts b/src/app/core/data/request.models.ts index d2cdd45a0a..a2b3423960 100644 --- a/src/app/core/data/request.models.ts +++ b/src/app/core/data/request.models.ts @@ -14,10 +14,10 @@ import { RestRequestMethod } from './rest-request-method'; import { SearchParam } from '../cache/models/search-param.model'; import { EpersonResponseParsingService } from '../eperson/eperson-response-parsing.service'; import { BrowseItemsResponseParsingService } from './browse-items-response-parsing-service'; -import { RegistryMetadataschemasResponseParsingService } from './registry-metadataschemas-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'; /* tslint:disable:max-classes-per-file */ @@ -371,6 +371,30 @@ export class DeleteByIDRequest extends DeleteRequest { } } +export class TaskPostRequest extends PostRequest { + constructor(uuid: string, href: string, public body?: any, public options?: HttpOptions) { + super(uuid, href, body, options); + } + + getResponseParser(): GenericConstructor { + return TaskResponseParsingService; + } +} + +export class TaskDeleteRequest extends DeleteRequest { + constructor(uuid: string, href: string, public body?: any, public options?: HttpOptions) { + super(uuid, href, body, options); + } + + getResponseParser(): GenericConstructor { + return TaskResponseParsingService; + } +} + +export class MyDSpaceRequest extends GetRequest { + public responseMsToLive = 0; +} + export class RequestError extends Error { statusCode: number; statusText: string; diff --git a/src/app/core/data/request.service.ts b/src/app/core/data/request.service.ts index 9f79d7539b..83071382ed 100644 --- a/src/app/core/data/request.service.ts +++ b/src/app/core/data/request.service.ts @@ -1,11 +1,13 @@ import { Injectable } from '@angular/core'; +import { HttpHeaders } from '@angular/common/http'; import { createSelector, MemoizedSelector, select, Store } from '@ngrx/store'; import { Observable, race as observableRace } from 'rxjs'; -import { filter, map, mergeMap, take } from 'rxjs/operators'; +import { filter, find, map, mergeMap, take } from 'rxjs/operators'; +import { cloneDeep, remove } from 'lodash'; import { AppState } from '../../app.reducer'; -import { hasValue, isNotEmpty } from '../../shared/empty.util'; +import { hasValue, isEmpty, isNotEmpty } from '../../shared/empty.util'; import { CacheableObject } from '../cache/object-cache.reducer'; import { ObjectCacheService } from '../cache/object-cache.service'; import { CoreState } from '../core.reducers'; @@ -23,8 +25,6 @@ import { CommitSSBAction } from '../cache/server-sync-buffer.actions'; import { RestRequestMethod } from './rest-request-method'; import { AddToIndexAction, RemoveFromIndexBySubstringAction } from '../index/index.actions'; import { coreSelector } from '../core.selectors'; -import { HttpHeaders } from '@angular/common/http'; -import { cloneDeep } from 'lodash'; /** * The base selector function to select the request state in the store @@ -49,7 +49,6 @@ const entryFromUUIDSelector = (uuid: string): MemoizedSelector(request: RestRequest, forceBypassCache: boolean = false): void { const isGetRequest = request.method === RestRequestMethod.GET; - if (!isGetRequest || !this.isCachedOrPending(request) || forceBypassCache) { + if (forceBypassCache) { + this.clearRequestsOnTheirWayToTheStore(request); + } + if (!isGetRequest || (forceBypassCache && !this.isPending(request)) || !this.isCachedOrPending(request)) { this.dispatchRequest(request); - if (isGetRequest && !forceBypassCache) { + if (isGetRequest) { this.trackRequestsOnTheirWayToTheStore(request); } } else { @@ -168,6 +169,29 @@ export class RequestService { } } + /** + * Convert request Payload to a URL-encoded string + * + * e.g. uriEncodeBody({param: value, param1: value1}) + * returns: param=value¶m1=value1 + * + * @param body + * The request Payload to convert + * @return string + * URL-encoded string + */ + public uriEncodeBody(body: any) { + let queryParams = ''; + if (isNotEmpty(body) && typeof body === 'object') { + Object.keys(body) + .forEach((param) => { + const paramValue = `${param}=${body[param]}`; + queryParams = isEmpty(queryParams) ? queryParams.concat(paramValue) : queryParams.concat('&', paramValue); + }) + } + return encodeURI(queryParams); + } + /** * Remove all request cache providing (part of) the href * This also includes href-to-uuid index cache @@ -234,6 +258,19 @@ export class RequestService { }); } + /** + * This method remove requests that are on their way to the store. + */ + private clearRequestsOnTheirWayToTheStore(request: GetRequest) { + this.getByHref(request.href).pipe( + find((re: RequestEntry) => hasValue(re))) + .subscribe((re: RequestEntry) => { + if (!re.responsePending) { + remove(this.requestsOnTheirWayToTheStore, (item) => item === request.href); + } + }); + } + /** * Dispatch commit action to send all changes (for a certain method) to the server (buffer) * @param {RestRequestMethod} method RestRequestMethod for which the changes should be committed diff --git a/src/app/core/data/search-response-parsing.service.ts b/src/app/core/data/search-response-parsing.service.ts index 0e9d39849b..9ab0104393 100644 --- a/src/app/core/data/search-response-parsing.service.ts +++ b/src/app/core/data/search-response-parsing.service.ts @@ -15,7 +15,13 @@ export class SearchResponseParsingService implements ResponseParsingService { } parse(request: RestRequest, data: DSpaceRESTV2Response): RestResponse { - const payload = data.payload._embedded.searchResult; + // fallback for unexpected empty response + const emptyPayload = { + _embedded : { + objects: [] + } + }; + const payload = data.payload._embedded.searchResult || emptyPayload; const hitHighlights: MetadataMap[] = payload._embedded.objects .map((object) => object.hitHighlights) .map((hhObject) => { @@ -47,7 +53,7 @@ export class SearchResponseParsingService implements ResponseParsingService { const objects = payload._embedded.objects .filter((object) => hasValue(object._embedded)) .map((object, index) => Object.assign({}, object, { - dspaceObject: dsoSelfLinks[index], + indexableObject: dsoSelfLinks[index], hitHighlights: hitHighlights[index], // we don't need embedded collections, bitstreamformats, etc for search results. // And parsing them all takes up a lot of time. Throw them away to improve performance diff --git a/src/app/core/dspace-rest-v2/dspace-rest-v2.service.ts b/src/app/core/dspace-rest-v2/dspace-rest-v2.service.ts index 204c782e79..290f4be8a2 100644 --- a/src/app/core/dspace-rest-v2/dspace-rest-v2.service.ts +++ b/src/app/core/dspace-rest-v2/dspace-rest-v2.service.ts @@ -68,6 +68,8 @@ export class DSpaceRESTv2Service { * the URL for the request * @param body * an optional body for the request + * @param options + * the HttpOptions object * @return {Observable} * An Observable containing the response from the server */ diff --git a/src/app/core/eperson/models/eperson.model.ts b/src/app/core/eperson/models/eperson.model.ts index 32286929ee..f8c11c1201 100644 --- a/src/app/core/eperson/models/eperson.model.ts +++ b/src/app/core/eperson/models/eperson.model.ts @@ -47,7 +47,9 @@ export class EPerson extends DSpaceObject { */ public selfRegistered: boolean; - /** Getter to retrieve the EPerson's full name as a string */ + /** + * Getter to retrieve the EPerson's full name as a string + */ get name(): string { return this.firstMetadataValue('eperson.firstname') + ' ' + this.firstMetadataValue('eperson.lastname'); } diff --git a/src/app/core/roles/role-types.ts b/src/app/core/roles/role-types.ts new file mode 100644 index 0000000000..b39d1205a6 --- /dev/null +++ b/src/app/core/roles/role-types.ts @@ -0,0 +1,5 @@ +export enum RoleType { + Submitter = 'submitter', + Controller = 'controller', + Admin = 'admin' +} diff --git a/src/app/core/roles/role.service.ts b/src/app/core/roles/role.service.ts new file mode 100644 index 0000000000..7a4b6e6ccf --- /dev/null +++ b/src/app/core/roles/role.service.ts @@ -0,0 +1,70 @@ +import { Injectable } from '@angular/core'; + +import { Observable, of as observableOf } from 'rxjs'; +import { distinctUntilChanged } from 'rxjs/operators'; + +import { RoleType } from './role-types'; +import { CollectionDataService } from '../data/collection-data.service'; + +/** + * A service that provides methods to identify user role. + */ +@Injectable() +export class RoleService { + + /** + * Initialize instance variables + * + * @param {CollectionDataService} collectionService + */ + constructor(private collectionService: CollectionDataService) { + } + + /** + * Check if current user is a submitter + */ + isSubmitter(): Observable { + return this.collectionService.hasAuthorizedCollection().pipe( + distinctUntilChanged() + ); + } + + /** + * Check if current user is a controller + */ + isController(): Observable { + // TODO find a way to check if user is a controller + return observableOf(true); + } + + /** + * Check if current user is an admin + */ + isAdmin(): Observable { + // TODO find a way to check if user is an admin + return observableOf(false); + } + + /** + * Check if current user by role type + * + * @param {RoleType} role + * the role type + */ + checkRole(role: RoleType): Observable { + let check: Observable; + switch (role) { + case RoleType.Submitter: + check = this.isSubmitter(); + break; + case RoleType.Controller: + check = this.isController(); + break; + case RoleType.Admin: + check = this.isAdmin(); + break; + } + + return check; + } +} diff --git a/src/app/core/shared/item.model.ts b/src/app/core/shared/item.model.ts index 645b50d5db..839103b9f5 100644 --- a/src/app/core/shared/item.model.ts +++ b/src/app/core/shared/item.model.ts @@ -5,7 +5,7 @@ import { DSpaceObject } from './dspace-object.model'; import { Collection } from './collection.model'; import { RemoteData } from '../data/remote-data'; import { Bitstream } from './bitstream.model'; -import { hasValue, isNotEmpty } from '../../shared/empty.util'; +import { hasValue, isNotEmpty, isNotUndefined } from '../../shared/empty.util'; import { PaginatedList } from '../data/paginated-list'; import { Relationship } from './item-relationships/relationship.model'; @@ -95,7 +95,7 @@ export class Item extends DSpaceObject { */ getBitstreamsByBundleName(bundleName: string): Observable { return this.bitstreams.pipe( - filter((rd: RemoteData>) => !rd.isResponsePending), + filter((rd: RemoteData>) => !rd.isResponsePending && isNotUndefined(rd.payload)), map((rd: RemoteData>) => rd.payload.page), filter((bitstreams: Bitstream[]) => hasValue(bitstreams)), take(1), diff --git a/src/app/core/shared/operators.ts b/src/app/core/shared/operators.ts index ce9740a0fc..29bb2f6b7d 100644 --- a/src/app/core/shared/operators.ts +++ b/src/app/core/shared/operators.ts @@ -75,7 +75,7 @@ export const toDSpaceObjectListRD = () => source.pipe( filter((rd: RemoteData>>) => rd.hasSucceeded), map((rd: RemoteData>>) => { - const dsoPage: T[] = rd.payload.page.map((searchResult: SearchResult) => searchResult.dspaceObject); + const dsoPage: T[] = rd.payload.page.map((searchResult: SearchResult) => searchResult.indexableObject); const payload = Object.assign(rd.payload, { page: dsoPage }) as PaginatedList; return Object.assign(rd, { payload: payload }); }) diff --git a/src/app/core/shared/resource-type.ts b/src/app/core/shared/resource-type.ts index d5afa4105f..bdcc3a52f6 100644 --- a/src/app/core/shared/resource-type.ts +++ b/src/app/core/shared/resource-type.ts @@ -23,4 +23,6 @@ export enum ResourceType { SubmissionForms = 'submissionforms', SubmissionSections = 'submissionsections', SubmissionSection = 'submissionsection', + ClaimedTask = 'claimedtask', + PoolTask = 'pooltask' } diff --git a/src/app/core/shared/view-mode.model.ts b/src/app/core/shared/view-mode.model.ts index b026d68431..9c8d086097 100644 --- a/src/app/core/shared/view-mode.model.ts +++ b/src/app/core/shared/view-mode.model.ts @@ -4,5 +4,6 @@ export enum ViewMode { List = 'list', - Grid = 'grid' + Grid = 'grid', + Detail = 'detail' } diff --git a/src/app/core/submission/models/normalized-submission-object.model.ts b/src/app/core/submission/models/normalized-submission-object.model.ts index 8091781760..f674ebdf72 100644 --- a/src/app/core/submission/models/normalized-submission-object.model.ts +++ b/src/app/core/submission/models/normalized-submission-object.model.ts @@ -1,4 +1,4 @@ -import { autoserialize, inheritSerialization } from 'cerialize'; +import { autoserialize, autoserializeAs, inheritSerialization } from 'cerialize'; import { NormalizedDSpaceObject } from '../../cache/models/normalized-dspace-object.model'; import { WorkspaceitemSectionsObject } from './workspaceitem-sections.model'; @@ -17,6 +17,12 @@ export class NormalizedSubmissionObject extends Normaliz @autoserialize id: string; + /** + * The workspaceitem/workflowitem identifier + */ + @autoserializeAs(String, 'id') + uuid: string; + /** * The workspaceitem/workflowitem last modified date */ diff --git a/src/app/core/submission/models/submission-object.model.ts b/src/app/core/submission/models/submission-object.model.ts index 6b2d9a03b9..23f75553c5 100644 --- a/src/app/core/submission/models/submission-object.model.ts +++ b/src/app/core/submission/models/submission-object.model.ts @@ -25,6 +25,11 @@ export abstract class SubmissionObject extends DSpaceObject implements Cacheable */ id: string; + /** + * The workspaceitem/workflowitem identifier + */ + uuid: string; + /** * The workspaceitem/workflowitem last modified date */ diff --git a/src/app/core/submission/submission-response-parsing.service.ts b/src/app/core/submission/submission-response-parsing.service.ts index 20dfb43cbd..21135be463 100644 --- a/src/app/core/submission/submission-response-parsing.service.ts +++ b/src/app/core/submission/submission-response-parsing.service.ts @@ -27,16 +27,16 @@ export function isServerFormValue(obj: any): boolean { && obj.hasOwnProperty('value') && obj.hasOwnProperty('language') && obj.hasOwnProperty('authority') - && obj.hasOwnProperty('confidence') - && obj.hasOwnProperty('place')) + && obj.hasOwnProperty('confidence')) } /** * Export a function to normalize sections object of the server response * * @param obj + * @param objIndex */ -export function normalizeSectionData(obj: any) { +export function normalizeSectionData(obj: any, objIndex?: number) { let result: any = obj; if (isNotNull(obj)) { // If is an Instance of FormFieldMetadataValueObject normalize it @@ -49,14 +49,14 @@ export function normalizeSectionData(obj: any) { obj.language, obj.authority, (obj.display || obj.value), - obj.place, + obj.place || objIndex, obj.confidence, obj.otherInformation ); } else if (Array.isArray(obj)) { result = []; obj.forEach((item, index) => { - result[index] = normalizeSectionData(item); + result[index] = normalizeSectionData(item, index); }); } else if (typeof obj === 'object') { result = Object.create({}); @@ -93,11 +93,10 @@ export class SubmissionResponseParsingService extends BaseResponseParsingService parse(request: RestRequest, data: DSpaceRESTV2Response): RestResponse { if (isNotEmpty(data.payload) && isNotEmpty(data.payload._links) - && (data.statusCode === 201 || data.statusCode === 200)) { + && this.isSuccessStatus(data.statusCode)) { const dataDefinition = this.processResponse(data.payload, request.href); return new SubmissionSuccessResponse(dataDefinition, data.statusCode, data.statusText, this.processPageInfo(data.payload)); - } else if (isEmpty(data.payload) && data.statusCode === 204) { - // Response from a DELETE request + } else if (isEmpty(data.payload) && this.isSuccessStatus(data.statusCode)) { return new SubmissionSuccessResponse(null, data.statusCode, data.statusText); } else { return new ErrorResponse( @@ -141,9 +140,9 @@ export class SubmissionResponseParsingService extends BaseResponseParsingService // If entry is not an array, for sure is not a section of type form if (Array.isArray(entry)) { normalizedSectionData[metdadataId] = []; - entry.forEach((valueItem) => { + entry.forEach((valueItem, index) => { // Parse value and normalize it - const normValue = normalizeSectionData(valueItem); + const normValue = normalizeSectionData(valueItem, index); if (isNotEmpty(normValue)) { normalizedSectionData[metdadataId].push(normValue); } diff --git a/src/app/core/tasks/claimed-task-data.service.spec.ts b/src/app/core/tasks/claimed-task-data.service.spec.ts new file mode 100644 index 0000000000..a7be0830ec --- /dev/null +++ b/src/app/core/tasks/claimed-task-data.service.spec.ts @@ -0,0 +1,108 @@ +import { HttpClient, HttpHeaders } from '@angular/common/http'; + +import { Store } from '@ngrx/store'; + +import { getMockRequestService } from '../../shared/mocks/mock-request.service'; +import { HALEndpointServiceStub } from '../../shared/testing/hal-endpoint-service-stub'; +import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { NormalizedObjectBuildService } from '../cache/builders/normalized-object-build.service'; +import { CoreState } from '../core.reducers'; +import { ClaimedTaskDataService } from './claimed-task-data.service'; +import { HttpOptions } from '../dspace-rest-v2/dspace-rest-v2.service'; + +describe('ClaimedTaskDataService', () => { + let service: ClaimedTaskDataService; + let options: HttpOptions; + const taskEndpoint = 'https://rest.api/task'; + const linkPath = 'claimedtasks'; + const requestService: any = getMockRequestService(); + const halService: any = new HALEndpointServiceStub(taskEndpoint); + const rdbService = {} as RemoteDataBuildService; + const notificationsService = {} as NotificationsService; + const http = {} as HttpClient; + const comparator = {} as any; + const dataBuildService = { + normalize: (object) => object + } as NormalizedObjectBuildService; + const objectCache = { + addPatch: () => { + /* empty */ + }, + getObjectBySelfLink: () => { + /* empty */ + } + } as any; + const store = {} as Store; + + function initTestService(): ClaimedTaskDataService { + return new ClaimedTaskDataService( + requestService, + rdbService, + dataBuildService, + store, + objectCache, + halService, + notificationsService, + http, + comparator + ); + } + + beforeEach(() => { + service = initTestService(); + options = Object.create({}); + let headers = new HttpHeaders(); + headers = headers.append('Content-Type', 'application/x-www-form-urlencoded'); + options.headers = headers; + }); + + describe('approveTask', () => { + + it('should call postToEndpoint method', () => { + const scopeId = '1234'; + const body = { + submit_approve: 'true' + }; + + spyOn(service, 'postToEndpoint'); + requestService.uriEncodeBody.and.returnValue(body); + + service.approveTask(scopeId); + + expect(service.postToEndpoint).toHaveBeenCalledWith(linkPath, body, scopeId, options); + }); + }); + + describe('rejectTask', () => { + + it('should call postToEndpoint method', () => { + const scopeId = '1234'; + const reason = 'test reject'; + const body = { + submit_reject: 'true', + reason + }; + + spyOn(service, 'postToEndpoint'); + requestService.uriEncodeBody.and.returnValue(body); + + service.rejectTask(reason, scopeId); + + expect(service.postToEndpoint).toHaveBeenCalledWith(linkPath, body, scopeId, options); + }); + }); + + describe('returnToPoolTask', () => { + + it('should call deleteById method', () => { + const scopeId = '1234'; + + spyOn(service, 'deleteById'); + + service.returnToPoolTask(scopeId); + + expect(service.deleteById).toHaveBeenCalledWith(linkPath, scopeId, options); + }); + }); +}); diff --git a/src/app/core/tasks/claimed-task-data.service.ts b/src/app/core/tasks/claimed-task-data.service.ts new file mode 100644 index 0000000000..dda42e1c67 --- /dev/null +++ b/src/app/core/tasks/claimed-task-data.service.ts @@ -0,0 +1,106 @@ +import { Injectable } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; + +import { Store } from '@ngrx/store'; +import { Observable } from 'rxjs'; + +import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; +import { CoreState } from '../core.reducers'; +import { RequestService } from '../data/request.service'; +import { ClaimedTask } from './models/claimed-task-object.model'; +import { TasksService } from './tasks.service'; +import { HALEndpointService } from '../shared/hal-endpoint.service'; +import { NormalizedObjectBuildService } from '../cache/builders/normalized-object-build.service'; +import { ObjectCacheService } from '../cache/object-cache.service'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { DSOChangeAnalyzer } from '../data/dso-change-analyzer.service'; +import { ProcessTaskResponse } from './models/process-task-response'; + +/** + * The service handling all REST requests for ClaimedTask + */ +@Injectable() +export class ClaimedTaskDataService extends TasksService { + + /** + * The endpoint link name + */ + protected linkPath = 'claimedtasks'; + + /** + * When true, a new request is always dispatched + */ + protected forceBypassCache = true; + + /** + * Initialize instance variables + * + * @param {RequestService} requestService + * @param {RemoteDataBuildService} rdbService + * @param {NormalizedObjectBuildService} dataBuildService + * @param {Store} store + * @param {ObjectCacheService} objectCache + * @param {HALEndpointService} halService + * @param {NotificationsService} notificationsService + * @param {HttpClient} http + * @param {DSOChangeAnalyzer, + protected objectCache: ObjectCacheService, + protected halService: HALEndpointService, + protected notificationsService: NotificationsService, + protected http: HttpClient, + protected comparator: DSOChangeAnalyzer) { + super(); + } + + /** + * Make a request to approve the given task + * + * @param scopeId + * The task id + * @return {Observable} + * Emit the server response + */ + public approveTask(scopeId: string): Observable { + const body = { + submit_approve: 'true' + }; + return this.postToEndpoint(this.linkPath, this.requestService.uriEncodeBody(body), scopeId, this.makeHttpOptions()); + } + + /** + * Make a request to reject the given task + * + * @param reason + * The reason of reject + * @param scopeId + * The task id + * @return {Observable} + * Emit the server response + */ + public rejectTask(reason: string, scopeId: string): Observable { + const body = { + submit_reject: 'true', + reason + }; + return this.postToEndpoint(this.linkPath, this.requestService.uriEncodeBody(body), scopeId, this.makeHttpOptions()); + } + + /** + * Make a request to return the given task to the pool + * + * @param scopeId + * The task id + * @return {Observable} + * Emit the server response + */ + public returnToPoolTask(scopeId: string): Observable { + return this.deleteById(this.linkPath, scopeId, this.makeHttpOptions()); + } + +} diff --git a/src/app/core/tasks/models/claimed-task-object.model.ts b/src/app/core/tasks/models/claimed-task-object.model.ts new file mode 100644 index 0000000000..212e75ed95 --- /dev/null +++ b/src/app/core/tasks/models/claimed-task-object.model.ts @@ -0,0 +1,8 @@ +import { TaskObject } from './task-object.model'; + +/** + * A model class for a ClaimedTask. + */ +export class ClaimedTask extends TaskObject { + +} diff --git a/src/app/core/tasks/models/normalized-claimed-task-object.model.ts b/src/app/core/tasks/models/normalized-claimed-task-object.model.ts new file mode 100644 index 0000000000..c2c3f12bc4 --- /dev/null +++ b/src/app/core/tasks/models/normalized-claimed-task-object.model.ts @@ -0,0 +1,39 @@ +import { NormalizedTaskObject } from './normalized-task-object.model'; +import { mapsTo, relationship } from '../../cache/builders/build-decorators'; +import { autoserialize, inheritSerialization } from 'cerialize'; +import { ClaimedTask } from './claimed-task-object.model'; +import { ResourceType } from '../../shared/resource-type'; + +/** + * A normalized model class for a ClaimedTask. + */ +@mapsTo(ClaimedTask) +@inheritSerialization(NormalizedTaskObject) +export class NormalizedClaimedTask extends NormalizedTaskObject { + + /** + * The task identifier + */ + @autoserialize + id: string; + + /** + * The workflow step + */ + @autoserialize + step: string; + + /** + * The task action type + */ + @autoserialize + action: string; + + /** + * The workflowitem object whom this task is related + */ + @autoserialize + @relationship(ResourceType.Workflowitem, false) + workflowitem: string; + +} diff --git a/src/app/core/tasks/models/normalized-pool-task-object.model.ts b/src/app/core/tasks/models/normalized-pool-task-object.model.ts new file mode 100644 index 0000000000..22cda6ff9c --- /dev/null +++ b/src/app/core/tasks/models/normalized-pool-task-object.model.ts @@ -0,0 +1,38 @@ +import { NormalizedTaskObject } from './normalized-task-object.model'; +import { PoolTask } from './pool-task-object.model'; +import { autoserialize, inheritSerialization } from 'cerialize'; +import { mapsTo, relationship } from '../../cache/builders/build-decorators'; +import { ResourceType } from '../../shared/resource-type'; + +/** + * A normalized model class for a PoolTask. + */ +@mapsTo(PoolTask) +@inheritSerialization(NormalizedTaskObject) +export class NormalizedPoolTask extends NormalizedTaskObject { + + /** + * The task identifier + */ + @autoserialize + id: string; + + /** + * The workflow step + */ + @autoserialize + step: string; + + /** + * The task action type + */ + @autoserialize + action: string; + + /** + * The workflowitem object whom this task is related + */ + @autoserialize + @relationship(ResourceType.Workflowitem, false) + workflowitem: string; +} diff --git a/src/app/core/tasks/models/normalized-task-object.model.ts b/src/app/core/tasks/models/normalized-task-object.model.ts new file mode 100644 index 0000000000..52c274e3a8 --- /dev/null +++ b/src/app/core/tasks/models/normalized-task-object.model.ts @@ -0,0 +1,39 @@ +import { autoserialize, inheritSerialization } from 'cerialize'; +import { mapsTo, relationship } from '../../cache/builders/build-decorators'; +import { ResourceType } from '../../shared/resource-type'; +import { NormalizedDSpaceObject } from '../../cache/models/normalized-dspace-object.model'; +import { TaskObject } from './task-object.model'; +import { DSpaceObject } from '../../shared/dspace-object.model'; + +/** + * An abstract normalized model class for a TaskObject. + */ +@mapsTo(TaskObject) +@inheritSerialization(NormalizedDSpaceObject) +export abstract class NormalizedTaskObject extends NormalizedDSpaceObject { + + /** + * The task identifier + */ + @autoserialize + id: string; + + /** + * The workflow step + */ + @autoserialize + step: string; + + /** + * The task action type + */ + @autoserialize + action: string; + + /** + * The workflowitem object whom this task is related + */ + @autoserialize + @relationship(ResourceType.Workflowitem, false) + workflowitem: string; +} diff --git a/src/app/core/tasks/models/pool-task-object.model.ts b/src/app/core/tasks/models/pool-task-object.model.ts new file mode 100644 index 0000000000..8d98d3e1a5 --- /dev/null +++ b/src/app/core/tasks/models/pool-task-object.model.ts @@ -0,0 +1,8 @@ +import { TaskObject } from './task-object.model'; + +/** + * A model class for a PoolTask. + */ +export class PoolTask extends TaskObject { + +} diff --git a/src/app/core/tasks/models/process-task-response.ts b/src/app/core/tasks/models/process-task-response.ts new file mode 100644 index 0000000000..ca4bc9a068 --- /dev/null +++ b/src/app/core/tasks/models/process-task-response.ts @@ -0,0 +1,17 @@ +import { RemoteDataError } from '../../data/remote-data-error'; + +/** + * A class to represent the data retrieved by after processing a task + */ +export class ProcessTaskResponse { + constructor( + private isSuccessful: boolean, + public error?: RemoteDataError, + public payload?: any + ) { + } + + get hasSucceeded(): boolean { + return this.isSuccessful; + } +} diff --git a/src/app/core/tasks/models/task-object.model.ts b/src/app/core/tasks/models/task-object.model.ts new file mode 100644 index 0000000000..97a1c9f59e --- /dev/null +++ b/src/app/core/tasks/models/task-object.model.ts @@ -0,0 +1,33 @@ +import { Observable } from 'rxjs'; + +import { CacheableObject } from '../../cache/object-cache.reducer'; +import { DSpaceObject } from '../../shared/dspace-object.model'; +import { ListableObject } from '../../../shared/object-collection/shared/listable-object.model'; +import { RemoteData } from '../../data/remote-data'; +import { Workflowitem } from '../../submission/models/workflowitem.model'; + +/** + * An abstract model class for a TaskObject. + */ +export class TaskObject extends DSpaceObject implements CacheableObject, ListableObject { + + /** + * The task identifier + */ + id: string; + + /** + * The workflow step + */ + step: string; + + /** + * The task action type + */ + action: string; + + /** + * The workflowitem object whom this task is related + */ + workflowitem: Observable> | Workflowitem; +} diff --git a/src/app/core/tasks/pool-task-data.service.spec.ts b/src/app/core/tasks/pool-task-data.service.spec.ts new file mode 100644 index 0000000000..7f40c6e89c --- /dev/null +++ b/src/app/core/tasks/pool-task-data.service.spec.ts @@ -0,0 +1,70 @@ +import { HttpClient, HttpHeaders } from '@angular/common/http'; + +import { Store } from '@ngrx/store'; + +import { getMockRequestService } from '../../shared/mocks/mock-request.service'; +import { HALEndpointServiceStub } from '../../shared/testing/hal-endpoint-service-stub'; +import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { NormalizedObjectBuildService } from '../cache/builders/normalized-object-build.service'; +import { CoreState } from '../core.reducers'; +import { PoolTaskDataService } from './pool-task-data.service'; +import { HttpOptions } from '../dspace-rest-v2/dspace-rest-v2.service'; + +describe('PoolTaskDataService', () => { + let service: PoolTaskDataService; + let options: HttpOptions; + const taskEndpoint = 'https://rest.api/task'; + const linkPath = 'pooltasks'; + const requestService = getMockRequestService(); + const halService: any = new HALEndpointServiceStub(taskEndpoint); + const rdbService = {} as RemoteDataBuildService; + const notificationsService = {} as NotificationsService; + const http = {} as HttpClient; + const comparator = {} as any; + const dataBuildService = { + normalize: (object) => object + } as NormalizedObjectBuildService; + const objectCache = { + addPatch: () => { + /* empty */ + }, + getObjectBySelfLink: () => { + /* empty */ + } + } as any; + const store = {} as Store; + + function initTestService(): PoolTaskDataService { + return new PoolTaskDataService( + requestService, + rdbService, + dataBuildService, + store, + objectCache, + halService, + notificationsService, + http, + comparator + ); + } + + beforeEach(() => { + service = initTestService(); + options = Object.create({}); + let headers = new HttpHeaders(); + headers = headers.append('Content-Type', 'application/x-www-form-urlencoded'); + options.headers = headers; + }); + + describe('claimTask', () => { + + it('should call postToEndpoint method', () => { + spyOn(service, 'postToEndpoint'); + const scopeId = '1234'; + service.claimTask(scopeId); + + expect(service.postToEndpoint).toHaveBeenCalledWith(linkPath, {}, scopeId, options); + }); + }); +}); diff --git a/src/app/core/tasks/pool-task-data.service.ts b/src/app/core/tasks/pool-task-data.service.ts new file mode 100644 index 0000000000..1a93450d4d --- /dev/null +++ b/src/app/core/tasks/pool-task-data.service.ts @@ -0,0 +1,72 @@ +import { Injectable } from '@angular/core'; +import { HttpClient } from '@angular/common/http'; + +import { Observable } from 'rxjs'; +import { Store } from '@ngrx/store'; + +import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; +import { CoreState } from '../core.reducers'; +import { RequestService } from '../data/request.service'; +import { PoolTask } from './models/pool-task-object.model'; +import { TasksService } from './tasks.service'; +import { HALEndpointService } from '../shared/hal-endpoint.service'; +import { NormalizedObjectBuildService } from '../cache/builders/normalized-object-build.service'; +import { ObjectCacheService } from '../cache/object-cache.service'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { DSOChangeAnalyzer } from '../data/dso-change-analyzer.service'; +import { ProcessTaskResponse } from './models/process-task-response'; + +/** + * The service handling all REST requests for PoolTask + */ +@Injectable() +export class PoolTaskDataService extends TasksService { + + /** + * The endpoint link name + */ + protected linkPath = 'pooltasks'; + + /** + * When true, a new request is always dispatched + */ + protected forceBypassCache = true; + + /** + * Initialize instance variables + * + * @param {RequestService} requestService + * @param {RemoteDataBuildService} rdbService + * @param {NormalizedObjectBuildService} dataBuildService + * @param {Store} store + * @param {ObjectCacheService} objectCache + * @param {HALEndpointService} halService + * @param {NotificationsService} notificationsService + * @param {HttpClient} http + * @param {DSOChangeAnalyzer, + protected objectCache: ObjectCacheService, + protected halService: HALEndpointService, + protected notificationsService: NotificationsService, + protected http: HttpClient, + protected comparator: DSOChangeAnalyzer) { + super(); + } + + /** + * Make a request to claim the given task + * + * @param scopeId + * The task id + * @return {Observable} + * Emit the server response + */ + public claimTask(scopeId: string): Observable { + return this.postToEndpoint(this.linkPath, {}, scopeId, this.makeHttpOptions()); + } +} diff --git a/src/app/core/tasks/task-response-parsing.service.ts b/src/app/core/tasks/task-response-parsing.service.ts new file mode 100644 index 0000000000..7445f9d267 --- /dev/null +++ b/src/app/core/tasks/task-response-parsing.service.ts @@ -0,0 +1,54 @@ +import { Inject, Injectable } from '@angular/core'; + +import { ResponseParsingService } from '../data/parsing.service'; +import { RestRequest } from '../data/request.models'; +import { DSpaceRESTV2Response } from '../dspace-rest-v2/dspace-rest-v2-response.model'; + +import { BaseResponseParsingService } from '../data/base-response-parsing.service'; +import { GLOBAL_CONFIG } from '../../../config'; +import { GlobalConfig } from '../../../config/global-config.interface'; +import { ObjectCacheService } from '../cache/object-cache.service'; +import { NormalizedObjectFactory } from '../cache/models/normalized-object-factory'; +import { ErrorResponse, RestResponse, TaskResponse } from '../cache/response.models'; + +/** + * Provides methods to parse response for a task request. + */ +@Injectable() +export class TaskResponseParsingService extends BaseResponseParsingService implements ResponseParsingService { + + protected objectFactory = NormalizedObjectFactory; + protected toCache = false; + + /** + * Initialize instance variables + * + * @param {GlobalConfig} EnvConfig + * @param {ObjectCacheService} objectCache + */ + constructor(@Inject(GLOBAL_CONFIG) protected EnvConfig: GlobalConfig, + protected objectCache: ObjectCacheService,) { + super(); + } + + /** + * Parses data from the tasks endpoints + * + * @param {RestRequest} request + * @param {DSpaceRESTV2Response} data + * @returns {RestResponse} + */ + parse(request: RestRequest, data: DSpaceRESTV2Response): RestResponse { + if (this.isSuccessStatus(data.statusCode)) { + return new TaskResponse( data.statusCode, data.statusText); + } else { + return new ErrorResponse( + Object.assign( + new Error('Unexpected response from server'), + { statusCode: data.statusCode, statusText: data.statusText } + ) + ); + } + } + +} diff --git a/src/app/core/tasks/tasks.service.spec.ts b/src/app/core/tasks/tasks.service.spec.ts new file mode 100644 index 0000000000..753ce2ddd5 --- /dev/null +++ b/src/app/core/tasks/tasks.service.spec.ts @@ -0,0 +1,130 @@ +import { getTestScheduler } from 'jasmine-marbles'; +import { TestScheduler } from 'rxjs/testing'; + +import { getMockRequestService } from '../../shared/mocks/mock-request.service'; +import { TasksService } from './tasks.service'; +import { RequestService } from '../data/request.service'; +import { TaskDeleteRequest, TaskPostRequest } from '../data/request.models'; +import { HALEndpointService } from '../shared/hal-endpoint.service'; +import { HALEndpointServiceStub } from '../../shared/testing/hal-endpoint-service-stub'; +import { TaskObject } from './models/task-object.model'; +import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; +import { NormalizedObjectBuildService } from '../cache/builders/normalized-object-build.service'; +import { Store } from '@ngrx/store'; +import { CoreState } from '../core.reducers'; +import { ObjectCacheService } from '../cache/object-cache.service'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { HttpClient, HttpHeaders } from '@angular/common/http'; +import { DSOChangeAnalyzer } from '../data/dso-change-analyzer.service'; +import { ChangeAnalyzer } from '../data/change-analyzer'; +import { compare, Operation } from 'fast-json-patch'; +import { NormalizedTaskObject } from './models/normalized-task-object.model'; +import { HttpOptions } from '../dspace-rest-v2/dspace-rest-v2.service'; + +const LINK_NAME = 'test'; + +/* tslint:disable:max-classes-per-file */ +class TestTask extends TaskObject { +} + +class TestService extends TasksService { + protected linkPath = LINK_NAME; + protected forceBypassCache = true; + + constructor( + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected dataBuildService: NormalizedObjectBuildService, + protected store: Store, + protected objectCache: ObjectCacheService, + protected halService: HALEndpointService, + protected notificationsService: NotificationsService, + protected http: HttpClient, + protected comparator: DSOChangeAnalyzer) { + super(); + } +} + +class NormalizedTestTaskObject extends NormalizedTaskObject { +} + +class DummyChangeAnalyzer implements ChangeAnalyzer { + diff(object1: NormalizedTestTaskObject, object2: NormalizedTestTaskObject): Operation[] { + return compare((object1 as any).metadata, (object2 as any).metadata); + } + +} +/* tslint:enable:max-classes-per-file */ + +describe('TasksService', () => { + let scheduler: TestScheduler; + let service: TestService; + const taskEndpoint = 'https://rest.api/task'; + const linkPath = 'testTask'; + const requestService = getMockRequestService(); + const halService: any = new HALEndpointServiceStub(taskEndpoint); + const rdbService = {} as RemoteDataBuildService; + const notificationsService = {} as NotificationsService; + const http = {} as HttpClient; + const comparator = new DummyChangeAnalyzer() as any; + const dataBuildService = { + normalize: (object) => object + } as NormalizedObjectBuildService; + const objectCache = { + addPatch: () => { + /* empty */ + }, + getObjectBySelfLink: () => { + /* empty */ + } + } as any; + const store = {} as Store; + + function initTestService(): TestService { + return new TestService( + requestService, + rdbService, + dataBuildService, + store, + objectCache, + halService, + notificationsService, + http, + comparator + ); + } + + beforeEach(() => { + scheduler = getTestScheduler(); + service = initTestService(); + const options: HttpOptions = Object.create({}); + let headers = new HttpHeaders(); + headers = headers.append('Content-Type', 'application/x-www-form-urlencoded'); + options.headers = headers; + + }); + + describe('postToEndpoint', () => { + + it('should configure a new TaskPostRequest', () => { + const expected = new TaskPostRequest(requestService.generateRequestId(), `${taskEndpoint}/${linkPath}`, {}); + scheduler.schedule(() => service.postToEndpoint('testTask', {}).subscribe()); + scheduler.flush(); + + expect(requestService.configure).toHaveBeenCalledWith(expected); + }); + }); + + describe('deleteById', () => { + + it('should configure a new TaskDeleteRequest', () => { + const scopeId = '1234'; + const expected = new TaskDeleteRequest(requestService.generateRequestId(), `${taskEndpoint}/${linkPath}/${scopeId}`, null); + scheduler.schedule(() => service.deleteById('testTask', scopeId).subscribe()); + scheduler.flush(); + + expect(requestService.configure).toHaveBeenCalledWith(expected); + }); + }); + +}); diff --git a/src/app/core/tasks/tasks.service.ts b/src/app/core/tasks/tasks.service.ts new file mode 100644 index 0000000000..f39b144c6a --- /dev/null +++ b/src/app/core/tasks/tasks.service.ts @@ -0,0 +1,125 @@ +import { HttpHeaders } from '@angular/common/http'; + +import { merge as observableMerge, Observable, of as observableOf } from 'rxjs'; +import { distinctUntilChanged, filter, flatMap, map, mergeMap, tap } from 'rxjs/operators'; + +import { DataService } from '../data/data.service'; +import { DeleteRequest, FindAllOptions, PostRequest, TaskDeleteRequest, TaskPostRequest } from '../data/request.models'; +import { isNotEmpty } from '../../shared/empty.util'; +import { HttpOptions } from '../dspace-rest-v2/dspace-rest-v2.service'; +import { ProcessTaskResponse } from './models/process-task-response'; +import { RemoteDataError } from '../data/remote-data-error'; +import { getResponseFromEntry } from '../shared/operators'; +import { ErrorResponse, MessageResponse, RestResponse } from '../cache/response.models'; +import { CacheableObject } from '../cache/object-cache.reducer'; + +/** + * An abstract class that provides methods to handle task requests. + */ +export abstract class TasksService extends DataService { + + public getBrowseEndpoint(options: FindAllOptions): Observable { + return this.halService.getEndpoint(this.linkPath); + } + + /** + * Fetch a RestRequest + * + * @param requestId + * The base endpoint for the type of object + * @return Observable + * server response + */ + protected fetchRequest(requestId: string): Observable { + const responses = this.requestService.getByUUID(requestId).pipe( + getResponseFromEntry() + ); + const errorResponses = responses.pipe( + filter((response: RestResponse) => !response.isSuccessful), + mergeMap((response: ErrorResponse) => observableOf( + new ProcessTaskResponse( + response.isSuccessful, + new RemoteDataError(response.statusCode, response.statusText, response.errorMessage) + )) + )); + const successResponses = responses.pipe( + filter((response: RestResponse) => response.isSuccessful), + map((response: MessageResponse) => new ProcessTaskResponse(response.isSuccessful)), + distinctUntilChanged() + ); + return observableMerge(errorResponses, successResponses); + } + + /** + * Create the HREF for a specific submission object based on its identifier + * + * @param endpoint + * The base endpoint for the type of object + * @param resourceID + * The identifier for the object + */ + protected getEndpointByIDHref(endpoint, resourceID): string { + return isNotEmpty(resourceID) ? `${endpoint}/${resourceID}` : `${endpoint}`; + } + + /** + * Make a new post request + * + * @param linkPath + * The endpoint link name + * @param body + * The request body + * @param scopeId + * The task id to be removed + * @param options + * The HttpOptions object + * @return Observable + * server response + */ + public postToEndpoint(linkPath: string, body: any, scopeId?: string, options?: HttpOptions): Observable { + const requestId = this.requestService.generateRequestId(); + return this.halService.getEndpoint(linkPath).pipe( + filter((href: string) => isNotEmpty(href)), + map((endpointURL: string) => this.getEndpointByIDHref(endpointURL, scopeId)), + distinctUntilChanged(), + map((endpointURL: string) => new TaskPostRequest(requestId, endpointURL, body, options)), + tap((request: PostRequest) => this.requestService.configure(request)), + flatMap((request: PostRequest) => this.fetchRequest(requestId)), + distinctUntilChanged()); + } + + /** + * Delete an existing task on the server + * + * @param linkPath + * The endpoint link name + * @param scopeId + * The task id to be removed + * @param options + * The HttpOptions object + * @return Observable + * server response + */ + public deleteById(linkPath: string, scopeId: string, options?: HttpOptions): Observable { + const requestId = this.requestService.generateRequestId(); + return this.halService.getEndpoint(linkPath || this.linkPath).pipe( + filter((href: string) => isNotEmpty(href)), + distinctUntilChanged(), + map((endpointURL: string) => this.getEndpointByIDHref(endpointURL, scopeId)), + map((endpointURL: string) => new TaskDeleteRequest(requestId, endpointURL, null, options)), + tap((request: DeleteRequest) => this.requestService.configure(request)), + flatMap((request: DeleteRequest) => this.fetchRequest(requestId)), + distinctUntilChanged()); + } + + /** + * Create a new HttpOptions + */ + protected makeHttpOptions() { + const options: HttpOptions = Object.create({}); + let headers = new HttpHeaders(); + headers = headers.append('Content-Type', 'application/x-www-form-urlencoded'); + options.headers = headers; + return options; + } +} diff --git a/src/app/shared/auth-nav-menu/auth-nav-menu.component.html b/src/app/shared/auth-nav-menu/auth-nav-menu.component.html index 97c3e39353..b560283ad5 100644 --- a/src/app/shared/auth-nav-menu/auth-nav-menu.component.html +++ b/src/app/shared/auth-nav-menu/auth-nav-menu.component.html @@ -13,10 +13,9 @@ - - {{(user | async).name}} ({{(user | async).email}}) - - + + + diff --git a/src/app/shared/auth-nav-menu/auth-nav-menu.component.spec.ts b/src/app/shared/auth-nav-menu/auth-nav-menu.component.spec.ts index ff4948caa0..5e01494674 100644 --- a/src/app/shared/auth-nav-menu/auth-nav-menu.component.spec.ts +++ b/src/app/shared/auth-nav-menu/auth-nav-menu.component.spec.ts @@ -228,8 +228,8 @@ describe('AuthNavMenuComponent', () => { fixture.destroy(); component = null; }); - it('should render logout dropdown menu', () => { - const logoutDropdownMenu = deNavMenuItem.query(By.css('ul[id=logoutDropdownMenu]')); + it('should render UserMenuComponent component', () => { + const logoutDropdownMenu = deNavMenuItem.query(By.css('ds-user-menu')); expect(logoutDropdownMenu.nativeElement).toBeDefined(); }); }) diff --git a/src/app/shared/auth-nav-menu/user-menu/user-menu.component.html b/src/app/shared/auth-nav-menu/user-menu/user-menu.component.html new file mode 100644 index 0000000000..fef47b395b --- /dev/null +++ b/src/app/shared/auth-nav-menu/user-menu/user-menu.component.html @@ -0,0 +1,9 @@ + + + {{(user$ | async)?.name}} ({{(user$ | async)?.email}}) + {{'nav.mydspace' | translate}} + + + + + diff --git a/src/app/shared/auth-nav-menu/user-menu/user-menu.component.scss b/src/app/shared/auth-nav-menu/user-menu/user-menu.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/auth-nav-menu/user-menu/user-menu.component.spec.ts b/src/app/shared/auth-nav-menu/user-menu/user-menu.component.spec.ts new file mode 100644 index 0000000000..512d9e0917 --- /dev/null +++ b/src/app/shared/auth-nav-menu/user-menu/user-menu.component.spec.ts @@ -0,0 +1,151 @@ +import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, inject, TestBed } from '@angular/core/testing'; + +import { Store, StoreModule } from '@ngrx/store'; +import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; + +import { UserMenuComponent } from './user-menu.component'; +import { authReducer, AuthState } from '../../../core/auth/auth.reducer'; +import { AuthTokenInfo } from '../../../core/auth/models/auth-token-info.model'; +import { EPersonMock } from '../../testing/eperson-mock'; +import { AppState } from '../../../app.reducer'; +import { MockTranslateLoader } from '../../mocks/mock-translate-loader'; +import { cold } from 'jasmine-marbles'; +import { By } from '@angular/platform-browser'; + +describe('UserMenuComponent', () => { + + let component: UserMenuComponent; + let fixture: ComponentFixture; + let deUserMenu: DebugElement; + let authState: AuthState; + let authStateLoading: AuthState; + + function init() { + authState = { + authenticated: true, + loaded: true, + loading: false, + authToken: new AuthTokenInfo('test_token'), + user: EPersonMock + }; + authStateLoading = { + authenticated: true, + loaded: true, + loading: true, + authToken: null, + user: EPersonMock + }; + } + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + StoreModule.forRoot(authReducer), + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }) + ], + declarations: [ + UserMenuComponent + ], + schemas: [ + NO_ERRORS_SCHEMA + ] + }).compileComponents(); + + })); + + beforeEach(() => { + init(); + }); + + describe('when auth state is loading', () => { + beforeEach(inject([Store], (store: Store) => { + store + .subscribe((state) => { + (state as any).core = Object.create({}); + (state as any).core.auth = authStateLoading; + }); + + // create component and test fixture + fixture = TestBed.createComponent(UserMenuComponent); + + // get test component from the fixture + component = fixture.componentInstance; + + fixture.detectChanges(); + + deUserMenu = fixture.debugElement.query(By.css('div')); + })); + + afterEach(() => { + fixture.destroy(); + }); + + it('should init component properly', () => { + expect(component).toBeDefined(); + + expect(component.loading$).toBeObservable(cold('b', { + b: true + })); + + expect(component.user$).toBeObservable(cold('c', { + c: EPersonMock + })); + + expect(deUserMenu).toBeNull(); + }); + + }); + + describe('when auth state is not loading', () => { + beforeEach(inject([Store], (store: Store) => { + store + .subscribe((state) => { + (state as any).core = Object.create({}); + (state as any).core.auth = authState; + }); + + // create component and test fixture + fixture = TestBed.createComponent(UserMenuComponent); + + // get test component from the fixture + component = fixture.componentInstance; + + fixture.detectChanges(); + + deUserMenu = fixture.debugElement.query(By.css('div')); + })); + + afterEach(() => { + fixture.destroy(); + }); + + it('should init component properly', () => { + expect(component).toBeDefined(); + + expect(component.loading$).toBeObservable(cold('b', { + b: false + })); + + expect(component.user$).toBeObservable(cold('c', { + c: EPersonMock + })); + + expect(deUserMenu).toBeDefined(); + }); + + it('should display user name and email', () => { + const user = 'User Test (test@test.com)'; + const span = deUserMenu.query(By.css('.dropdown-item-text')); + expect(span).toBeDefined(); + expect(span.nativeElement.innerHTML).toBe(user); + }) + + }); + +}); diff --git a/src/app/shared/auth-nav-menu/user-menu/user-menu.component.ts b/src/app/shared/auth-nav-menu/user-menu/user-menu.component.ts new file mode 100644 index 0000000000..e3c21b4e24 --- /dev/null +++ b/src/app/shared/auth-nav-menu/user-menu/user-menu.component.ts @@ -0,0 +1,54 @@ +import { Component, OnInit } from '@angular/core'; + +import { Observable } from 'rxjs'; +import { select, Store } from '@ngrx/store'; + +import { EPerson } from '../../../core/eperson/models/eperson.model'; +import { AppState } from '../../../app.reducer'; +import { getAuthenticatedUser, isAuthenticationLoading } from '../../../core/auth/selectors'; +import { MYDSPACE_ROUTE } from '../../../+my-dspace-page/my-dspace-page.component'; + +/** + * This component represents the user nav menu. + */ +@Component({ + selector: 'ds-user-menu', + templateUrl: './user-menu.component.html', + styleUrls: ['./user-menu.component.scss'] +}) +export class UserMenuComponent implements OnInit { + + /** + * True if the authentication is loading. + * @type {Observable} + */ + public loading$: Observable; + + /** + * The authenticated user. + * @type {Observable} + */ + public user$: Observable; + + /** + * The mydspace page route. + * @type {string} + */ + public mydspaceRoute = MYDSPACE_ROUTE; + + constructor(private store: Store) { + } + + /** + * Initialize all instance variables + */ + ngOnInit(): void { + + // set loading + this.loading$ = this.store.pipe(select(isAuthenticationLoading)); + + // set user + this.user$ = this.store.pipe(select(getAuthenticatedUser)); + + } +} diff --git a/src/app/shared/dso-selector/dso-selector/dso-selector.component.html b/src/app/shared/dso-selector/dso-selector/dso-selector.component.html index 1e0deed4b9..662144823d 100644 --- a/src/app/shared/dso-selector/dso-selector/dso-selector.component.html +++ b/src/app/shared/dso-selector/dso-selector/dso-selector.component.html @@ -13,8 +13,8 @@ + title="{{ listEntry.indexableObject.name }}" + (click)="onSelect.emit(listEntry.indexableObject)" #listEntryElement> - \ No newline at end of file + diff --git a/src/app/shared/dso-selector/dso-selector/dso-selector.component.spec.ts b/src/app/shared/dso-selector/dso-selector/dso-selector.component.spec.ts index 04111a4ea6..5ec553222b 100644 --- a/src/app/shared/dso-selector/dso-selector/dso-selector.component.spec.ts +++ b/src/app/shared/dso-selector/dso-selector/dso-selector.component.spec.ts @@ -1,4 +1,4 @@ -import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { TranslateModule } from '@ngx-translate/core'; import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core'; import { DSOSelectorComponent } from './dso-selector.component'; @@ -27,7 +27,7 @@ describe('DSOSelectorComponent', () => { language: undefined })] }; - searchResult.dspaceObject = item; + searchResult.indexableObject = item; searchResult.hitHighlights = {}; const searchService = jasmine.createSpyObj('searchService', { search: observableOf(new RemoteData(false, false, true, undefined, new PaginatedList(undefined, [searchResult]))) diff --git a/src/app/shared/dso-selector/modal-wrappers/create-collection-parent-selector/create-collection-parent-selector.component.ts b/src/app/shared/dso-selector/modal-wrappers/create-collection-parent-selector/create-collection-parent-selector.component.ts index 1e129c0dbe..0533addb01 100644 --- a/src/app/shared/dso-selector/modal-wrappers/create-collection-parent-selector/create-collection-parent-selector.component.ts +++ b/src/app/shared/dso-selector/modal-wrappers/create-collection-parent-selector/create-collection-parent-selector.component.ts @@ -1,7 +1,5 @@ -import { Component, Input, OnInit } from '@angular/core'; +import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, NavigationExtras, Router } from '@angular/router'; -import { Community } from '../../../../core/shared/community.model'; -import { RemoteData } from '../../../../core/data/remote-data'; import { DSpaceObjectType } from '../../../../core/shared/dspace-object-type.model'; import { DSpaceObject } from '../../../../core/shared/dspace-object.model'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; @@ -9,10 +7,7 @@ import { COLLECTION_PARENT_PARAMETER, getCollectionCreatePath } from '../../../../+collection-page/collection-page-routing.module'; -import { - DSOSelectorModalWrapperComponent, - SelectorActionType -} from '../dso-selector-modal-wrapper.component'; +import { DSOSelectorModalWrapperComponent, SelectorActionType } from '../dso-selector-modal-wrapper.component'; /** * Component to wrap a list of existing communities inside a modal 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 dac5888bf7..29af9f624e 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 @@ -1,18 +1,9 @@ -import { Component, Input, OnInit } from '@angular/core'; +import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; -import { Community } from '../../../../core/shared/community.model'; -import { RemoteData } from '../../../../core/data/remote-data'; -import { Collection } from '../../../../core/shared/collection.model'; import { DSpaceObjectType } from '../../../../core/shared/dspace-object-type.model'; import { DSpaceObject } from '../../../../core/shared/dspace-object.model'; -import { hasValue } from '../../../empty.util'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { map } from 'rxjs/operators'; -import { Observable } from 'rxjs'; -import { - DSOSelectorModalWrapperComponent, - SelectorActionType -} from '../dso-selector-modal-wrapper.component'; +import { DSOSelectorModalWrapperComponent, SelectorActionType } from '../dso-selector-modal-wrapper.component'; /** * Component to wrap a list of existing collections inside a modal 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 ea857f7d62..4ceaeccb3a 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 @@ -5,10 +5,7 @@ import { DSpaceObjectType } from '../../../core/shared/dspace-object-type.model' import { RemoteData } from '../../../core/data/remote-data'; import { Item } from '../../../core/shared/item.model'; import { of as observableOf } from 'rxjs'; -import { - DSOSelectorModalWrapperComponent, - SelectorActionType -} from './dso-selector-modal-wrapper.component'; +import { DSOSelectorModalWrapperComponent, SelectorActionType } from './dso-selector-modal-wrapper.component'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { ActivatedRoute } from '@angular/router'; import { DSpaceObject } from '../../../core/shared/dspace-object.model'; @@ -16,7 +13,7 @@ import { first } from 'rxjs/operators'; import { By } from '@angular/platform-browser'; import { DSOSelectorComponent } from '../dso-selector/dso-selector.component'; import { MockComponent } from 'ng-mocks'; -import { MetadataMap, MetadataValue } from '../../../core/shared/metadata.models'; +import { MetadataValue } from '../../../core/shared/metadata.models'; describe('DSOSelectorModalWrapperComponent', () => { let component: DSOSelectorModalWrapperComponent; 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 351a92302c..881476cac6 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,4 +1,4 @@ -import { Component, Injectable, Input, OnInit } from '@angular/core'; +import { Injectable, Input, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Observable } from 'rxjs'; import { DSpaceObject } from '../../../core/shared/dspace-object.model'; diff --git a/src/app/shared/dso-selector/modal-wrappers/edit-item-selector/edit-item-selector.component.ts b/src/app/shared/dso-selector/modal-wrappers/edit-item-selector/edit-item-selector.component.ts index 9182df8045..dae36d3017 100644 --- a/src/app/shared/dso-selector/modal-wrappers/edit-item-selector/edit-item-selector.component.ts +++ b/src/app/shared/dso-selector/modal-wrappers/edit-item-selector/edit-item-selector.component.ts @@ -1,19 +1,10 @@ -import { Component, Input, OnInit } from '@angular/core'; -import { ActivatedRoute, NavigationExtras, Router } from '@angular/router'; -import { Community } from '../../../../core/shared/community.model'; -import { RemoteData } from '../../../../core/data/remote-data'; +import { Component, OnInit } from '@angular/core'; +import { ActivatedRoute, Router } from '@angular/router'; import { DSpaceObjectType } from '../../../../core/shared/dspace-object-type.model'; import { DSpaceObject } from '../../../../core/shared/dspace-object.model'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { Collection } from '../../../../core/shared/collection.model'; -import { Observable } from 'rxjs'; -import { map } from 'rxjs/operators'; -import { Item } from '../../../../core/shared/item.model'; import { getItemEditPath } from '../../../../+item-page/item-page-routing.module'; -import { - DSOSelectorModalWrapperComponent, - SelectorActionType -} from '../dso-selector-modal-wrapper.component'; +import { DSOSelectorModalWrapperComponent, SelectorActionType } from '../dso-selector-modal-wrapper.component'; /** * Component to wrap a list of existing items inside a modal diff --git a/src/app/shared/form/builder/ds-dynamic-form-ui/models/tag/dynamic-tag.component.ts b/src/app/shared/form/builder/ds-dynamic-form-ui/models/tag/dynamic-tag.component.ts index d61134347a..a44a20d4bd 100644 --- a/src/app/shared/form/builder/ds-dynamic-form-ui/models/tag/dynamic-tag.component.ts +++ b/src/app/shared/form/builder/ds-dynamic-form-ui/models/tag/dynamic-tag.component.ts @@ -168,7 +168,7 @@ export class DsDynamicTagComponent extends DynamicFormControlComponent implement } private addTagsToChips() { - if (!this.hasAuthority || !this.model.authorityOptions.closed) { + if (hasValue(this.currentValue) && (!this.hasAuthority || !this.model.authorityOptions.closed)) { let res: string[] = []; res = this.currentValue.split(','); diff --git a/src/app/shared/input-suggestions/input-suggestions.component.ts b/src/app/shared/input-suggestions/input-suggestions.component.ts index 727421c83e..9f59f42cc4 100644 --- a/src/app/shared/input-suggestions/input-suggestions.component.ts +++ b/src/app/shared/input-suggestions/input-suggestions.component.ts @@ -12,7 +12,7 @@ import { ViewChildren } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; -import { hasValue, isNotEmpty, isNotUndefined } from '../empty.util'; +import { hasValue, isNotEmpty } from '../empty.util'; import { InputSuggestion } from './input-suggestions.model'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; diff --git a/src/app/shared/items/switcher/item-type-switcher.component.ts b/src/app/shared/items/switcher/item-type-switcher.component.ts index 3a3f193114..a3296b8f13 100644 --- a/src/app/shared/items/switcher/item-type-switcher.component.ts +++ b/src/app/shared/items/switcher/item-type-switcher.component.ts @@ -56,7 +56,7 @@ export class ItemTypeSwitcherComponent implements OnInit { let item: Item; if (hasValue((this.object as any).dspaceObject)) { const searchResult = this.object as ItemSearchResult; - item = searchResult.dspaceObject; + item = searchResult.indexableObject; } else { item = this.object as Item; } diff --git a/src/app/shared/log-out/log-out.component.html b/src/app/shared/log-out/log-out.component.html index f3ceae0087..d522fc6fb9 100644 --- a/src/app/shared/log-out/log-out.component.html +++ b/src/app/shared/log-out/log-out.component.html @@ -1,7 +1,6 @@ - - + - {{ error | async }} + {{ error | async }} {{"logout.form.submit" | translate}} diff --git a/src/app/shared/log-out/log-out.component.ts b/src/app/shared/log-out/log-out.component.ts index 9e8e7f7865..6fa71caa32 100644 --- a/src/app/shared/log-out/log-out.component.ts +++ b/src/app/shared/log-out/log-out.component.ts @@ -1,21 +1,12 @@ -import { Component, OnDestroy, OnInit } from '@angular/core'; +import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; -// @ngrx +import { Observable } from 'rxjs'; import { select, Store } from '@ngrx/store'; -// actions import { LogOutAction } from '../../core/auth/auth.actions'; - -// reducers -import { - getLogOutError, - isAuthenticated, - isAuthenticationLoading, -} from '../../core/auth/selectors'; - +import { getLogOutError, } from '../../core/auth/selectors'; import { AppState } from '../../app.reducer'; -import { Observable } from 'rxjs'; import { fadeOut } from '../animations/fade'; @Component({ @@ -24,49 +15,28 @@ import { fadeOut } from '../animations/fade'; styleUrls: ['./log-out.component.scss'], animations: [fadeOut] }) -export class LogOutComponent implements OnDestroy, OnInit { +export class LogOutComponent implements OnInit { /** * The error if authentication fails. * @type {Observable} */ public error: Observable; - /** - * True if the logout is loading. - * @type {boolean} - */ - public loading: Observable; - - /** - * Component state. - * @type {boolean} - */ - private alive = true; - /** * @constructor * @param {Store} store + * @param {Router} router */ constructor(private router: Router, private store: Store) { } - /** - * Lifecycle hook that is called when a directive, pipe or service is destroyed. - */ - public ngOnDestroy() { - this.alive = false; - } - /** * Lifecycle hook that is called after data-bound properties of a directive are initialized. */ ngOnInit() { // set error this.error = this.store.pipe(select(getLogOutError)); - - // set loading - this.loading = this.store.pipe(select(isAuthenticationLoading)); } /** diff --git a/src/app/shared/menu/menu-item/onclick-menu-item.component.spec.ts b/src/app/shared/menu/menu-item/onclick-menu-item.component.spec.ts index dd031a96e0..dbe6fdab6a 100644 --- a/src/app/shared/menu/menu-item/onclick-menu-item.component.spec.ts +++ b/src/app/shared/menu/menu-item/onclick-menu-item.component.spec.ts @@ -1,5 +1,4 @@ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; -import { TextMenuItemComponent } from './text-menu-item.component'; import { TranslateModule } from '@ngx-translate/core'; import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core'; import { By } from '@angular/platform-browser'; diff --git a/src/app/shared/mocks/mock-remote-data-build.service.ts b/src/app/shared/mocks/mock-remote-data-build.service.ts index 3cab439581..6a05c9bf36 100644 --- a/src/app/shared/mocks/mock-remote-data-build.service.ts +++ b/src/app/shared/mocks/mock-remote-data-build.service.ts @@ -1,5 +1,5 @@ -import {of as observableOf, Observable } from 'rxjs'; -import { map, take } from 'rxjs/operators'; +import { Observable, of as observableOf } from 'rxjs'; +import { map } from 'rxjs/operators'; import { RemoteDataBuildService } from '../../core/cache/builders/remote-data-build.service'; import { RemoteData } from '../../core/data/remote-data'; import { RequestEntry } from '../../core/data/request.reducer'; diff --git a/src/app/shared/mocks/mock-request.service.ts b/src/app/shared/mocks/mock-request.service.ts index ce09f6d85e..9a320b749c 100644 --- a/src/app/shared/mocks/mock-request.service.ts +++ b/src/app/shared/mocks/mock-request.service.ts @@ -8,6 +8,7 @@ export function getMockRequestService(requestEntry$: Observable = generateRequestId: 'clients/b186e8ce-e99c-4183-bc9a-42b4821bdb78', getByHref: requestEntry$, getByUUID: requestEntry$, + uriEncodeBody: jasmine.createSpy('uriEncodeBody'), /* tslint:disable:no-empty */ removeByHrefSubstring: () => {} /* tslint:enable:no-empty */ diff --git a/src/app/shared/mocks/mock-role-service.ts b/src/app/shared/mocks/mock-role-service.ts new file mode 100644 index 0000000000..dad296f986 --- /dev/null +++ b/src/app/shared/mocks/mock-role-service.ts @@ -0,0 +1,51 @@ +import { Observable } from 'rxjs/internal/Observable'; +import { RoleType } from '../../core/roles/role-types'; +import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject'; + +export class MockRoleService { + + _isSubmitter = new BehaviorSubject(true); + _isController = new BehaviorSubject(true); + _isAdmin = new BehaviorSubject(true); + + setSubmitter(isSubmitter: boolean) { + this._isSubmitter.next(isSubmitter); + } + + setController(isController: boolean) { + this._isController.next(isController); + } + + setAdmin(isAdmin: boolean) { + this._isAdmin.next(isAdmin); + } + + isSubmitter(): Observable { + return this._isSubmitter; + } + + isController(): Observable { + return this._isController; + } + + isAdmin(): Observable { + return this._isAdmin; + } + + checkRole(role: RoleType): Observable { + let check: Observable; + switch (role) { + case RoleType.Submitter: + check = this.isSubmitter(); + break; + case RoleType.Controller: + check = this.isController(); + break; + case RoleType.Admin: + check = this.isAdmin(); + break; + } + + return check; + } +} diff --git a/src/app/shared/mocks/mock-router.ts b/src/app/shared/mocks/mock-router.ts index 929e2644e8..fb475a0467 100644 --- a/src/app/shared/mocks/mock-router.ts +++ b/src/app/shared/mocks/mock-router.ts @@ -7,7 +7,10 @@ export class MockRouter { public events = observableOf({}); public routerState = { snapshot: { - url: '' + url: '', + root: { + queryParamMap: null + } } }; @@ -18,4 +21,12 @@ export class MockRouter { setRoute(route) { this.routerState.snapshot.url = route; } + + setParams(paramsMap) { + this.routerState.snapshot.root.queryParamMap = paramsMap; + } + + createUrlTree(commands, navExtras = {}) { + return {}; + } } diff --git a/src/app/shared/mydspace-actions/claimed-task/approve/claimed-task-actions-approve.component.html b/src/app/shared/mydspace-actions/claimed-task/approve/claimed-task-actions-approve.component.html new file mode 100644 index 0000000000..3c41fdbb07 --- /dev/null +++ b/src/app/shared/mydspace-actions/claimed-task/approve/claimed-task-actions-approve.component.html @@ -0,0 +1,8 @@ + + {{'submission.workflow.tasks.generic.processing' | translate}} + {{'submission.workflow.tasks.claimed.approve' | translate}} + diff --git a/src/app/shared/mydspace-actions/claimed-task/approve/claimed-task-actions-approve.component.scss b/src/app/shared/mydspace-actions/claimed-task/approve/claimed-task-actions-approve.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/mydspace-actions/claimed-task/approve/claimed-task-actions-approve.component.spec.ts b/src/app/shared/mydspace-actions/claimed-task/approve/claimed-task-actions-approve.component.spec.ts new file mode 100644 index 0000000000..552d31675e --- /dev/null +++ b/src/app/shared/mydspace-actions/claimed-task/approve/claimed-task-actions-approve.component.spec.ts @@ -0,0 +1,65 @@ +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { By } from '@angular/platform-browser'; +import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; + +import { ClaimedTaskActionsApproveComponent } from './claimed-task-actions-approve.component'; +import { MockTranslateLoader } from '../../../mocks/mock-translate-loader'; + +let component: ClaimedTaskActionsApproveComponent; +let fixture: ComponentFixture; + +describe('ClaimedTaskActionsApproveComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }) + ], + declarations: [ClaimedTaskActionsApproveComponent], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(ClaimedTaskActionsApproveComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(ClaimedTaskActionsApproveComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + afterEach(() => { + fixture = null; + component = null; + }); + + it('should display approve button', () => { + const btn = fixture.debugElement.query(By.css('.btn-success')); + + expect(btn).toBeDefined(); + }); + + it('should display spin icon when approve is pending', () => { + component.processingApprove = true; + fixture.detectChanges(); + + const span = fixture.debugElement.query(By.css('.btn-success .fa-spin')); + + expect(span).toBeDefined(); + }); + + it('should emit approve event', () => { + spyOn(component.approve, 'emit'); + + component.confirmApprove(); + fixture.detectChanges(); + + expect(component.approve.emit).toHaveBeenCalled(); + }); + +}); diff --git a/src/app/shared/mydspace-actions/claimed-task/approve/claimed-task-actions-approve.component.ts b/src/app/shared/mydspace-actions/claimed-task/approve/claimed-task-actions-approve.component.ts new file mode 100644 index 0000000000..8e7c0dab60 --- /dev/null +++ b/src/app/shared/mydspace-actions/claimed-task/approve/claimed-task-actions-approve.component.ts @@ -0,0 +1,32 @@ +import { Component, EventEmitter, Input, Output } from '@angular/core'; + +@Component({ + selector: 'ds-claimed-task-actions-approve', + styleUrls: ['./claimed-task-actions-approve.component.scss'], + templateUrl: './claimed-task-actions-approve.component.html', +}) + +export class ClaimedTaskActionsApproveComponent { + + /** + * A boolean representing if a reject operation is pending + */ + @Input() processingApprove: boolean; + + /** + * CSS classes to append to reject button + */ + @Input() wrapperClass: string; + + /** + * An event fired when a approve action is confirmed. + */ + @Output() approve: EventEmitter = new EventEmitter(); + + /** + * Emit approve event + */ + confirmApprove() { + this.approve.emit(); + } +} diff --git a/src/app/shared/mydspace-actions/claimed-task/claimed-task-actions.component.html b/src/app/shared/mydspace-actions/claimed-task/claimed-task-actions.component.html new file mode 100644 index 0000000000..4b9b93e7e3 --- /dev/null +++ b/src/app/shared/mydspace-actions/claimed-task/claimed-task-actions.component.html @@ -0,0 +1,20 @@ + + + {{'submission.workflow.tasks.claimed.edit' | translate}} + + + + + + + diff --git a/src/app/shared/mydspace-actions/claimed-task/claimed-task-actions.component.scss b/src/app/shared/mydspace-actions/claimed-task/claimed-task-actions.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/mydspace-actions/claimed-task/claimed-task-actions.component.spec.ts b/src/app/shared/mydspace-actions/claimed-task/claimed-task-actions.component.spec.ts new file mode 100644 index 0000000000..4144cb3760 --- /dev/null +++ b/src/app/shared/mydspace-actions/claimed-task/claimed-task-actions.component.spec.ts @@ -0,0 +1,269 @@ +import { ChangeDetectionStrategy, Injector, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing'; +import { Router } from '@angular/router'; +import { By } from '@angular/platform-browser'; + +import { of as observableOf } from 'rxjs'; +import { cold } from 'jasmine-marbles'; +import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; + +import { MockTranslateLoader } from '../../mocks/mock-translate-loader'; +import { NotificationsService } from '../../notifications/notifications.service'; +import { NotificationsServiceStub } from '../../testing/notifications-service-stub'; +import { RouterStub } from '../../testing/router-stub'; +import { RemoteData } from '../../../core/data/remote-data'; +import { Item } from '../../../core/shared/item.model'; +import { ClaimedTaskDataService } from '../../../core/tasks/claimed-task-data.service'; +import { ClaimedTaskActionsComponent } from './claimed-task-actions.component'; +import { ClaimedTask } from '../../../core/tasks/models/claimed-task-object.model'; +import { Workflowitem } from '../../../core/submission/models/workflowitem.model'; + +let component: ClaimedTaskActionsComponent; +let fixture: ComponentFixture; + +let mockObject: ClaimedTask; +let notificationsServiceStub: NotificationsServiceStub; +let router: RouterStub; + +const mockDataService = jasmine.createSpyObj('PoolTaskDataService', { + approveTask: jasmine.createSpy('approveTask'), + rejectTask: jasmine.createSpy('rejectTask'), + returnToPoolTask: jasmine.createSpy('returnToPoolTask'), +}); + +const item = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ], + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); +const rdItem = new RemoteData(false, false, true, null, item); +const workflowitem = Object.assign(new Workflowitem(), { item: observableOf(rdItem) }); +const rdWorkflowitem = new RemoteData(false, false, true, null, workflowitem); +mockObject = Object.assign(new ClaimedTask(), { workflowitem: observableOf(rdWorkflowitem), id: '1234' }); + +describe('ClaimedTaskActionsComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }) + ], + declarations: [ClaimedTaskActionsComponent], + providers: [ + { provide: Injector, useValue: {} }, + { provide: NotificationsService, useValue: new NotificationsServiceStub() }, + { provide: Router, useValue: new RouterStub() }, + { provide: ClaimedTaskDataService, useValue: mockDataService }, + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(ClaimedTaskActionsComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(ClaimedTaskActionsComponent); + component = fixture.componentInstance; + component.object = mockObject; + notificationsServiceStub = TestBed.get(NotificationsService); + router = TestBed.get(Router); + fixture.detectChanges(); + }); + + afterEach(() => { + fixture = null; + component = null; + }); + + it('should init objects properly', () => { + component.object = null; + component.initObjects(mockObject); + + expect(component.object).toEqual(mockObject); + + expect(component.workflowitem$).toBeObservable(cold('(b|)', { + b: rdWorkflowitem.payload + })) + }); + + it('should display edit task button', () => { + const btn = fixture.debugElement.query(By.css('.btn-info')); + + expect(btn).toBeDefined(); + }); + + it('should call approveTask method when approving a task', fakeAsync(() => { + spyOn(component, 'reload'); + mockDataService.approveTask.and.returnValue(observableOf({hasSucceeded: true})); + + component.approve(); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(mockDataService.approveTask).toHaveBeenCalledWith(mockObject.id); + }); + + })); + + it('should display a success notification on approve success', async(() => { + spyOn(component, 'reload'); + mockDataService.approveTask.and.returnValue(observableOf({hasSucceeded: true})); + + component.approve(); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(notificationsServiceStub.success).toHaveBeenCalled(); + }); + })); + + it('should reload page on approve success', async(() => { + spyOn(router, 'navigateByUrl'); + router.url = 'test.url/test'; + mockDataService.approveTask.and.returnValue(observableOf({hasSucceeded: true})); + + component.approve(); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(router.navigateByUrl).toHaveBeenCalledWith('test.url/test'); + }); + })); + + it('should display an error notification on approve failure', async(() => { + mockDataService.approveTask.and.returnValue(observableOf({hasSucceeded: false})); + + component.approve(); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(notificationsServiceStub.error).toHaveBeenCalled(); + }); + })); + + it('should call rejectTask method when rejecting a task', fakeAsync(() => { + spyOn(component, 'reload'); + mockDataService.rejectTask.and.returnValue(observableOf({hasSucceeded: true})); + + component.reject('test reject'); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(mockDataService.rejectTask).toHaveBeenCalledWith('test reject', mockObject.id); + }); + + })); + + it('should display a success notification on reject success', async(() => { + spyOn(component, 'reload'); + mockDataService.rejectTask.and.returnValue(observableOf({hasSucceeded: true})); + + component.reject('test reject'); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(notificationsServiceStub.success).toHaveBeenCalled(); + }); + })); + + it('should reload page on reject success', async(() => { + spyOn(router, 'navigateByUrl'); + router.url = 'test.url/test'; + mockDataService.rejectTask.and.returnValue(observableOf({hasSucceeded: true})); + + component.reject('test reject'); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(router.navigateByUrl).toHaveBeenCalledWith('test.url/test'); + }); + })); + + it('should display an error notification on reject failure', async(() => { + mockDataService.rejectTask.and.returnValue(observableOf({hasSucceeded: false})); + + component.reject('test reject'); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(notificationsServiceStub.error).toHaveBeenCalled(); + }); + })); + + it('should call returnToPoolTask method when returning a task to pool', fakeAsync(() => { + spyOn(component, 'reload'); + mockDataService.returnToPoolTask.and.returnValue(observableOf({hasSucceeded: true})); + + component.returnToPool(); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(mockDataService.returnToPoolTask).toHaveBeenCalledWith( mockObject.id); + }); + + })); + + it('should display a success notification on return to pool success', async(() => { + spyOn(component, 'reload'); + mockDataService.returnToPoolTask.and.returnValue(observableOf({hasSucceeded: true})); + + component.returnToPool(); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(notificationsServiceStub.success).toHaveBeenCalled(); + }); + })); + + it('should reload page on return to pool success', async(() => { + spyOn(router, 'navigateByUrl'); + router.url = 'test.url/test'; + mockDataService.returnToPoolTask.and.returnValue(observableOf({hasSucceeded: true})); + + component.returnToPool(); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(router.navigateByUrl).toHaveBeenCalledWith('test.url/test'); + }); + })); + + it('should display an error notification on return to pool failure', async(() => { + mockDataService.returnToPoolTask.and.returnValue(observableOf({hasSucceeded: false})); + + component.returnToPool(); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(notificationsServiceStub.error).toHaveBeenCalled(); + }); + })); +}); diff --git a/src/app/shared/mydspace-actions/claimed-task/claimed-task-actions.component.ts b/src/app/shared/mydspace-actions/claimed-task/claimed-task-actions.component.ts new file mode 100644 index 0000000000..2a7669f5b1 --- /dev/null +++ b/src/app/shared/mydspace-actions/claimed-task/claimed-task-actions.component.ts @@ -0,0 +1,123 @@ +import { Component, Injector, Input, OnInit } from '@angular/core'; +import { Router } from '@angular/router'; + +import { BehaviorSubject, Observable } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { TranslateService } from '@ngx-translate/core'; + +import { ClaimedTaskDataService } from '../../../core/tasks/claimed-task-data.service'; +import { ClaimedTask } from '../../../core/tasks/models/claimed-task-object.model'; +import { ProcessTaskResponse } from '../../../core/tasks/models/process-task-response'; +import { isNotUndefined } from '../../empty.util'; +import { Workflowitem } from '../../../core/submission/models/workflowitem.model'; +import { RemoteData } from '../../../core/data/remote-data'; +import { MyDSpaceActionsComponent } from '../mydspace-actions'; +import { ResourceType } from '../../../core/shared/resource-type'; +import { NotificationsService } from '../../notifications/notifications.service'; + +/** + * This component represents mydspace actions related to ClaimedTask object. + */ +@Component({ + selector: 'ds-claimed-task-actions', + styleUrls: ['./claimed-task-actions.component.scss'], + templateUrl: './claimed-task-actions.component.html', +}) +export class ClaimedTaskActionsComponent extends MyDSpaceActionsComponent implements OnInit { + + /** + * The ClaimedTask object + */ + @Input() object: ClaimedTask; + + /** + * The workflowitem object that belonging to the ClaimedTask object + */ + public workflowitem$: Observable; + + /** + * A boolean representing if an approve operation is pending + */ + public processingApprove$ = new BehaviorSubject(false); + + /** + * A boolean representing if a reject operation is pending + */ + public processingReject$ = new BehaviorSubject(false); + + /** + * A boolean representing if a return to pool operation is pending + */ + public processingReturnToPool$ = new BehaviorSubject(false); + + /** + * Initialize instance variables + * + * @param {Injector} injector + * @param {Router} router + * @param {NotificationsService} notificationsService + * @param {TranslateService} translate + */ + constructor(protected injector: Injector, + protected router: Router, + protected notificationsService: NotificationsService, + protected translate: TranslateService) { + super(ResourceType.ClaimedTask, injector, router, notificationsService, translate); + } + + /** + * Initialize objects + */ + ngOnInit() { + this.initObjects(this.object); + } + + /** + * Init the ClaimedTask and Workflowitem objects + * + * @param {PoolTask} object + */ + initObjects(object: ClaimedTask) { + this.object = object; + this.workflowitem$ = (this.object.workflowitem as Observable>).pipe( + filter((rd: RemoteData) => ((!rd.isRequestPending) && isNotUndefined(rd.payload))), + map((rd: RemoteData) => rd.payload)); + } + + /** + * Approve the task. + */ + approve() { + this.processingApprove$.next(true); + this.objectDataService.approveTask(this.object.id) + .subscribe((res: ProcessTaskResponse) => { + this.processingApprove$.next(false); + this.handleActionResponse(res.hasSucceeded); + }); + } + + /** + * Reject the task. + */ + reject(reason) { + this.processingReject$.next(true); + this.objectDataService.rejectTask(reason, this.object.id) + .subscribe((res: ProcessTaskResponse) => { + this.processingReject$.next(false); + this.handleActionResponse(res.hasSucceeded); + }); + } + + /** + * Return task to the pool. + */ + returnToPool() { + this.processingReturnToPool$.next(true); + this.objectDataService.returnToPoolTask(this.object.id) + .subscribe((res: ProcessTaskResponse) => { + this.processingReturnToPool$.next(false); + this.handleActionResponse(res.hasSucceeded); + }); + } + +} diff --git a/src/app/shared/mydspace-actions/claimed-task/reject/claimed-task-actions-reject.component.html b/src/app/shared/mydspace-actions/claimed-task/reject/claimed-task-actions-reject.component.html new file mode 100644 index 0000000000..91edee66bd --- /dev/null +++ b/src/app/shared/mydspace-actions/claimed-task/reject/claimed-task-actions-reject.component.html @@ -0,0 +1,38 @@ + + + {{'submission.workflow.tasks.generic.processing' | translate}} + {{'submission.workflow.tasks.claimed.reject.submit' | translate}} + + + + + {{'submission.workflow.tasks.claimed.reject.reason.title' | translate}} + + × + + + + + {{'submission.workflow.tasks.claimed.reject.reason.info' | translate}} + + + + + {{'submission.workflow.tasks.generic.processing' | translate}} + {{'submission.workflow.tasks.claimed.reject.reason.submit' | translate}} + + + + diff --git a/src/app/shared/mydspace-actions/claimed-task/reject/claimed-task-actions-reject.component.scss b/src/app/shared/mydspace-actions/claimed-task/reject/claimed-task-actions-reject.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/mydspace-actions/claimed-task/reject/claimed-task-actions-reject.component.spec.ts b/src/app/shared/mydspace-actions/claimed-task/reject/claimed-task-actions-reject.component.spec.ts new file mode 100644 index 0000000000..d7e0b53748 --- /dev/null +++ b/src/app/shared/mydspace-actions/claimed-task/reject/claimed-task-actions-reject.component.spec.ts @@ -0,0 +1,108 @@ +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing'; +import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms'; +import { By } from '@angular/platform-browser'; + +import { NgbModal, NgbModule } from '@ng-bootstrap/ng-bootstrap'; +import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; + +import { ClaimedTaskActionsRejectComponent } from './claimed-task-actions-reject.component'; +import { MockTranslateLoader } from '../../../mocks/mock-translate-loader'; + +let component: ClaimedTaskActionsRejectComponent; +let fixture: ComponentFixture; +let formBuilder: FormBuilder; +let modalService: NgbModal; + +describe('ClaimedTaskActionsRejectComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + NgbModule.forRoot(), + ReactiveFormsModule, + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }) + ], + declarations: [ClaimedTaskActionsRejectComponent], + providers: [ + FormBuilder, + NgbModal + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(ClaimedTaskActionsRejectComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(ClaimedTaskActionsRejectComponent); + component = fixture.componentInstance; + formBuilder = TestBed.get(FormBuilder); + modalService = TestBed.get(NgbModal); + component.modalRef = modalService.open('ok'); + fixture.detectChanges(); + }); + + afterEach(() => { + fixture = null; + component = null; + modalService = null; + formBuilder = null; + }); + + it('should init reject form properly', () => { + expect(component.rejectForm).toBeDefined(); + expect(component.rejectForm instanceof FormGroup).toBeTruthy(); + expect(component.rejectForm.controls.reason).toBeDefined(); + }); + + it('should display reject button', () => { + const btn = fixture.debugElement.query(By.css('.btn-danger')); + + expect(btn).toBeDefined(); + }); + + it('should display spin icon when reject is pending', () => { + component.processingReject = true; + fixture.detectChanges(); + + const span = fixture.debugElement.query(By.css('.btn-danger .fa-spin')); + + expect(span).toBeDefined(); + }); + + it('should call openRejectModal on reject button click', fakeAsync(() => { + spyOn(component.rejectForm, 'reset'); + const btn = fixture.debugElement.query(By.css('.btn-danger')); + btn.nativeElement.click(); + fixture.detectChanges(); + + expect(component.rejectForm.reset).toHaveBeenCalled(); + expect(component.modalRef).toBeDefined(); + + component.modalRef.close() + })); + + it('should call confirmReject on form submit', fakeAsync(() => { + spyOn(component.reject, 'emit'); + + const btn = fixture.debugElement.query(By.css('.btn-danger')); + btn.nativeElement.click(); + fixture.detectChanges(); + + expect(component.modalRef).toBeDefined(); + + const form = ((document as any).querySelector('form')); + form.dispatchEvent(new Event('ngSubmit')); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(component.reject.emit).toHaveBeenCalled(); + }); + + })); +}); diff --git a/src/app/shared/mydspace-actions/claimed-task/reject/claimed-task-actions-reject.component.ts b/src/app/shared/mydspace-actions/claimed-task/reject/claimed-task-actions-reject.component.ts new file mode 100644 index 0000000000..b66c104695 --- /dev/null +++ b/src/app/shared/mydspace-actions/claimed-task/reject/claimed-task-actions-reject.component.ts @@ -0,0 +1,78 @@ +import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; +import { FormBuilder, FormGroup, Validators } from '@angular/forms'; + +import { NgbModal, NgbModalRef } from '@ng-bootstrap/ng-bootstrap'; + +@Component({ + selector: 'ds-claimed-task-actions-reject', + styleUrls: ['./claimed-task-actions-reject.component.scss'], + templateUrl: './claimed-task-actions-reject.component.html', +}) + +export class ClaimedTaskActionsRejectComponent implements OnInit { + + /** + * A boolean representing if a reject operation is pending + */ + @Input() processingReject: boolean; + + /** + * CSS classes to append to reject button + */ + @Input() wrapperClass: string; + + /** + * An event fired when a reject action is confirmed. + * Event's payload equals to reject reason. + */ + @Output() reject: EventEmitter = new EventEmitter(); + + /** + * The reject form group + */ + public rejectForm: FormGroup; + + /** + * Reference to NgbModal + */ + public modalRef: NgbModalRef; + + /** + * Initialize instance variables + * + * @param {FormBuilder} formBuilder + * @param {NgbModal} modalService + */ + constructor(private formBuilder: FormBuilder, private modalService: NgbModal) { + } + + /** + * Initialize form + */ + ngOnInit() { + this.rejectForm = this.formBuilder.group({ + reason: ['', Validators.required] + }); + + } + + /** + * Close modal and emit reject event + */ + confirmReject() { + this.processingReject = true; + this.modalRef.close('Send Button'); + const reason = this.rejectForm.get('reason').value; + this.reject.emit(reason); + } + + /** + * Open modal + * + * @param content + */ + openRejectModal(content: any) { + this.rejectForm.reset(); + this.modalRef = this.modalService.open(content); + } +} diff --git a/src/app/shared/mydspace-actions/claimed-task/return-to-pool/claimed-task-actions-return-to-pool.component.html b/src/app/shared/mydspace-actions/claimed-task/return-to-pool/claimed-task-actions-return-to-pool.component.html new file mode 100644 index 0000000000..702ce75e7f --- /dev/null +++ b/src/app/shared/mydspace-actions/claimed-task/return-to-pool/claimed-task-actions-return-to-pool.component.html @@ -0,0 +1,8 @@ + + {{'submission.workflow.tasks.generic.processing' | translate}} + {{'submission.workflow.tasks.claimed.return' | translate}} + diff --git a/src/app/shared/mydspace-actions/claimed-task/return-to-pool/claimed-task-actions-return-to-pool.component.scss b/src/app/shared/mydspace-actions/claimed-task/return-to-pool/claimed-task-actions-return-to-pool.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/mydspace-actions/claimed-task/return-to-pool/claimed-task-actions-return-to-pool.component.spec.ts b/src/app/shared/mydspace-actions/claimed-task/return-to-pool/claimed-task-actions-return-to-pool.component.spec.ts new file mode 100644 index 0000000000..d461d9e055 --- /dev/null +++ b/src/app/shared/mydspace-actions/claimed-task/return-to-pool/claimed-task-actions-return-to-pool.component.spec.ts @@ -0,0 +1,65 @@ +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { By } from '@angular/platform-browser'; +import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; + +import { ClaimedTaskActionsReturnToPoolComponent } from './claimed-task-actions-return-to-pool.component'; +import { MockTranslateLoader } from '../../../mocks/mock-translate-loader'; + +let component: ClaimedTaskActionsReturnToPoolComponent; +let fixture: ComponentFixture; + +describe('ClaimedTaskActionsReturnToPoolComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }) + ], + declarations: [ClaimedTaskActionsReturnToPoolComponent], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(ClaimedTaskActionsReturnToPoolComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(ClaimedTaskActionsReturnToPoolComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + afterEach(() => { + fixture = null; + component = null; + }); + + it('should display return to pool button', () => { + const btn = fixture.debugElement.query(By.css('.btn-secondary')); + + expect(btn).toBeDefined(); + }); + + it('should display spin icon when return to pool action is pending', () => { + component.processingReturnToPool = true; + fixture.detectChanges(); + + const span = fixture.debugElement.query(By.css('.btn-secondary .fa-spin')); + + expect(span).toBeDefined(); + }); + + it('should emit return to pool event', () => { + spyOn(component.returnToPool, 'emit'); + + component.confirmReturnToPool(); + fixture.detectChanges(); + + expect(component.returnToPool.emit).toHaveBeenCalled(); + }); + +}); diff --git a/src/app/shared/mydspace-actions/claimed-task/return-to-pool/claimed-task-actions-return-to-pool.component.ts b/src/app/shared/mydspace-actions/claimed-task/return-to-pool/claimed-task-actions-return-to-pool.component.ts new file mode 100644 index 0000000000..1dfe91eb5b --- /dev/null +++ b/src/app/shared/mydspace-actions/claimed-task/return-to-pool/claimed-task-actions-return-to-pool.component.ts @@ -0,0 +1,32 @@ +import { Component, EventEmitter, Input, Output } from '@angular/core'; + +@Component({ + selector: 'ds-claimed-task-actions-return-to-pool', + styleUrls: ['./claimed-task-actions-return-to-pool.component.scss'], + templateUrl: './claimed-task-actions-return-to-pool.component.html', +}) + +export class ClaimedTaskActionsReturnToPoolComponent { + + /** + * A boolean representing if a return to pool operation is pending + */ + @Input() processingReturnToPool: boolean; + + /** + * CSS classes to append to return to pool button + */ + @Input() wrapperClass: string; + + /** + * An event fired when a return to pool action is confirmed. + */ + @Output() returnToPool: EventEmitter = new EventEmitter(); + + /** + * Emit returnToPool event + */ + confirmReturnToPool() { + this.returnToPool.emit(); + } +} diff --git a/src/app/shared/mydspace-actions/item/item-actions.component.html b/src/app/shared/mydspace-actions/item/item-actions.component.html new file mode 100644 index 0000000000..91993466b6 --- /dev/null +++ b/src/app/shared/mydspace-actions/item/item-actions.component.html @@ -0,0 +1,5 @@ + + {{"submission.workflow.generic.view" | translate}} + diff --git a/src/app/shared/mydspace-actions/item/item-actions.component.scss b/src/app/shared/mydspace-actions/item/item-actions.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/mydspace-actions/item/item-actions.component.spec.ts b/src/app/shared/mydspace-actions/item/item-actions.component.spec.ts new file mode 100644 index 0000000000..72be122c8f --- /dev/null +++ b/src/app/shared/mydspace-actions/item/item-actions.component.spec.ts @@ -0,0 +1,96 @@ +import { ChangeDetectionStrategy, Injector, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { Router } from '@angular/router'; + +import { of as observableOf } from 'rxjs'; +import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; + +import { MockTranslateLoader } from '../../mocks/mock-translate-loader'; +import { RouterStub } from '../../testing/router-stub'; +import { Item } from '../../../core/shared/item.model'; +import { ItemActionsComponent } from './item-actions.component'; +import { ItemDataService } from '../../../core/data/item-data.service'; +import { NotificationsService } from '../../notifications/notifications.service'; +import { NotificationsServiceStub } from '../../testing/notifications-service-stub'; + +let component: ItemActionsComponent; +let fixture: ComponentFixture; + +let mockObject: Item; + +const mockDataService = {}; + +mockObject = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ], + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); + +describe('ItemActionsComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }) + ], + declarations: [ItemActionsComponent], + providers: [ + { provide: Injector, useValue: {} }, + { provide: Router, useValue: new RouterStub() }, + { provide: ItemDataService, useValue: mockDataService }, + { provide: NotificationsService, useValue: new NotificationsServiceStub() }, + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(ItemActionsComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(ItemActionsComponent); + component = fixture.componentInstance; + component.object = mockObject; + fixture.detectChanges(); + }); + + afterEach(() => { + fixture = null; + component = null; + }); + + it('should init object properly', () => { + component.object = null; + component.initObjects(mockObject); + + expect(component.object).toEqual(mockObject); + }); + +}); diff --git a/src/app/shared/mydspace-actions/item/item-actions.component.ts b/src/app/shared/mydspace-actions/item/item-actions.component.ts new file mode 100644 index 0000000000..0760fe54e0 --- /dev/null +++ b/src/app/shared/mydspace-actions/item/item-actions.component.ts @@ -0,0 +1,52 @@ +import { Component, Injector, Input } from '@angular/core'; +import { Router } from '@angular/router'; + +import { TranslateService } from '@ngx-translate/core'; + +import { MyDSpaceActionsComponent } from '../mydspace-actions'; +import { ItemDataService } from '../../../core/data/item-data.service'; +import { Item } from '../../../core/shared/item.model'; +import { ResourceType } from '../../../core/shared/resource-type'; +import { NotificationsService } from '../../notifications/notifications.service'; + +/** + * This component represents mydspace actions related to Item object. + */ +@Component({ + selector: 'ds-item-actions', + styleUrls: ['./item-actions.component.scss'], + templateUrl: './item-actions.component.html', +}) + +export class ItemActionsComponent extends MyDSpaceActionsComponent { + + /** + * The Item object + */ + @Input() object: Item; + + /** + * Initialize instance variables + * + * @param {Injector} injector + * @param {Router} router + * @param {NotificationsService} notificationsService + * @param {TranslateService} translate + */ + constructor(protected injector: Injector, + protected router: Router, + protected notificationsService: NotificationsService, + protected translate: TranslateService) { + super(ResourceType.Item, injector, router, notificationsService, translate); + } + + /** + * Init the target object + * + * @param {Item} object + */ + initObjects(object: Item) { + this.object = object; + } + +} diff --git a/src/app/shared/mydspace-actions/mydspace-actions-service.factory.ts b/src/app/shared/mydspace-actions/mydspace-actions-service.factory.ts new file mode 100644 index 0000000000..7aa948f689 --- /dev/null +++ b/src/app/shared/mydspace-actions/mydspace-actions-service.factory.ts @@ -0,0 +1,36 @@ +import { DataService } from '../../core/data/data.service'; +import { ResourceType } from '../../core/shared/resource-type'; +import { WorkspaceitemDataService } from '../../core/submission/workspaceitem-data.service'; +import { ClaimedTaskDataService } from '../../core/tasks/claimed-task-data.service'; +import { PoolTaskDataService } from '../../core/tasks/pool-task-data.service'; +import { WorkflowitemDataService } from '../../core/submission/workflowitem-data.service'; +import { CacheableObject } from '../../core/cache/object-cache.reducer'; +import { ItemDataService } from '../../core/data/item-data.service'; + +/** + * Class to return DataService for given ResourceType + */ +export class MydspaceActionsServiceFactory> { + public getConstructor(type: ResourceType): TService { + switch (type) { + case ResourceType.Item: { + return ItemDataService as any; + } + case ResourceType.Workspaceitem: { + return WorkspaceitemDataService as any; + } + case ResourceType.Workflowitem: { + return WorkflowitemDataService as any; + } + case ResourceType.ClaimedTask: { + return ClaimedTaskDataService as any; + } + case ResourceType.PoolTask: { + return PoolTaskDataService as any; + } + default: { + return undefined; + } + } + } +} diff --git a/src/app/shared/mydspace-actions/mydspace-actions.ts b/src/app/shared/mydspace-actions/mydspace-actions.ts new file mode 100644 index 0000000000..8e465644c3 --- /dev/null +++ b/src/app/shared/mydspace-actions/mydspace-actions.ts @@ -0,0 +1,99 @@ +import { Router } from '@angular/router'; +import { Injector, Input } from '@angular/core'; + +import { find } from 'rxjs/operators'; + +import { MydspaceActionsServiceFactory } from './mydspace-actions-service.factory'; +import { RemoteData } from '../../core/data/remote-data'; +import { DataService } from '../../core/data/data.service'; +import { DSpaceObject } from '../../core/shared/dspace-object.model'; +import { ResourceType } from '../../core/shared/resource-type'; +import { NotificationOptions } from '../notifications/models/notification-options.model'; +import { NotificationsService } from '../notifications/notifications.service'; +import { TranslateService } from '@ngx-translate/core'; + +/** + * Abstract class for all different representations of mydspace actions + */ +export abstract class MyDSpaceActionsComponent> { + + /** + * The target mydspace object + */ + @Input() abstract object: T; + + /** + * Instance of DataService realted to mydspace object + */ + protected objectDataService: TService; + + /** + * Initialize instance variables + * + * @param {ResourceType} objectType + * @param {Injector} injector + * @param {Router} router + * @param {NotificationsService} notificationsService + * @param {TranslateService} translate + */ + constructor( + protected objectType: ResourceType, + protected injector: Injector, + protected router: Router, + protected notificationsService: NotificationsService, + protected translate: TranslateService) { + const factory = new MydspaceActionsServiceFactory(); + this.objectDataService = injector.get(factory.getConstructor(objectType)); + } + + /** + * Abstract method called to init the target object + * + * @param {T} object + */ + abstract initObjects(object: T): void; + + /** + * Refresh current page + */ + reload(): void { + // override the route reuse strategy + this.router.routeReuseStrategy.shouldReuseRoute = () => { + return false; + }; + this.router.navigated = false; + const url = decodeURIComponent(this.router.url); + this.router.navigateByUrl(url); + } + + /** + * Override the target object with a refreshed one + */ + refresh(): void { + // find object by id + this.objectDataService.findById(this.object.id).pipe( + find((rd: RemoteData) => rd.hasSucceeded) + ).subscribe((rd: RemoteData) => { + this.initObjects(rd.payload as T); + }); + } + + /** + * Handle action response and show properly notification + * + * @param result + * true on success, false otherwise + */ + handleActionResponse(result: boolean): void { + if (result) { + this.reload(); + this.notificationsService.success(null, + this.translate.get('submission.workflow.tasks.generic.success'), + new NotificationOptions(5000, false)); + } else { + this.notificationsService.error(null, + this.translate.get('submission.workflow.tasks.generic.error'), + new NotificationOptions(20000, true)); + } + } +} diff --git a/src/app/shared/mydspace-actions/pool-task/pool-task-actions.component.html b/src/app/shared/mydspace-actions/pool-task/pool-task-actions.component.html new file mode 100644 index 0000000000..6f4ffffad3 --- /dev/null +++ b/src/app/shared/mydspace-actions/pool-task/pool-task-actions.component.html @@ -0,0 +1,8 @@ + + {{'submission.workflow.tasks.generic.processing' | translate}} + {{'submission.workflow.tasks.pool.claim' | translate}} + diff --git a/src/app/shared/mydspace-actions/pool-task/pool-task-actions.component.scss b/src/app/shared/mydspace-actions/pool-task/pool-task-actions.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/mydspace-actions/pool-task/pool-task-actions.component.spec.ts b/src/app/shared/mydspace-actions/pool-task/pool-task-actions.component.spec.ts new file mode 100644 index 0000000000..1c0e8e71fa --- /dev/null +++ b/src/app/shared/mydspace-actions/pool-task/pool-task-actions.component.spec.ts @@ -0,0 +1,170 @@ +import { ChangeDetectionStrategy, Injector, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing'; +import { Router } from '@angular/router'; +import { By } from '@angular/platform-browser'; + +import { of as observableOf } from 'rxjs'; +import { cold } from 'jasmine-marbles'; +import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; + +import { MockTranslateLoader } from '../../mocks/mock-translate-loader'; +import { NotificationsService } from '../../notifications/notifications.service'; +import { NotificationsServiceStub } from '../../testing/notifications-service-stub'; +import { RouterStub } from '../../testing/router-stub'; +import { RemoteData } from '../../../core/data/remote-data'; +import { Item } from '../../../core/shared/item.model'; +import { PoolTaskDataService } from '../../../core/tasks/pool-task-data.service'; +import { PoolTaskActionsComponent } from './pool-task-actions.component'; +import { PoolTask } from '../../../core/tasks/models/pool-task-object.model'; +import { Workflowitem } from '../../../core/submission/models/workflowitem.model'; + +let component: PoolTaskActionsComponent; +let fixture: ComponentFixture; + +let mockObject: PoolTask; +let notificationsServiceStub: NotificationsServiceStub; +let router: RouterStub; + +const mockDataService = jasmine.createSpyObj('PoolTaskDataService', { + claimTask: jasmine.createSpy('claimTask') +}); + +const item = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ], + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); +const rdItem = new RemoteData(false, false, true, null, item); +const workflowitem = Object.assign(new Workflowitem(), { item: observableOf(rdItem) }); +const rdWorkflowitem = new RemoteData(false, false, true, null, workflowitem); +mockObject = Object.assign(new PoolTask(), { workflowitem: observableOf(rdWorkflowitem), id: '1234' }); + +describe('PoolTaskActionsComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }) + ], + declarations: [PoolTaskActionsComponent], + providers: [ + { provide: Injector, useValue: {} }, + { provide: NotificationsService, useValue: new NotificationsServiceStub() }, + { provide: Router, useValue: new RouterStub() }, + { provide: PoolTaskDataService, useValue: mockDataService }, + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(PoolTaskActionsComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(PoolTaskActionsComponent); + component = fixture.componentInstance; + component.object = mockObject; + notificationsServiceStub = TestBed.get(NotificationsService); + router = TestBed.get(Router); + fixture.detectChanges(); + }); + + afterEach(() => { + fixture = null; + component = null; + }); + + it('should init objects properly', () => { + component.object = null; + component.initObjects(mockObject); + + expect(component.object).toEqual(mockObject); + + expect(component.workflowitem$).toBeObservable(cold('(b|)', { + b: rdWorkflowitem.payload + })) + }); + + it('should display claim task button', () => { + const btn = fixture.debugElement.query(By.css('.btn-info')); + + expect(btn).toBeDefined(); + }); + + it('should call claimTask method on claim', fakeAsync(() => { + spyOn(component, 'reload'); + mockDataService.claimTask.and.returnValue(observableOf({hasSucceeded: true})); + + component.claim(); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(mockDataService.claimTask).toHaveBeenCalledWith(mockObject.id); + }); + + })); + + it('should display a success notification on claim success', async(() => { + spyOn(component, 'reload'); + mockDataService.claimTask.and.returnValue(observableOf({hasSucceeded: true})); + + component.claim(); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(notificationsServiceStub.success).toHaveBeenCalled(); + }); + })); + + it('should reload page on claim success', async(() => { + spyOn(router, 'navigateByUrl'); + router.url = 'test.url/test'; + mockDataService.claimTask.and.returnValue(observableOf({hasSucceeded: true})); + + component.claim(); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(router.navigateByUrl).toHaveBeenCalledWith('test.url/test'); + }); + })); + + it('should display an error notification on claim failure', async(() => { + mockDataService.claimTask.and.returnValue(observableOf({hasSucceeded: false})); + + component.claim(); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(notificationsServiceStub.error).toHaveBeenCalled(); + }); + })); + +}); diff --git a/src/app/shared/mydspace-actions/pool-task/pool-task-actions.component.ts b/src/app/shared/mydspace-actions/pool-task/pool-task-actions.component.ts new file mode 100644 index 0000000000..bd8f3f1a37 --- /dev/null +++ b/src/app/shared/mydspace-actions/pool-task/pool-task-actions.component.ts @@ -0,0 +1,89 @@ +import { Component, Injector, Input } from '@angular/core'; +import { Router } from '@angular/router'; + +import { BehaviorSubject, Observable } from 'rxjs'; +import { filter, map } from 'rxjs/operators'; +import { TranslateService } from '@ngx-translate/core'; + +import { Workflowitem } from '../../../core/submission/models/workflowitem.model'; +import { ProcessTaskResponse } from '../../../core/tasks/models/process-task-response'; +import { RemoteData } from '../../../core/data/remote-data'; +import { PoolTask } from '../../../core/tasks/models/pool-task-object.model'; +import { PoolTaskDataService } from '../../../core/tasks/pool-task-data.service'; +import { isNotUndefined } from '../../empty.util'; +import { MyDSpaceActionsComponent } from '../mydspace-actions'; +import { ResourceType } from '../../../core/shared/resource-type'; +import { NotificationsService } from '../../notifications/notifications.service'; + +/** + * This component represents mydspace actions related to PoolTask object. + */ +@Component({ + selector: 'ds-pool-task-actions', + styleUrls: ['./pool-task-actions.component.scss'], + templateUrl: './pool-task-actions.component.html', +}) +export class PoolTaskActionsComponent extends MyDSpaceActionsComponent { + + /** + * The PoolTask object + */ + @Input() object: PoolTask; + + /** + * A boolean representing if a claim operation is pending + * @type {BehaviorSubject} + */ + public processingClaim$ = new BehaviorSubject(false); + + /** + * The workflowitem object that belonging to the PoolTask object + */ + public workflowitem$: Observable; + + /** + * Initialize instance variables + * + * @param {Injector} injector + * @param {Router} router + * @param {NotificationsService} notificationsService + * @param {TranslateService} translate + */ + constructor(protected injector: Injector, + protected router: Router, + protected notificationsService: NotificationsService, + protected translate: TranslateService) { + super(ResourceType.PoolTask, injector, router, notificationsService, translate); + } + + /** + * Initialize objects + */ + ngOnInit() { + this.initObjects(this.object); + } + + /** + * Init the PoolTask and Workflowitem objects + * + * @param {PoolTask} object + */ + initObjects(object: PoolTask) { + this.object = object; + this.workflowitem$ = (this.object.workflowitem as Observable>).pipe( + filter((rd: RemoteData) => ((!rd.isRequestPending) && isNotUndefined(rd.payload))), + map((rd: RemoteData) => rd.payload)); + } + + /** + * Claim the task. + */ + claim() { + this.processingClaim$.next(true); + this.objectDataService.claimTask(this.object.id) + .subscribe((res: ProcessTaskResponse) => { + this.handleActionResponse(res.hasSucceeded); + this.processingClaim$.next(false); + }); + } +} diff --git a/src/app/shared/mydspace-actions/workflowitem/workflowitem-actions.component.html b/src/app/shared/mydspace-actions/workflowitem/workflowitem-actions.component.html new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/mydspace-actions/workflowitem/workflowitem-actions.component.scss b/src/app/shared/mydspace-actions/workflowitem/workflowitem-actions.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/mydspace-actions/workflowitem/workflowitem-actions.component.spec.ts b/src/app/shared/mydspace-actions/workflowitem/workflowitem-actions.component.spec.ts new file mode 100644 index 0000000000..7533565afe --- /dev/null +++ b/src/app/shared/mydspace-actions/workflowitem/workflowitem-actions.component.spec.ts @@ -0,0 +1,98 @@ +import { ChangeDetectionStrategy, Injector, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { Router } from '@angular/router'; + +import { of as observableOf } from 'rxjs'; +import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; + +import { MockTranslateLoader } from '../../mocks/mock-translate-loader'; +import { RouterStub } from '../../testing/router-stub'; +import { RemoteData } from '../../../core/data/remote-data'; +import { Item } from '../../../core/shared/item.model'; +import { Workflowitem } from '../../../core/submission/models/workflowitem.model'; +import { WorkflowitemActionsComponent } from './workflowitem-actions.component'; +import { WorkflowitemDataService } from '../../../core/submission/workflowitem-data.service'; +import { NotificationsService } from '../../notifications/notifications.service'; +import { NotificationsServiceStub } from '../../testing/notifications-service-stub'; + +let component: WorkflowitemActionsComponent; +let fixture: ComponentFixture; + +let mockObject: Workflowitem; + +const mockDataService = {}; + +const item = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ], + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); +const rd = new RemoteData(false, false, true, null, item); +mockObject = Object.assign(new Workflowitem(), { item: observableOf(rd), id: '1234', uuid: '1234' }); + +describe('WorkflowitemActionsComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }) + ], + declarations: [WorkflowitemActionsComponent], + providers: [ + { provide: Injector, useValue: {} }, + { provide: Router, useValue: new RouterStub() }, + { provide: WorkflowitemDataService, useValue: mockDataService }, + { provide: NotificationsService, useValue: new NotificationsServiceStub() }, + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(WorkflowitemActionsComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(WorkflowitemActionsComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + afterEach(() => { + fixture = null; + component = null; + }); + + it('should init object properly', () => { + component.initObjects(mockObject); + + expect(component.object).toEqual(mockObject); + }); + +}); diff --git a/src/app/shared/mydspace-actions/workflowitem/workflowitem-actions.component.ts b/src/app/shared/mydspace-actions/workflowitem/workflowitem-actions.component.ts new file mode 100644 index 0000000000..a6304bf5d4 --- /dev/null +++ b/src/app/shared/mydspace-actions/workflowitem/workflowitem-actions.component.ts @@ -0,0 +1,51 @@ +import { Component, Injector, Input } from '@angular/core'; +import { Router } from '@angular/router'; + +import { TranslateService } from '@ngx-translate/core'; + +import { MyDSpaceActionsComponent } from '../mydspace-actions'; +import { Workflowitem } from '../../../core/submission/models/workflowitem.model'; +import { WorkflowitemDataService } from '../../../core/submission/workflowitem-data.service'; +import { ResourceType } from '../../../core/shared/resource-type'; +import { NotificationsService } from '../../notifications/notifications.service'; + +/** + * This component represents mydspace actions related to Workflowitem object. + */ +@Component({ + selector: 'ds-workflowitem-actions', + styleUrls: ['./workflowitem-actions.component.scss'], + templateUrl: './workflowitem-actions.component.html', +}) +export class WorkflowitemActionsComponent extends MyDSpaceActionsComponent { + + /** + * The Workflowitem object + */ + @Input() object: Workflowitem; + + /** + * Initialize instance variables + * + * @param {Injector} injector + * @param {Router} router + * @param {NotificationsService} notificationsService + * @param {TranslateService} translate + */ + constructor(protected injector: Injector, + protected router: Router, + protected notificationsService: NotificationsService, + protected translate: TranslateService) { + super(ResourceType.Workflowitem, injector, router, notificationsService, translate); + } + + /** + * Init the target object + * + * @param {Workflowitem} object + */ + initObjects(object: Workflowitem) { + this.object = object; + } + +} diff --git a/src/app/shared/mydspace-actions/workspaceitem/workspaceitem-actions.component.html b/src/app/shared/mydspace-actions/workspaceitem/workspaceitem-actions.component.html new file mode 100644 index 0000000000..6c3a047f73 --- /dev/null +++ b/src/app/shared/mydspace-actions/workspaceitem/workspaceitem-actions.component.html @@ -0,0 +1,30 @@ + + {{'submission.workflow.generic.edit' | translate}} + + + + {{'submission.workflow.tasks.generic.processing' | translate}} + {{'submission.workflow.generic.delete' | translate}} + + + + + {{'submission.general.discard.confirm.title' | translate}} + + × + + + + {{'submission.general.discard.confirm.info' | translate}} + + + diff --git a/src/app/shared/mydspace-actions/workspaceitem/workspaceitem-actions.component.scss b/src/app/shared/mydspace-actions/workspaceitem/workspaceitem-actions.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/mydspace-actions/workspaceitem/workspaceitem-actions.component.spec.ts b/src/app/shared/mydspace-actions/workspaceitem/workspaceitem-actions.component.spec.ts new file mode 100644 index 0000000000..ec8bc4a11c --- /dev/null +++ b/src/app/shared/mydspace-actions/workspaceitem/workspaceitem-actions.component.spec.ts @@ -0,0 +1,163 @@ +import { ChangeDetectionStrategy, Injector, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, fakeAsync, TestBed } from '@angular/core/testing'; +import { Router } from '@angular/router'; +import { By } from '@angular/platform-browser'; + +import { of as observableOf } from 'rxjs'; +import { NgbModal, NgbModule } from '@ng-bootstrap/ng-bootstrap'; +import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; + +import { MockTranslateLoader } from '../../mocks/mock-translate-loader'; +import { NotificationsService } from '../../notifications/notifications.service'; +import { NotificationsServiceStub } from '../../testing/notifications-service-stub'; +import { RouterStub } from '../../testing/router-stub'; +import { RemoteData } from '../../../core/data/remote-data'; +import { Item } from '../../../core/shared/item.model'; +import { Workspaceitem } from '../../../core/submission/models/workspaceitem.model'; +import { WorkspaceitemActionsComponent } from './workspaceitem-actions.component'; +import { WorkspaceitemDataService } from '../../../core/submission/workspaceitem-data.service'; + +let component: WorkspaceitemActionsComponent; +let fixture: ComponentFixture; + +let mockObject: Workspaceitem; +let notificationsServiceStub: NotificationsServiceStub; + +const mockDataService = jasmine.createSpyObj('WorkspaceitemDataService', { + delete: jasmine.createSpy('delete') +}); + +const item = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ], + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); +const rd = new RemoteData(false, false, true, null, item); +mockObject = Object.assign(new Workspaceitem(), { item: observableOf(rd), id: '1234', uuid: '1234' }); + +describe('WorkspaceitemActionsComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + NgbModule.forRoot(), + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }) + ], + declarations: [WorkspaceitemActionsComponent], + providers: [ + { provide: Injector, useValue: {} }, + { provide: NotificationsService, useValue: new NotificationsServiceStub() }, + { provide: Router, useValue: new RouterStub() }, + { provide: WorkspaceitemDataService, useValue: mockDataService }, + NgbModal + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(WorkspaceitemActionsComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(WorkspaceitemActionsComponent); + component = fixture.componentInstance; + component.object = mockObject; + notificationsServiceStub = TestBed.get(NotificationsService); + fixture.detectChanges(); + }); + + afterEach(() => { + fixture = null; + component = null; + }); + + it('should init object properly', () => { + component.object = null; + component.initObjects(mockObject); + + expect(component.object).toEqual(mockObject); + }); + + it('should display edit button', () => { + const btn = fixture.debugElement.query(By.css('.btn-primary')); + + expect(btn).toBeDefined(); + }); + + it('should display delete button', () => { + const btn = fixture.debugElement.query(By.css('.btn-danger')); + + expect(btn).toBeDefined(); + }); + + it('should call confirmDiscard on discard confirmation', fakeAsync(() => { + mockDataService.delete.and.returnValue(observableOf(true)); + spyOn(component, 'reload'); + const btn = fixture.debugElement.query(By.css('.btn-danger')); + btn.nativeElement.click(); + fixture.detectChanges(); + + const confirmBtn: any = ((document as any).querySelector('.modal-footer .btn-danger')); + confirmBtn.click(); + + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(mockDataService.delete).toHaveBeenCalledWith(mockObject); + }); + + })); + + it('should display a success notification on delete success', async(() => { + spyOn((component as any).modalService, 'open').and.returnValue({result: Promise.resolve('ok')}); + mockDataService.delete.and.returnValue(observableOf(true)); + spyOn(component, 'reload'); + + component.confirmDiscard('ok'); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(notificationsServiceStub.success).toHaveBeenCalled(); + }); + })); + + it('should display an error notification on delete failure', async(() => { + spyOn((component as any).modalService, 'open').and.returnValue({result: Promise.resolve('ok')}); + mockDataService.delete.and.returnValue(observableOf(false)); + spyOn(component, 'reload'); + + component.confirmDiscard('ok'); + fixture.detectChanges(); + + fixture.whenStable().then(() => { + expect(notificationsServiceStub.error).toHaveBeenCalled(); + }); + })); +}); diff --git a/src/app/shared/mydspace-actions/workspaceitem/workspaceitem-actions.component.ts b/src/app/shared/mydspace-actions/workspaceitem/workspaceitem-actions.component.ts new file mode 100644 index 0000000000..cea4c3746e --- /dev/null +++ b/src/app/shared/mydspace-actions/workspaceitem/workspaceitem-actions.component.ts @@ -0,0 +1,79 @@ +import { Component, Injector, Input } from '@angular/core'; +import { Router } from '@angular/router'; + +import { BehaviorSubject } from 'rxjs'; +import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; +import { TranslateService } from '@ngx-translate/core'; + +import { Workspaceitem } from '../../../core/submission/models/workspaceitem.model'; +import { MyDSpaceActionsComponent } from '../mydspace-actions'; +import { WorkspaceitemDataService } from '../../../core/submission/workspaceitem-data.service'; +import { ResourceType } from '../../../core/shared/resource-type'; +import { NotificationsService } from '../../notifications/notifications.service'; + +/** + * This component represents mydspace actions related to Workspaceitem object. + */ +@Component({ + selector: 'ds-workspaceitem-actions', + styleUrls: ['./workspaceitem-actions.component.scss'], + templateUrl: './workspaceitem-actions.component.html', +}) +export class WorkspaceitemActionsComponent extends MyDSpaceActionsComponent { + + /** + * The workspaceitem object + */ + @Input() object: Workspaceitem; + + /** + * A boolean representing if a delete operation is pending + * @type {BehaviorSubject} + */ + public processingDelete$ = new BehaviorSubject(false); + + /** + * Initialize instance variables + * + * @param {Injector} injector + * @param {Router} router + * @param {NgbModal} modalService + * @param {NotificationsService} notificationsService + * @param {TranslateService} translate + */ + constructor(protected injector: Injector, + protected router: Router, + protected modalService: NgbModal, + protected notificationsService: NotificationsService, + protected translate: TranslateService) { + super(ResourceType.Workspaceitem, injector, router, notificationsService, translate); + } + + /** + * Delete the target workspaceitem object + */ + public confirmDiscard(content) { + this.modalService.open(content).result.then( + (result) => { + if (result === 'ok') { + this.processingDelete$.next(true); + this.objectDataService.delete(this.object) + .subscribe((response: boolean) => { + this.processingDelete$.next(false); + this.handleActionResponse(response); + }) + } + } + ); + } + + /** + * Init the target object + * + * @param {Workspaceitem} object + */ + initObjects(object: Workspaceitem) { + this.object = object; + } + +} diff --git a/src/app/shared/object-collection/object-collection.component.html b/src/app/shared/object-collection/object-collection.component.html index a81ee5a882..5ba889892a 100644 --- a/src/app/shared/object-collection/object-collection.component.html +++ b/src/app/shared/object-collection/object-collection.component.html @@ -1,6 +1,7 @@ + + + diff --git a/src/app/shared/object-collection/object-collection.component.ts b/src/app/shared/object-collection/object-collection.component.ts index 5d382c4a0a..ccc1de1f2f 100644 --- a/src/app/shared/object-collection/object-collection.component.ts +++ b/src/app/shared/object-collection/object-collection.component.ts @@ -1,20 +1,22 @@ - -import {map} from 'rxjs/operators'; -import { Component, EventEmitter, +import { + ChangeDetectorRef, + Component, + EventEmitter, Input, + OnChanges, OnInit, - Output, SimpleChanges, OnChanges, ChangeDetectorRef } from '@angular/core'; + Output, + SimpleChanges +} from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Observable } from 'rxjs'; +import { map } from 'rxjs/operators'; import { RemoteData } from '../../core/data/remote-data'; import { PageInfo } from '../../core/shared/page-info.model'; - import { PaginationComponentOptions } from '../pagination/pagination-component-options.model'; - import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model'; - import { ListableObject } from './shared/listable-object.model'; import { SetViewMode } from '../view-mode'; import { hasValue, isNotEmpty } from '../empty.util'; @@ -29,6 +31,7 @@ export class ObjectCollectionComponent implements OnChanges, OnInit { @Input() objects: RemoteData; @Input() config?: PaginationComponentOptions; @Input() sortConfig: SortOptions; + @Input() hasBorder = false; @Input() hideGear = false; pageInfo: Observable; private sub; @@ -80,13 +83,17 @@ export class ObjectCollectionComponent implements OnChanges, OnInit { } /** + * @param cdRef + * ChangeDetectorRef service provided by Angular. * @param route * Route is a singleton service provided by Angular. * @param router * Router is a singleton service provided by Angular. */ - constructor(private cdRef: ChangeDetectorRef, private route: ActivatedRoute, - private router: Router) { + constructor( + private cdRef: ChangeDetectorRef, + private route: ActivatedRoute, + private router: Router) { } getViewMode(): SetViewMode { diff --git a/src/app/shared/object-collection/shared/claimed-task-my-dspace-result.model.ts b/src/app/shared/object-collection/shared/claimed-task-my-dspace-result.model.ts new file mode 100644 index 0000000000..051bfe6d9f --- /dev/null +++ b/src/app/shared/object-collection/shared/claimed-task-my-dspace-result.model.ts @@ -0,0 +1,11 @@ +import { ClaimedTask } from '../../../core/tasks/models/claimed-task-object.model'; +import { SearchResult } from '../../../+search-page/search-result.model'; +import { MyDSpaceConfigurationValueType } from '../../../+my-dspace-page/my-dspace-configuration-value-type'; +import { searchResultFor } from '../../../+search-page/search-service/search-result-element-decorator'; + +/** + * Represents a search result object of a ClaimedTask object + */ +@searchResultFor(ClaimedTask, MyDSpaceConfigurationValueType.Workflow) +export class ClaimedTaskMyDSpaceResult extends SearchResult { +} diff --git a/src/app/shared/object-collection/shared/item-my-dspace-result.model.ts b/src/app/shared/object-collection/shared/item-my-dspace-result.model.ts new file mode 100644 index 0000000000..92724a762f --- /dev/null +++ b/src/app/shared/object-collection/shared/item-my-dspace-result.model.ts @@ -0,0 +1,11 @@ +import { Item } from '../../../core/shared/item.model'; +import { SearchResult } from '../../../+search-page/search-result.model'; +import { searchResultFor } from '../../../+search-page/search-service/search-result-element-decorator'; +import { MyDSpaceConfigurationValueType } from '../../../+my-dspace-page/my-dspace-configuration-value-type'; + +/** + * Represents a search result object of a Item object + */ +@searchResultFor(Item, MyDSpaceConfigurationValueType.Workspace) +export class ItemMyDSpaceResult extends SearchResult { +} diff --git a/src/app/shared/object-collection/shared/mydspace-item-status/my-dspace-item-status-type.ts b/src/app/shared/object-collection/shared/mydspace-item-status/my-dspace-item-status-type.ts new file mode 100644 index 0000000000..48a0a6f4a3 --- /dev/null +++ b/src/app/shared/object-collection/shared/mydspace-item-status/my-dspace-item-status-type.ts @@ -0,0 +1,7 @@ +export enum MyDspaceItemStatusType { + WORKFLOW = 'mydspace.status.workflow', + VALIDATION = 'mydspace.status.validation', + WAITING_CONTROLLER = 'mydspace.status.waiting-for-controller', + WORKSPACE = 'mydspace.status.workspace', + ARCHIVED = 'mydspace.status.archived' +} diff --git a/src/app/shared/object-collection/shared/mydspace-item-status/my-dspace-item-status.component.html b/src/app/shared/object-collection/shared/mydspace-item-status/my-dspace-item-status.component.html new file mode 100644 index 0000000000..848dd502a4 --- /dev/null +++ b/src/app/shared/object-collection/shared/mydspace-item-status/my-dspace-item-status.component.html @@ -0,0 +1,5 @@ + + + {{badgeContent | translate}} + + diff --git a/src/app/shared/object-collection/shared/mydspace-item-status/my-dspace-item-status.component.scss b/src/app/shared/object-collection/shared/mydspace-item-status/my-dspace-item-status.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/object-collection/shared/mydspace-item-status/my-dspace-item-status.component.spec.ts b/src/app/shared/object-collection/shared/mydspace-item-status/my-dspace-item-status.component.spec.ts new file mode 100644 index 0000000000..9c23ab3603 --- /dev/null +++ b/src/app/shared/object-collection/shared/mydspace-item-status/my-dspace-item-status.component.spec.ts @@ -0,0 +1,89 @@ +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; + +import { of as observableOf } from 'rxjs'; +import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; + +import { RemoteData } from '../../../../core/data/remote-data'; + +import { Workflowitem } from '../../../../core/submission/models/workflowitem.model'; +import { PoolTask } from '../../../../core/tasks/models/pool-task-object.model'; +import { EPersonMock } from '../../../testing/eperson-mock'; +import { MyDSpaceItemStatusComponent } from './my-dspace-item-status.component'; +import { MyDspaceItemStatusType } from './my-dspace-item-status-type'; +import { MockTranslateLoader } from '../../../mocks/mock-translate-loader'; +import { By } from '@angular/platform-browser'; + +let component: MyDSpaceItemStatusComponent; +let fixture: ComponentFixture; + +let mockResultObject: PoolTask; + +const rdSumbitter = new RemoteData(false, false, true, null, EPersonMock); +const workflowitem = Object.assign(new Workflowitem(), { submitter: observableOf(rdSumbitter) }); +const rdWorkflowitem = new RemoteData(false, false, true, null, workflowitem); +mockResultObject = Object.assign(new PoolTask(), { workflowitem: observableOf(rdWorkflowitem) }); + +describe('MyDSpaceItemStatusComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }) + ], + declarations: [MyDSpaceItemStatusComponent], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(MyDSpaceItemStatusComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(MyDSpaceItemStatusComponent); + component = fixture.componentInstance; + }); + + it('should display badge', () => { + const badge = fixture.debugElement.query(By.css('span')); + expect(badge).toBeDefined(); + }); + + it('should init badge content and class', () => { + component.status = MyDspaceItemStatusType.VALIDATION; + fixture.detectChanges(); + expect(component.badgeContent).toBe(MyDspaceItemStatusType.VALIDATION); + expect(component.badgeClass).toBe('text-light badge badge-warning'); + }); + + it('should init badge content and class', () => { + component.status = MyDspaceItemStatusType.WAITING_CONTROLLER; + fixture.detectChanges(); + expect(component.badgeContent).toBe(MyDspaceItemStatusType.WAITING_CONTROLLER); + expect(component.badgeClass).toBe('text-light badge badge-info'); + }); + + it('should init badge content and class', () => { + component.status = MyDspaceItemStatusType.WORKSPACE; + fixture.detectChanges(); + expect(component.badgeContent).toBe(MyDspaceItemStatusType.WORKSPACE); + expect(component.badgeClass).toBe('text-light badge badge-primary'); + }); + + it('should init badge content and class', () => { + component.status = MyDspaceItemStatusType.ARCHIVED; + fixture.detectChanges(); + expect(component.badgeContent).toBe(MyDspaceItemStatusType.ARCHIVED); + expect(component.badgeClass).toBe('text-light badge badge-success'); + }); + + it('should init badge content and class', () => { + component.status = MyDspaceItemStatusType.WORKFLOW; + fixture.detectChanges(); + expect(component.badgeContent).toBe(MyDspaceItemStatusType.WORKFLOW); + expect(component.badgeClass).toBe('text-light badge badge-info'); + }); +}); diff --git a/src/app/shared/object-collection/shared/mydspace-item-status/my-dspace-item-status.component.ts b/src/app/shared/object-collection/shared/mydspace-item-status/my-dspace-item-status.component.ts new file mode 100644 index 0000000000..917dd45acc --- /dev/null +++ b/src/app/shared/object-collection/shared/mydspace-item-status/my-dspace-item-status.component.ts @@ -0,0 +1,54 @@ +import { Component, Input, OnInit } from '@angular/core'; +import { MyDspaceItemStatusType } from './my-dspace-item-status-type'; + +/** + * This component represents a badge with mydspace item status + */ +@Component({ + selector: 'ds-mydspace-item-status', + styleUrls: ['./my-dspace-item-status.component.scss'], + templateUrl: './my-dspace-item-status.component.html' +}) +export class MyDSpaceItemStatusComponent implements OnInit { + + /** + * This mydspace item status + */ + @Input() status: MyDspaceItemStatusType; + + /** + * This badge class + */ + public badgeClass: string; + + /** + * This badge content + */ + public badgeContent: string; + + /** + * Initialize badge content and class + */ + ngOnInit() { + this.badgeContent = this.status; + this.badgeClass = 'text-light badge '; + switch (this.status) { + case MyDspaceItemStatusType.VALIDATION: + this.badgeClass += 'badge-warning'; + break; + case MyDspaceItemStatusType.WAITING_CONTROLLER: + this.badgeClass += 'badge-info'; + break; + case MyDspaceItemStatusType.WORKSPACE: + this.badgeClass += 'badge-primary'; + break; + case MyDspaceItemStatusType.ARCHIVED: + this.badgeClass += 'badge-success'; + break; + case MyDspaceItemStatusType.WORKFLOW: + this.badgeClass += 'badge-info'; + break; + } + } + +} diff --git a/src/app/shared/object-collection/shared/mydspace-item-submitter/item-submitter.component.html b/src/app/shared/object-collection/shared/mydspace-item-submitter/item-submitter.component.html new file mode 100644 index 0000000000..47674025ca --- /dev/null +++ b/src/app/shared/object-collection/shared/mydspace-item-submitter/item-submitter.component.html @@ -0,0 +1,3 @@ + + {{'submission.workflow.tasks.generic.submitter' | translate}} : {{(submitter$ | async)?.name}} + diff --git a/src/app/shared/object-collection/shared/mydspace-item-submitter/item-submitter.component.scss b/src/app/shared/object-collection/shared/mydspace-item-submitter/item-submitter.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/object-collection/shared/mydspace-item-submitter/item-submitter.component.spec.ts b/src/app/shared/object-collection/shared/mydspace-item-submitter/item-submitter.component.spec.ts new file mode 100644 index 0000000000..77460a3674 --- /dev/null +++ b/src/app/shared/object-collection/shared/mydspace-item-submitter/item-submitter.component.spec.ts @@ -0,0 +1,68 @@ +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; + +import { of as observableOf } from 'rxjs'; +import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; +import { cold } from 'jasmine-marbles'; + +import { RemoteData } from '../../../../core/data/remote-data'; +import { ItemSubmitterComponent } from './item-submitter.component'; +import { Workflowitem } from '../../../../core/submission/models/workflowitem.model'; +import { PoolTask } from '../../../../core/tasks/models/pool-task-object.model'; +import { EPersonMock } from '../../../testing/eperson-mock'; +import { MockTranslateLoader } from '../../../mocks/mock-translate-loader'; +import { By } from '@angular/platform-browser'; + +let component: ItemSubmitterComponent; +let fixture: ComponentFixture; + +const compIndex = 1; + +let mockResultObject: PoolTask; + +const rdSumbitter = new RemoteData(false, false, true, null, EPersonMock); +const workflowitem = Object.assign(new Workflowitem(), { submitter: observableOf(rdSumbitter) }); +const rdWorkflowitem = new RemoteData(false, false, true, null, workflowitem); +mockResultObject = Object.assign(new PoolTask(), { workflowitem: observableOf(rdWorkflowitem) }); + +describe('ItemSubmitterComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }) + ], + declarations: [ItemSubmitterComponent], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(ItemSubmitterComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(async(() => { + fixture = TestBed.createComponent(ItemSubmitterComponent); + component = fixture.componentInstance; + })); + + beforeEach(() => { + component.object = mockResultObject; + fixture.detectChanges(); + }); + + it('should init submitter properly', () => { + expect(component.submitter$).toBeObservable(cold('(b|)', { + b: EPersonMock + })); + }); + + it('should show a badge with submitter name', () => { + const badge = fixture.debugElement.query(By.css('.badge')); + + expect(badge).toBeDefined(); + expect(badge.nativeElement.innerHTML).toBe(EPersonMock.name); + }); +}); diff --git a/src/app/shared/object-collection/shared/mydspace-item-submitter/item-submitter.component.ts b/src/app/shared/object-collection/shared/mydspace-item-submitter/item-submitter.component.ts new file mode 100644 index 0000000000..f752fa6f04 --- /dev/null +++ b/src/app/shared/object-collection/shared/mydspace-item-submitter/item-submitter.component.ts @@ -0,0 +1,41 @@ +import { Component, Input, OnInit } from '@angular/core'; + +import { Observable } from 'rxjs'; +import { filter, find, flatMap, map } from 'rxjs/operators'; + +import { EPerson } from '../../../../core/eperson/models/eperson.model'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { isNotEmpty, isNotUndefined } from '../../../empty.util'; +import { Workflowitem } from '../../../../core/submission/models/workflowitem.model'; + +/** + * This component represents a badge with submitter information. + */ +@Component({ + selector: 'ds-item-submitter', + styleUrls: ['./item-submitter.component.scss'], + templateUrl: './item-submitter.component.html' +}) +export class ItemSubmitterComponent implements OnInit { + + /** + * The target object + */ + @Input() object: any; + + /** + * The Eperson object + */ + submitter$: Observable; + + /** + * Initialize submitter object + */ + ngOnInit() { + this.submitter$ = (this.object.workflowitem as Observable>).pipe( + filter((rd: RemoteData) => (rd.hasSucceeded && isNotUndefined(rd.payload))), + flatMap((rd: RemoteData) => rd.payload.submitter as Observable>), + find((rd: RemoteData) => rd.hasSucceeded && isNotEmpty(rd.payload)), + map((rd: RemoteData) => rd.payload)); + } +} diff --git a/src/app/shared/object-collection/shared/pool-task-my-dspace-result.model.ts b/src/app/shared/object-collection/shared/pool-task-my-dspace-result.model.ts new file mode 100644 index 0000000000..1bc2c4c4c2 --- /dev/null +++ b/src/app/shared/object-collection/shared/pool-task-my-dspace-result.model.ts @@ -0,0 +1,11 @@ +import { PoolTask } from '../../../core/tasks/models/pool-task-object.model'; +import { SearchResult } from '../../../+search-page/search-result.model'; +import { MyDSpaceConfigurationValueType } from '../../../+my-dspace-page/my-dspace-configuration-value-type'; +import { searchResultFor } from '../../../+search-page/search-service/search-result-element-decorator'; + +/** + * Represents a search result object of a PoolTask object + */ +@searchResultFor(PoolTask, MyDSpaceConfigurationValueType.Workflow) +export class PoolTaskMyDSpaceResult extends SearchResult { +} diff --git a/src/app/shared/object-collection/shared/workflowitem-my-dspace-result.model.ts b/src/app/shared/object-collection/shared/workflowitem-my-dspace-result.model.ts new file mode 100644 index 0000000000..89f6f351ad --- /dev/null +++ b/src/app/shared/object-collection/shared/workflowitem-my-dspace-result.model.ts @@ -0,0 +1,11 @@ +import { Workflowitem } from '../../../core/submission/models/workflowitem.model'; +import { SearchResult } from '../../../+search-page/search-result.model'; +import { MyDSpaceConfigurationValueType } from '../../../+my-dspace-page/my-dspace-configuration-value-type'; +import { searchResultFor } from '../../../+search-page/search-service/search-result-element-decorator'; + +/** + * Represents a search result object of a Workflowitem object + */ +@searchResultFor(Workflowitem, MyDSpaceConfigurationValueType.Workspace) +export class WorkflowitemMyDSpaceResult extends SearchResult { +} diff --git a/src/app/shared/object-collection/shared/workspaceitem-my-dspace-result.model.ts b/src/app/shared/object-collection/shared/workspaceitem-my-dspace-result.model.ts new file mode 100644 index 0000000000..20474c9ad3 --- /dev/null +++ b/src/app/shared/object-collection/shared/workspaceitem-my-dspace-result.model.ts @@ -0,0 +1,11 @@ +import { Workspaceitem } from '../../../core/submission/models/workspaceitem.model'; +import { MyDSpaceConfigurationValueType } from '../../../+my-dspace-page/my-dspace-configuration-value-type'; +import { searchResultFor } from '../../../+search-page/search-service/search-result-element-decorator'; +import { SearchResult } from '../../../+search-page/search-result.model'; + +/** + * Represents a search result object of a Workspaceitem object + */ +@searchResultFor(Workspaceitem, MyDSpaceConfigurationValueType.Workspace) +export class WorkspaceitemMyDSpaceResult extends SearchResult { +} diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/claimed-my-dspace-result/claimed-my-dspace-result-detail-element.component.html b/src/app/shared/object-detail/my-dspace-result-detail-element/claimed-my-dspace-result/claimed-my-dspace-result-detail-element.component.html new file mode 100644 index 0000000000..d4ecaaa332 --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/claimed-my-dspace-result/claimed-my-dspace-result-detail-element.component.html @@ -0,0 +1,8 @@ + + + + diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/claimed-my-dspace-result/claimed-my-dspace-result-detail-element.component.spec.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/claimed-my-dspace-result/claimed-my-dspace-result-detail-element.component.spec.ts new file mode 100644 index 0000000000..d3307721ff --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/claimed-my-dspace-result/claimed-my-dspace-result-detail-element.component.spec.ts @@ -0,0 +1,89 @@ +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; + +import { of as observableOf } from 'rxjs'; + +import { Item } from '../../../../core/shared/item.model'; +import { ClaimedMyDSpaceResultDetailElementComponent } from './claimed-my-dspace-result-detail-element.component'; +import { ClaimedTaskMyDSpaceResult } from '../../../object-collection/shared/claimed-task-my-dspace-result.model'; +import { ClaimedTask } from '../../../../core/tasks/models/claimed-task-object.model'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { Workflowitem } from '../../../../core/submission/models/workflowitem.model'; + +let component: ClaimedMyDSpaceResultDetailElementComponent; +let fixture: ComponentFixture; + +const compIndex = 1; + +const mockResultObject: ClaimedTaskMyDSpaceResult = new ClaimedTaskMyDSpaceResult(); +mockResultObject.hitHighlights = {}; + +const item = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ], + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); +const rdItem = new RemoteData(false, false, true, null, item); +const workflowitem = Object.assign(new Workflowitem(), { item: observableOf(rdItem) }); +const rdWorkflowitem = new RemoteData(false, false, true, null, workflowitem); +mockResultObject.indexableObject = Object.assign(new ClaimedTask(), { workflowitem: observableOf(rdWorkflowitem) }); + +describe('ClaimedMyDSpaceResultDetailElementComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [NoopAnimationsModule], + declarations: [ClaimedMyDSpaceResultDetailElementComponent], + providers: [ + { provide: 'objectElementProvider', useValue: (mockResultObject) }, + { provide: 'indexElementProvider', useValue: (compIndex) } + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(ClaimedMyDSpaceResultDetailElementComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(async(() => { + fixture = TestBed.createComponent(ClaimedMyDSpaceResultDetailElementComponent); + component = fixture.componentInstance; + })); + + beforeEach(() => { + component.dso = mockResultObject.indexableObject; + fixture.detectChanges(); + }); + + it('should init item properly', () => { + expect(component.workflowitem).toEqual(workflowitem); + }); + + it('should have properly status', () => { + expect(component.status).toEqual(MyDspaceItemStatusType.VALIDATION); + }); +}); diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/claimed-my-dspace-result/claimed-my-dspace-result-detail-element.component.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/claimed-my-dspace-result/claimed-my-dspace-result-detail-element.component.ts new file mode 100644 index 0000000000..5f7b0aab55 --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/claimed-my-dspace-result/claimed-my-dspace-result-detail-element.component.ts @@ -0,0 +1,68 @@ +import { Component, Inject } from '@angular/core'; + +import { Observable } from 'rxjs'; +import { find } from 'rxjs/operators'; + +import { renderElementsFor } from '../../../object-collection/shared/dso-element-decorator'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { ViewMode } from '../../../../core/shared/view-mode.model'; +import { isNotUndefined } from '../../../empty.util'; +import { ListableObject } from '../../../object-collection/shared/listable-object.model'; +import { Workflowitem } from '../../../../core/submission/models/workflowitem.model'; +import { ClaimedTask } from '../../../../core/tasks/models/claimed-task-object.model'; +import { ClaimedTaskMyDSpaceResult } from '../../../object-collection/shared/claimed-task-my-dspace-result.model'; +import { MyDSpaceResultDetailElementComponent } from '../my-dspace-result-detail-element.component'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { SetViewMode } from '../../../view-mode'; + +/** + * This component renders claimed task object for the mydspace result in the detail view. + */ +@Component({ + selector: 'ds-claimed-my-dspace-result-detail-element', + styleUrls: ['../my-dspace-result-detail-element.component.scss'], + templateUrl: './claimed-my-dspace-result-detail-element.component.html' +}) + +@renderElementsFor(ClaimedTaskMyDSpaceResult, SetViewMode.Detail) +@renderElementsFor(ClaimedTask, SetViewMode.Detail) +export class ClaimedMyDSpaceResultDetailElementComponent extends MyDSpaceResultDetailElementComponent { + + /** + * A boolean representing if to show submitter information + */ + public showSubmitter = true; + + /** + * Represent item's status + */ + public status = MyDspaceItemStatusType.VALIDATION; + + /** + * The workflowitem object that belonging to the result object + */ + public workflowitem: Workflowitem; + + constructor(@Inject('objectElementProvider') public listable: ListableObject) { + super(listable); + } + + /** + * Initialize all instance variables + */ + ngOnInit() { + this.initWorkflowItem(this.dso.workflowitem as Observable>); + } + + /** + * Retrieve workflowitem from result object + */ + initWorkflowItem(wfi$: Observable>) { + wfi$.pipe( + find((rd: RemoteData) => (rd.hasSucceeded && isNotUndefined(rd.payload))) + ).subscribe((rd: RemoteData) => { + this.workflowitem = rd.payload; + }); + } + +} diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component.html b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component.html new file mode 100644 index 0000000000..2b7e7f8f6e --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component.html @@ -0,0 +1,10 @@ + + + + {{mdValue}} + + + + {{(placeholder | translate)}} + + diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component.spec.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component.spec.ts new file mode 100644 index 0000000000..ff5224a1a2 --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component.spec.ts @@ -0,0 +1,98 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; + +import { of as observableOf } from 'rxjs'; +import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; + +import { ItemDetailPreviewFieldComponent } from './item-detail-preview-field.component'; +import { Item } from '../../../../../core/shared/item.model'; +import { TruncatePipe } from '../../../../utils/truncate.pipe'; +import { MockTranslateLoader } from '../../../../mocks/mock-translate-loader'; +import { By } from '@angular/platform-browser'; + +let component: ItemDetailPreviewFieldComponent; +let fixture: ComponentFixture; + +const mockItemWithAuthorAndDate: Item = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ], + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ] + } +}); + +describe('ItemDetailPreviewFieldComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + NoopAnimationsModule, + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }), + ], + declarations: [ItemDetailPreviewFieldComponent, TruncatePipe], + providers: [ + { provide: 'objectElementProvider', useValue: { mockItemWithAuthorAndDate } } + + ], + + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(ItemDetailPreviewFieldComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(async(() => { + fixture = TestBed.createComponent(ItemDetailPreviewFieldComponent); + component = fixture.componentInstance; + + })); + + beforeEach(() => { + component.object = { hitHighlights: {} } as any; + component.item = mockItemWithAuthorAndDate; + component.label = 'test label'; + component.metadata = 'dc.title'; + component.placeholder = 'No title'; + fixture.detectChanges(); + }); + + it('should display dc.title value', () => { + const span = fixture.debugElement.query(By.css('span')); + expect(span.nativeElement.innerHTML).toContain('This is just another title'); + }); + + it('should display placeholder when metadata has no value', () => { + component.metadata = 'dc.abstract'; + component.placeholder = 'No abstract'; + fixture.detectChanges(); + const span = fixture.debugElement.query(By.css('.text-muted')); + expect(span.nativeElement.innerHTML).toContain('No abstract'); + }); +}); diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component.ts new file mode 100644 index 0000000000..b53d0a6b2d --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component.ts @@ -0,0 +1,55 @@ +import { Component, Input } from '@angular/core'; + +import { Metadata } from '../../../../../core/shared/metadata.utils'; +import { MyDSpaceResult } from '../../../../../+my-dspace-page/my-dspace-result.model'; +import { Item } from '../../../../../core/shared/item.model'; + +/** + * This component show values for the given item metadata + */ +@Component({ + selector: 'ds-item-detail-preview-field', + templateUrl: './item-detail-preview-field.component.html' +}) +export class ItemDetailPreviewFieldComponent { + + /** + * The item to display + */ + @Input() item: Item; + + /** + * The mydspace result object + */ + @Input() object: MyDSpaceResult; + + /** + * The metadata label + */ + @Input() label: string; + + /** + * The metadata to show + */ + @Input() metadata: string | string[]; + + /** + * The placeholder if there are no value to show + */ + @Input() placeholder: string; + + /** + * The value's separator + */ + @Input() separator: string; + + /** + * Gets all matching metadata string values from hitHighlights or dso metadata, preferring hitHighlights. + * + * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. + * @returns {string[]} the matching string values or an empty array. + */ + allMetadataValues(keyOrKeys: string | string[]): string[] { + return Metadata.allValues([this.object.hitHighlights, this.item.metadata], keyOrKeys); + } +} diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.html b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.html new file mode 100644 index 0000000000..04e128c49a --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.html @@ -0,0 +1,62 @@ + + + + + + + + {{('mydspace.results.no-title' | translate)}} + + + + + + + + + 0" class="file-section"> + + {{file?.name}} + ({{(file?.sizeBytes) | dsFileSize }}) + + + + + {{('mydspace.results.no-files' | translate)}} + + + + + + + + + + + + + + + + + diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.scss b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.spec.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.spec.ts new file mode 100644 index 0000000000..d0af614a6c --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.spec.ts @@ -0,0 +1,83 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; + +import { of as observableOf } from 'rxjs'; +import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; + +import { TruncatePipe } from '../../../utils/truncate.pipe'; +import { Item } from '../../../../core/shared/item.model'; +import { ItemDetailPreviewComponent } from './item-detail-preview.component'; +import { MockTranslateLoader } from '../../../mocks/mock-translate-loader'; +import { ItemDetailPreviewFieldComponent } from './item-detail-preview-field/item-detail-preview-field.component'; +import { FileSizePipe } from '../../../utils/file-size-pipe'; +import { VarDirective } from '../../../utils/var.directive'; + +let component: ItemDetailPreviewComponent; +let fixture: ComponentFixture; + +const mockItem: Item = Object.assign(new Item(), { + bitstreams: observableOf([]), + metadata: { + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ], + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ] + } +}); + +describe('ItemDetailPreviewComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + NoopAnimationsModule, + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }), + ], + declarations: [ItemDetailPreviewComponent, ItemDetailPreviewFieldComponent, TruncatePipe, FileSizePipe, VarDirective], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(ItemDetailPreviewComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(async(() => { + fixture = TestBed.createComponent(ItemDetailPreviewComponent); + component = fixture.componentInstance; + component.object = { hitHighlights: {} } as any; + component.item = mockItem; + component.separator = ', '; + spyOn(component.item, 'getFiles').and.returnValue(mockItem.bitstreams); + fixture.detectChanges(); + + })); + + it('should init thumbnail and bitstreams on init', () => { + expect(component.thumbnail$).toBeDefined(); + expect(component.bitstreams$).toBeDefined(); + }); +}); diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.ts new file mode 100644 index 0000000000..d26bfc4589 --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component.ts @@ -0,0 +1,65 @@ +import { Component, Input } from '@angular/core'; + +import { Observable } from 'rxjs'; + +import { Item } from '../../../../core/shared/item.model'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { fadeInOut } from '../../../animations/fade'; +import { Bitstream } from '../../../../core/shared/bitstream.model'; +import { MyDSpaceResult } from '../../../../+my-dspace-page/my-dspace-result.model'; + +/** + * This component show metadata for the given item object in the detail view. + */ +@Component({ + selector: 'ds-item-detail-preview', + styleUrls: ['./item-detail-preview.component.scss'], + templateUrl: './item-detail-preview.component.html', + animations: [fadeInOut] +}) +export class ItemDetailPreviewComponent { + + /** + * The item to display + */ + @Input() item: Item; + + /** + * The mydspace result object + */ + @Input() object: MyDSpaceResult; + + /** + * Represent item's status + */ + @Input() status: MyDspaceItemStatusType; + + /** + * A boolean representing if to show submitter information + */ + @Input() showSubmitter = false; + + /** + * The item's thumbnail + */ + public bitstreams$: Observable; + + /** + * The value's separator + */ + public separator = ', '; + + /** + * The item's thumbnail + */ + public thumbnail$: Observable; + + /** + * Initialize all instance variables + */ + ngOnInit() { + this.thumbnail$ = this.item.getThumbnail(); + this.bitstreams$ = this.item.getFiles(); + } + +} diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/item-my-dspace-result/item-my-dspace-result-detail-element.component.html b/src/app/shared/object-detail/my-dspace-result-detail-element/item-my-dspace-result/item-my-dspace-result-detail-element.component.html new file mode 100644 index 0000000000..2b687960ab --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/item-my-dspace-result/item-my-dspace-result-detail-element.component.html @@ -0,0 +1,8 @@ + + + + + + diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/item-my-dspace-result/item-my-dspace-result-detail-element.component.scss b/src/app/shared/object-detail/my-dspace-result-detail-element/item-my-dspace-result/item-my-dspace-result-detail-element.component.scss new file mode 100644 index 0000000000..1d0786105c --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/item-my-dspace-result/item-my-dspace-result-detail-element.component.scss @@ -0,0 +1 @@ +@import '../../../../../styles/variables'; diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/item-my-dspace-result/item-my-dspace-result-detail-element.component.spec.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/item-my-dspace-result/item-my-dspace-result-detail-element.component.spec.ts new file mode 100644 index 0000000000..c99f44cbae --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/item-my-dspace-result/item-my-dspace-result-detail-element.component.spec.ts @@ -0,0 +1,78 @@ +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; + +import { of as observableOf } from 'rxjs'; + +import { Item } from '../../../../core/shared/item.model'; +import { ItemMyDSpaceResultDetailElementComponent } from './item-my-dspace-result-detail-element.component'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { ItemMyDSpaceResult } from '../../../object-collection/shared/item-my-dspace-result.model'; + +let component: ItemMyDSpaceResultDetailElementComponent; +let fixture: ComponentFixture; + +const compIndex = 1; + +const mockResultObject: ItemMyDSpaceResult = new ItemMyDSpaceResult(); +mockResultObject.hitHighlights = {}; + +mockResultObject.indexableObject = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ], + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); + +describe('ItemMyDSpaceResultDetailElementComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [NoopAnimationsModule], + declarations: [ItemMyDSpaceResultDetailElementComponent], + providers: [ + { provide: 'objectElementProvider', useValue: (mockResultObject) }, + { provide: 'indexElementProvider', useValue: (compIndex) } + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(ItemMyDSpaceResultDetailElementComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(async(() => { + fixture = TestBed.createComponent(ItemMyDSpaceResultDetailElementComponent); + component = fixture.componentInstance; + })); + + beforeEach(() => { + component.dso = mockResultObject.indexableObject; + fixture.detectChanges(); + }); + + it('should have properly status', () => { + expect(component.status).toEqual(MyDspaceItemStatusType.ARCHIVED); + }); +}); diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/item-my-dspace-result/item-my-dspace-result-detail-element.component.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/item-my-dspace-result/item-my-dspace-result-detail-element.component.ts new file mode 100644 index 0000000000..26f63deb83 --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/item-my-dspace-result/item-my-dspace-result-detail-element.component.ts @@ -0,0 +1,28 @@ +import { Component } from '@angular/core'; + +import { renderElementsFor } from '../../../object-collection/shared/dso-element-decorator'; +import { ViewMode } from '../../../../core/shared/view-mode.model'; +import { Item } from '../../../../core/shared/item.model'; +import { ItemMyDSpaceResult } from '../../../object-collection/shared/item-my-dspace-result.model'; +import { MyDSpaceResultDetailElementComponent } from '../my-dspace-result-detail-element.component'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { SetViewMode } from '../../../view-mode'; + +/** + * This component renders item object for the mydspace result in the detail view. + */ +@Component({ + selector: 'ds-workspaceitem-my-dspace-result-detail-element', + styleUrls: ['../my-dspace-result-detail-element.component.scss', './item-my-dspace-result-detail-element.component.scss'], + templateUrl: './item-my-dspace-result-detail-element.component.html' +}) + +@renderElementsFor(ItemMyDSpaceResult, SetViewMode.Detail) +export class ItemMyDSpaceResultDetailElementComponent extends MyDSpaceResultDetailElementComponent { + + /** + * Represent item's status + */ + public status = MyDspaceItemStatusType.ARCHIVED; + +} diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/my-dspace-result-detail-element.component.scss b/src/app/shared/object-detail/my-dspace-result-detail-element/my-dspace-result-detail-element.component.scss new file mode 100644 index 0000000000..9a442f84e1 --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/my-dspace-result-detail-element.component.scss @@ -0,0 +1 @@ +@import '../../object-grid/search-result-grid-element/search-result-grid-element.component'; diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/my-dspace-result-detail-element.component.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/my-dspace-result-detail-element.component.ts new file mode 100644 index 0000000000..47a44d3132 --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/my-dspace-result-detail-element.component.ts @@ -0,0 +1,49 @@ +import { Component, Inject } from '@angular/core'; + +import { MyDSpaceResult } from '../../../+my-dspace-page/my-dspace-result.model'; +import { AbstractListableElementComponent } from '../../object-collection/shared/object-collection-element/abstract-listable-element.component'; +import { ListableObject } from '../../object-collection/shared/listable-object.model'; +import { DSpaceObject } from '../../../core/shared/dspace-object.model'; +import { Metadata } from '../../../core/shared/metadata.utils'; + +@Component({ + selector: 'ds-my-dspace-result-detail-element', + template: `` +}) +export class MyDSpaceResultDetailElementComponent, K extends DSpaceObject> extends AbstractListableElementComponent { + + /** + * The result element object + */ + dso: K; + + /** + * Initialize instance variables + * + * @param {ListableObject} detailable + */ + public constructor(@Inject('objectElementProvider') public detailable: ListableObject) { + super(detailable); + this.dso = this.object.indexableObject; + } + + /** + * Gets all matching metadata string values from hitHighlights or dso metadata, preferring hitHighlights. + * + * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. + * @returns {string[]} the matching string values or an empty array. + */ + allMetadataValues(keyOrKeys: string | string[]): string[] { + return Metadata.allValues([this.object.hitHighlights, this.dso.metadata], keyOrKeys); + } + + /** + * Gets the first matching metadata string value from hitHighlights or dso metadata, preferring hitHighlights. + * + * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. + * @returns {string} the first matching string value, or `undefined`. + */ + firstMetadataValue(keyOrKeys: string | string[]): string { + return Metadata.firstValue([this.object.hitHighlights, this.dso.metadata], keyOrKeys); + } +} diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/pool-my-dspace-result/pool-my-dspace-result-detail-element.component.html b/src/app/shared/object-detail/my-dspace-result-detail-element/pool-my-dspace-result/pool-my-dspace-result-detail-element.component.html new file mode 100644 index 0000000000..96ef68e3f8 --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/pool-my-dspace-result/pool-my-dspace-result-detail-element.component.html @@ -0,0 +1,7 @@ + + + diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/pool-my-dspace-result/pool-my-dspace-result-detail-element.component.spec.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/pool-my-dspace-result/pool-my-dspace-result-detail-element.component.spec.ts new file mode 100644 index 0000000000..0eea01aa1c --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/pool-my-dspace-result/pool-my-dspace-result-detail-element.component.spec.ts @@ -0,0 +1,89 @@ +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; + +import { of as observableOf } from 'rxjs'; + +import { Item } from '../../../../core/shared/item.model'; +import { PoolMyDSpaceResultDetailElementComponent } from './pool-my-dspace-result-detail-lement.component'; +import { PoolTaskMyDSpaceResult } from '../../../object-collection/shared/pool-task-my-dspace-result.model'; +import { PoolTask } from '../../../../core/tasks/models/pool-task-object.model'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { Workflowitem } from '../../../../core/submission/models/workflowitem.model'; + +let component: PoolMyDSpaceResultDetailElementComponent; +let fixture: ComponentFixture; + +const compIndex = 1; + +const mockResultObject: PoolTaskMyDSpaceResult = new PoolTaskMyDSpaceResult(); +mockResultObject.hitHighlights = {}; + +const item = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ], + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); +const rdItem = new RemoteData(false, false, true, null, item); +const workflowitem = Object.assign(new Workflowitem(), { item: observableOf(rdItem) }); +const rdWorkflowitem = new RemoteData(false, false, true, null, workflowitem); +mockResultObject.indexableObject = Object.assign(new PoolTask(), { workflowitem: observableOf(rdWorkflowitem) }); + +describe('PoolMyDSpaceResultDetailElementComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [NoopAnimationsModule], + declarations: [PoolMyDSpaceResultDetailElementComponent], + providers: [ + { provide: 'objectElementProvider', useValue: (mockResultObject) }, + { provide: 'indexElementProvider', useValue: (compIndex) } + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(PoolMyDSpaceResultDetailElementComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(async(() => { + fixture = TestBed.createComponent(PoolMyDSpaceResultDetailElementComponent); + component = fixture.componentInstance; + })); + + beforeEach(() => { + component.dso = mockResultObject.indexableObject; + fixture.detectChanges(); + }); + + it('should init item properly', () => { + expect(component.workflowitem).toEqual(workflowitem); + }); + + it('should have properly status', () => { + expect(component.status).toEqual(MyDspaceItemStatusType.WAITING_CONTROLLER); + }); +}); diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/pool-my-dspace-result/pool-my-dspace-result-detail-lement.component.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/pool-my-dspace-result/pool-my-dspace-result-detail-lement.component.ts new file mode 100644 index 0000000000..ef7bcadebf --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/pool-my-dspace-result/pool-my-dspace-result-detail-lement.component.ts @@ -0,0 +1,68 @@ +import { Component, Inject } from '@angular/core'; + +import { Observable } from 'rxjs'; +import { find } from 'rxjs/operators'; + +import { ViewMode } from '../../../../core/shared/view-mode.model'; +import { renderElementsFor } from '../../../object-collection/shared/dso-element-decorator'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { isNotUndefined } from '../../../empty.util'; +import { ListableObject } from '../../../object-collection/shared/listable-object.model'; +import { Workflowitem } from '../../../../core/submission/models/workflowitem.model'; +import { PoolTask } from '../../../../core/tasks/models/pool-task-object.model'; +import { PoolTaskMyDSpaceResult } from '../../../object-collection/shared/pool-task-my-dspace-result.model'; +import { MyDSpaceResultDetailElementComponent } from '../my-dspace-result-detail-element.component'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { SetViewMode } from '../../../view-mode'; + +/** + * This component renders pool task object for the mydspace result in the detail view. + */ +@Component({ + selector: 'ds-pool-my-dspace-result-detail-element', + styleUrls: ['../my-dspace-result-detail-element.component.scss'], + templateUrl: './pool-my-dspace-result-detail-element.component.html', +}) + +@renderElementsFor(PoolTaskMyDSpaceResult, SetViewMode.Detail) +@renderElementsFor(PoolTask, SetViewMode.Detail) +export class PoolMyDSpaceResultDetailElementComponent extends MyDSpaceResultDetailElementComponent { + + /** + * A boolean representing if to show submitter information + */ + public showSubmitter = true; + + /** + * Represent item's status + */ + public status = MyDspaceItemStatusType.WAITING_CONTROLLER; + + /** + * The workflowitem object that belonging to the result object + */ + public workflowitem: Workflowitem; + + constructor(@Inject('objectElementProvider') public listable: ListableObject) { + super(listable); + } + + /** + * Initialize all instance variables + */ + ngOnInit() { + this.initWorkflowItem(this.dso.workflowitem as Observable>); + } + + /** + * Retrieve workflowitem from result object + */ + initWorkflowItem(wfi$: Observable>) { + wfi$.pipe( + find((rd: RemoteData) => (rd.hasSucceeded && isNotUndefined(rd.payload))) + ).subscribe((rd: RemoteData) => { + this.workflowitem = rd.payload; + }); + } + +} diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-detail-element.component.html b/src/app/shared/object-detail/my-dspace-result-detail-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-detail-element.component.html new file mode 100644 index 0000000000..7ff1a9bf72 --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-detail-element.component.html @@ -0,0 +1,6 @@ + + + + diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-detail-element.component.spec.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-detail-element.component.spec.ts new file mode 100644 index 0000000000..f8bdbf9fd6 --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-detail-element.component.spec.ts @@ -0,0 +1,86 @@ +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; + +import { of as observableOf } from 'rxjs'; + +import { Item } from '../../../../core/shared/item.model'; +import { WorkflowitemMyDSpaceResultDetailElementComponent } from './workflowitem-my-dspace-result-detail-element.component'; +import { WorkflowitemMyDSpaceResult } from '../../../object-collection/shared/workflowitem-my-dspace-result.model'; +import { Workflowitem } from '../../../../core/submission/models/workflowitem.model'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; + +let component: WorkflowitemMyDSpaceResultDetailElementComponent; +let fixture: ComponentFixture; + +const compIndex = 1; + +const mockResultObject: WorkflowitemMyDSpaceResult = new WorkflowitemMyDSpaceResult(); +mockResultObject.hitHighlights = {}; + +const item = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ], + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); +const rd = new RemoteData(false, false, true, null, item); +mockResultObject.indexableObject = Object.assign(new Workflowitem(), { item: observableOf(rd) }); + +describe('WorkflowitemMyDSpaceResultDetailElementComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [NoopAnimationsModule], + declarations: [WorkflowitemMyDSpaceResultDetailElementComponent], + providers: [ + { provide: 'objectElementProvider', useValue: (mockResultObject) }, + { provide: 'indexElementProvider', useValue: (compIndex) } + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(WorkflowitemMyDSpaceResultDetailElementComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(async(() => { + fixture = TestBed.createComponent(WorkflowitemMyDSpaceResultDetailElementComponent); + component = fixture.componentInstance; + })); + + beforeEach(() => { + component.dso = mockResultObject.indexableObject; + fixture.detectChanges(); + }); + + it('should init item properly', () => { + expect(component.item).toEqual(item); + }); + + it('should have properly status', () => { + expect(component.status).toEqual(MyDspaceItemStatusType.WORKFLOW); + }); +}); diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-detail-element.component.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-detail-element.component.ts new file mode 100644 index 0000000000..1c4b0c668f --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-detail-element.component.ts @@ -0,0 +1,62 @@ +import { Component, Inject } from '@angular/core'; + +import { renderElementsFor } from '../../../object-collection/shared/dso-element-decorator'; +import { ViewMode } from '../../../../core/shared/view-mode.model'; +import { Item } from '../../../../core/shared/item.model'; +import { ListableObject } from '../../../object-collection/shared/listable-object.model'; +import { WorkflowitemMyDSpaceResult } from '../../../object-collection/shared/workflowitem-my-dspace-result.model'; +import { Workflowitem } from '../../../../core/submission/models/workflowitem.model'; +import { MyDSpaceResultDetailElementComponent } from '../my-dspace-result-detail-element.component'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { Observable } from 'rxjs/internal/Observable'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { find } from 'rxjs/operators'; +import { isNotUndefined } from '../../../empty.util'; +import { SetViewMode } from '../../../view-mode'; + +/** + * This component renders workflowitem object for the mydspace result in the detail view. + */ +@Component({ + selector: 'ds-workflowitem-my-dspace-result-detail-element', + styleUrls: ['../my-dspace-result-detail-element.component.scss'], + templateUrl: './workflowitem-my-dspace-result-detail-element.component.html', +}) + +@renderElementsFor(WorkflowitemMyDSpaceResult, SetViewMode.Detail) +@renderElementsFor(Workflowitem, SetViewMode.Detail) +export class WorkflowitemMyDSpaceResultDetailElementComponent extends MyDSpaceResultDetailElementComponent { + + /** + * The item object that belonging to the result object + */ + public item: Item; + + /** + * Represent item's status + */ + public status = MyDspaceItemStatusType.WORKFLOW; + + constructor(@Inject('objectElementProvider') public listable: ListableObject) { + super(listable); + } + + /** + * Initialize all instance variables + */ + ngOnInit() { + this.initItem(this.dso.item as Observable>); + } + + /** + * Retrieve item from result object + */ + initItem(item$: Observable>) { + item$.pipe( + find((rd: RemoteData) => rd.hasSucceeded && isNotUndefined(rd.payload)) + ).subscribe((rd: RemoteData) => { + this.item = rd.payload; + }); + } + +} diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-detail-element.component.html b/src/app/shared/object-detail/my-dspace-result-detail-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-detail-element.component.html new file mode 100644 index 0000000000..8d4eee6ba9 --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-detail-element.component.html @@ -0,0 +1,5 @@ + + + diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-detail-element.component.scss b/src/app/shared/object-detail/my-dspace-result-detail-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-detail-element.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-detail-element.component.spec.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-detail-element.component.spec.ts new file mode 100644 index 0000000000..af67bf53ea --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-detail-element.component.spec.ts @@ -0,0 +1,86 @@ +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; + +import { of as observableOf } from 'rxjs'; + +import { Item } from '../../../../core/shared/item.model'; +import { WorkspaceitemMyDSpaceResultDetailElementComponent } from './workspaceitem-my-dspace-result-detail-element.component'; +import { WorkspaceitemMyDSpaceResult } from '../../../object-collection/shared/workspaceitem-my-dspace-result.model'; +import { Workspaceitem } from '../../../../core/submission/models/workspaceitem.model'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; + +let component: WorkspaceitemMyDSpaceResultDetailElementComponent; +let fixture: ComponentFixture; + +const compIndex = 1; + +const mockResultObject: WorkspaceitemMyDSpaceResult = new WorkspaceitemMyDSpaceResult(); +mockResultObject.hitHighlights = {}; + +const item = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ], + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); +const rd = new RemoteData(false, false, true, null, item); +mockResultObject.indexableObject = Object.assign(new Workspaceitem(), { item: observableOf(rd) }); + +describe('WorkspaceitemMyDSpaceResultDetailElementComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [NoopAnimationsModule], + declarations: [WorkspaceitemMyDSpaceResultDetailElementComponent], + providers: [ + { provide: 'objectElementProvider', useValue: (mockResultObject) }, + { provide: 'indexElementProvider', useValue: (compIndex) } + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(WorkspaceitemMyDSpaceResultDetailElementComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(async(() => { + fixture = TestBed.createComponent(WorkspaceitemMyDSpaceResultDetailElementComponent); + component = fixture.componentInstance; + })); + + beforeEach(() => { + component.dso = mockResultObject.indexableObject; + fixture.detectChanges(); + }); + + it('should init item properly', () => { + expect(component.item).toEqual(item); + }); + + it('should have properly status', () => { + expect(component.status).toEqual(MyDspaceItemStatusType.WORKSPACE); + }); +}); diff --git a/src/app/shared/object-detail/my-dspace-result-detail-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-detail-element.component.ts b/src/app/shared/object-detail/my-dspace-result-detail-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-detail-element.component.ts new file mode 100644 index 0000000000..390db7ec28 --- /dev/null +++ b/src/app/shared/object-detail/my-dspace-result-detail-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-detail-element.component.ts @@ -0,0 +1,62 @@ +import { Component, Inject } from '@angular/core'; + +import { Observable } from 'rxjs'; +import { find } from 'rxjs/operators'; + +import { renderElementsFor } from '../../../object-collection/shared/dso-element-decorator'; +import { ViewMode } from '../../../../core/shared/view-mode.model'; +import { Workspaceitem } from '../../../../core/submission/models/workspaceitem.model'; +import { WorkspaceitemMyDSpaceResult } from '../../../object-collection/shared/workspaceitem-my-dspace-result.model'; +import { Item } from '../../../../core/shared/item.model'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { isNotUndefined } from '../../../empty.util'; +import { ListableObject } from '../../../object-collection/shared/listable-object.model'; +import { MyDSpaceResultDetailElementComponent } from '../my-dspace-result-detail-element.component'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { SetViewMode } from '../../../view-mode'; + +/** + * This component renders workspaceitem object for the mydspace result in the detail view. + */ +@Component({ + selector: 'ds-workspaceitem-my-dspace-result-detail-element', + styleUrls: ['../my-dspace-result-detail-element.component.scss', './workspaceitem-my-dspace-result-detail-element.component.scss'], + templateUrl: './workspaceitem-my-dspace-result-detail-element.component.html', +}) + +@renderElementsFor(WorkspaceitemMyDSpaceResult, SetViewMode.Detail) +@renderElementsFor(Workspaceitem, SetViewMode.Detail) +export class WorkspaceitemMyDSpaceResultDetailElementComponent extends MyDSpaceResultDetailElementComponent { + + /** + * The item object that belonging to the result object + */ + public item: Item; + + /** + * Represent item's status + */ + status = MyDspaceItemStatusType.WORKSPACE; + + constructor(@Inject('objectElementProvider') public listable: ListableObject) { + super(listable); + } + + /** + * Initialize all instance variables + */ + ngOnInit() { + this.initItem(this.dso.item as Observable>); + } + + /** + * Retrieve item from result object + */ + initItem(item$: Observable>) { + item$.pipe( + find((rd: RemoteData) => rd.hasSucceeded && isNotUndefined(rd.payload)) + ).subscribe((rd: RemoteData) => { + this.item = rd.payload; + }); + } +} diff --git a/src/app/shared/object-detail/object-detail.component.html b/src/app/shared/object-detail/object-detail.component.html new file mode 100644 index 0000000000..a57a23027e --- /dev/null +++ b/src/app/shared/object-detail/object-detail.component.html @@ -0,0 +1,22 @@ + + + + + + + + + diff --git a/src/app/shared/object-detail/object-detail.component.scss b/src/app/shared/object-detail/object-detail.component.scss new file mode 100644 index 0000000000..9a077e3e08 --- /dev/null +++ b/src/app/shared/object-detail/object-detail.component.scss @@ -0,0 +1,9 @@ +@import '../../../styles/variables'; +@import '../../../styles/mixins'; + +ds-wrapper-detail-element ::ng-deep { + div.thumbnail > img { + height: $card-thumbnail-height; + width: 100%; + } +} diff --git a/src/app/shared/object-detail/object-detail.component.spec.ts b/src/app/shared/object-detail/object-detail.component.spec.ts new file mode 100644 index 0000000000..9b81f1019f --- /dev/null +++ b/src/app/shared/object-detail/object-detail.component.spec.ts @@ -0,0 +1,181 @@ +import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { By } from '@angular/platform-browser'; +import { ObjectDetailComponent } from './object-detail.component'; +import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; +import { MockTranslateLoader } from '../mocks/mock-translate-loader'; +import { RemoteData } from '../../core/data/remote-data'; +import { PaginatedList } from '../../core/data/paginated-list'; +import { PageInfo } from '../../core/shared/page-info.model'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; + +describe('ObjectDetailComponent', () => { + let comp: ObjectDetailComponent; + let fixture: ComponentFixture; + const testEvent = {test: 'test'}; + + const testObjects = [ + { one: 1 }, + { two: 2 }, + { three: 3 }, + { four: 4 }, + { five: 5 }, + { six: 6 }, + { seven: 7 }, + { eight: 8 }, + { nine: 9 }, + { ten: 10 } + ]; + const pageInfo = Object.assign(new PageInfo(), {elementsPerPage: 1, totalElements: 10, totalPages: 10, currentPage: 1}) + const mockRD = new RemoteData(false, false, true, null, new PaginatedList(pageInfo, testObjects)); + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + NoopAnimationsModule, + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }) + ], + declarations: [ObjectDetailComponent], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(ObjectDetailComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(ObjectDetailComponent); + comp = fixture.componentInstance; // SearchPageComponent test instance + comp.objects = mockRD; + fixture.detectChanges(); + }); + + describe('when the pageChange output on the pagination is triggered', () => { + beforeEach(() => { + spyOn(comp, 'onPageChange'); + const paginationEl = fixture.debugElement.query(By.css('ds-pagination')); + paginationEl.triggerEventHandler('pageChange', testEvent); + }); + + it('should call onPageChange on the component', () => { + expect(comp.onPageChange).toHaveBeenCalledWith(testEvent); + }); + }); + + describe('when the pageSizeChange output on the pagination is triggered', () => { + beforeEach(() => { + spyOn(comp, 'onPageSizeChange'); + const paginationEl = fixture.debugElement.query(By.css('ds-pagination')); + paginationEl.triggerEventHandler('pageSizeChange', testEvent); + }); + + it('should call onPageSizeChange on the component', () => { + expect(comp.onPageSizeChange).toHaveBeenCalledWith(testEvent); + }); + }); + + describe('when the sortDirectionChange output on the pagination is triggered', () => { + beforeEach(() => { + spyOn(comp, 'onSortDirectionChange'); + const paginationEl = fixture.debugElement.query(By.css('ds-pagination')); + paginationEl.triggerEventHandler('sortDirectionChange', testEvent); + }); + + it('should call onSortDirectionChange on the component', () => { + expect(comp.onSortDirectionChange).toHaveBeenCalledWith(testEvent); + }); + }); + + describe('when the sortFieldChange output on the pagination is triggered', () => { + beforeEach(() => { + spyOn(comp, 'onSortFieldChange'); + const paginationEl = fixture.debugElement.query(By.css('ds-pagination')); + paginationEl.triggerEventHandler('sortFieldChange', testEvent); + }); + + it('should call onSortFieldChange on the component', () => { + expect(comp.onSortFieldChange).toHaveBeenCalledWith(testEvent); + }); + }); + + describe('when the paginationChange output on the pagination is triggered', () => { + beforeEach(() => { + spyOn(comp, 'onPaginationChange'); + const paginationEl = fixture.debugElement.query(By.css('ds-pagination')); + paginationEl.triggerEventHandler('paginationChange', testEvent); + }); + + it('should call onPaginationChange on the component', () => { + expect(comp.onPaginationChange).toHaveBeenCalledWith(testEvent); + }); + }); + + describe('when onPageChange is triggered with an event', () => { + beforeEach(() => { + spyOn(comp.pageChange, 'emit'); + comp.onPageChange(testEvent); + }); + + it('should emit the value from the pageChange EventEmitter', fakeAsync(() => { + tick(1); + expect(comp.pageChange.emit).toHaveBeenCalled(); + expect(comp.pageChange.emit).toHaveBeenCalledWith(testEvent); + })); + }); + + describe('when onPageSizeChange is triggered with an event', () => { + beforeEach(() => { + spyOn(comp.pageSizeChange, 'emit'); + comp.onPageSizeChange(testEvent); + }); + + it('should emit the value from the pageSizeChange EventEmitter', fakeAsync(() => { + tick(1); + expect(comp.pageSizeChange.emit).toHaveBeenCalled(); + expect(comp.pageSizeChange.emit).toHaveBeenCalledWith(testEvent); + })); + }); + + describe('when onSortDirectionChange is triggered with an event', () => { + beforeEach(() => { + spyOn(comp.sortDirectionChange, 'emit'); + comp.onSortDirectionChange(testEvent); + }); + + it('should emit the value from the sortDirectionChange EventEmitter', fakeAsync(() => { + tick(1); + expect(comp.sortDirectionChange.emit).toHaveBeenCalled(); + expect(comp.sortDirectionChange.emit).toHaveBeenCalledWith(testEvent); + })); + }); + + describe('when onSortFieldChange is triggered with an event', () => { + beforeEach(() => { + spyOn(comp.sortFieldChange, 'emit'); + comp.onSortFieldChange(testEvent); + }); + + it('should emit the value from the sortFieldChange EventEmitter', fakeAsync(() => { + tick(1); + expect(comp.sortFieldChange.emit).toHaveBeenCalled(); + expect(comp.sortFieldChange.emit).toHaveBeenCalledWith(testEvent); + })); + }); + + describe('when onPaginationChange is triggered with an event', () => { + beforeEach(() => { + spyOn(comp.paginationChange, 'emit'); + comp.onPaginationChange(testEvent); + }); + + it('should emit the value from the paginationChange EventEmitter', fakeAsync(() => { + tick(1); + expect(comp.paginationChange.emit).toHaveBeenCalled(); + expect(comp.paginationChange.emit).toHaveBeenCalledWith(testEvent); + })); + }); +}); diff --git a/src/app/shared/object-detail/object-detail.component.ts b/src/app/shared/object-detail/object-detail.component.ts new file mode 100644 index 0000000000..3187a2cd1b --- /dev/null +++ b/src/app/shared/object-detail/object-detail.component.ts @@ -0,0 +1,154 @@ +import { + ChangeDetectionStrategy, + Component, + EventEmitter, + Input, + Output, + ViewEncapsulation +} from '@angular/core'; + +import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model'; +import { PaginatedList } from '../../core/data/paginated-list'; + +import { RemoteData } from '../../core/data/remote-data'; +import { fadeIn } from '../animations/fade'; +import { ListableObject } from '../object-collection/shared/listable-object.model'; + +import { PaginationComponentOptions } from '../pagination/pagination-component-options.model'; + +/** + * This component renders a paginated set of results in the detail view. + */ +@Component({ + changeDetection: ChangeDetectionStrategy.Default, + encapsulation: ViewEncapsulation.Emulated, + selector: 'ds-object-detail', + styleUrls: [ './object-detail.component.scss' ], + templateUrl: './object-detail.component.html', + animations: [fadeIn] +}) +export class ObjectDetailComponent { + + /** + * Pagination options object + */ + @Input() config: PaginationComponentOptions; + + /** + * Sort options object + */ + @Input() sortConfig: SortOptions; + + /** + * A boolean representing if to hide gear pagination icon + */ + @Input() hideGear = true; + + /** + * A boolean representing if to hide pagination when there is only a page + */ + @Input() hidePagerWhenSinglePage = true; + + /** + * The list of objects to paginate + */ + private _objects: RemoteData>; + + /** + * Setter for _objects property + * @param objects + */ + @Input() set objects(objects: RemoteData>) { + this._objects = objects; + } + + /** + * Getter for _objects property + */ + get objects() { + return this._objects; + } + + /** + * Option for hiding the pagination detail + */ + public hidePaginationDetail = true; + + /** + * An event fired when the page is changed. + * Event's payload equals to the newly selected page. + */ + @Output() change: EventEmitter<{ + pagination: PaginationComponentOptions, + sort: SortOptions + }> = new EventEmitter<{ + pagination: PaginationComponentOptions, + sort: SortOptions + }>(); + + /** + * An event fired when the page is changed. + * Event's payload equals to the newly selected page. + */ + @Output() pageChange: EventEmitter = new EventEmitter(); + + /** + * An event fired when the page wsize is changed. + * Event's payload equals to the newly selected page size. + */ + @Output() pageSizeChange: EventEmitter = new EventEmitter(); + + /** + * An event fired when the sort direction is changed. + * Event's payload equals to the newly selected sort direction. + */ + @Output() sortDirectionChange: EventEmitter = new EventEmitter(); + + /** + * An event fired when the pagination is changed. + * Event's payload equals to the newly selected sort direction. + */ + @Output() paginationChange: EventEmitter = new EventEmitter(); + + /** + * An event fired when the sort field is changed. + * Event's payload equals to the newly selected sort field. + */ + @Output() sortFieldChange: EventEmitter = new EventEmitter(); + + /** + * Emit pageChange event + */ + onPageChange(event) { + this.pageChange.emit(event); + } + + /** + * Emit pageSizeChange event + */ + onPageSizeChange(event) { + this.pageSizeChange.emit(event); + } + + /** + * Emit sortDirectionChange event + */ + onSortDirectionChange(event) { + this.sortDirectionChange.emit(event); + } + + /** + * Emit sortFieldChange event + */ + onSortFieldChange(event) { + this.sortFieldChange.emit(event); + } + + /** + * Emit paginationChange event + */ + onPaginationChange(event) { + this.paginationChange.emit(event); + } + +} diff --git a/src/app/shared/object-detail/wrapper-detail-element/wrapper-detail-element.component.html b/src/app/shared/object-detail/wrapper-detail-element/wrapper-detail-element.component.html new file mode 100644 index 0000000000..00a8ed2dc8 --- /dev/null +++ b/src/app/shared/object-detail/wrapper-detail-element/wrapper-detail-element.component.html @@ -0,0 +1 @@ + diff --git a/src/app/shared/object-detail/wrapper-detail-element/wrapper-detail-element.component.scss b/src/app/shared/object-detail/wrapper-detail-element/wrapper-detail-element.component.scss new file mode 100644 index 0000000000..51a7fc6a55 --- /dev/null +++ b/src/app/shared/object-detail/wrapper-detail-element/wrapper-detail-element.component.scss @@ -0,0 +1,2 @@ +@import '../../../../styles/variables'; + diff --git a/src/app/shared/object-detail/wrapper-detail-element/wrapper-detail-element.component.spec.ts b/src/app/shared/object-detail/wrapper-detail-element/wrapper-detail-element.component.spec.ts new file mode 100644 index 0000000000..e54ae58398 --- /dev/null +++ b/src/app/shared/object-detail/wrapper-detail-element/wrapper-detail-element.component.spec.ts @@ -0,0 +1,44 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { NO_ERRORS_SCHEMA } from '@angular/core'; +import { By } from '@angular/platform-browser'; +import { ActivatedRoute, Router } from '@angular/router'; + +import { of as observableOf } from 'rxjs'; + +import { RouterStub } from '../../testing/router-stub'; +import { WrapperDetailElementComponent } from './wrapper-detail-element.component'; + +let wrapperDetailElementComponent: WrapperDetailElementComponent; +let fixture: ComponentFixture; +const queryParam = 'test query'; +const scopeParam = '7669c72a-3f2a-451f-a3b9-9210e7a4c02f'; +const activatedRouteStub = { + queryParams: observableOf({ + query: queryParam, + scope: scopeParam + }) +}; + +describe('WrapperDetailElementComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [ WrapperDetailElementComponent ], + providers: [ + { provide: ActivatedRoute, useValue: activatedRouteStub }, + { provide: Router, useClass: RouterStub }, + { provide: 'objectElementProvider', useFactory: (WrapperDetailElementComponent)} + ], + + schemas: [ NO_ERRORS_SCHEMA ] + }).compileComponents(); // compile template and css + })); + + beforeEach(async(() => { + fixture = TestBed.createComponent(WrapperDetailElementComponent); + wrapperDetailElementComponent = fixture.componentInstance; + })); + + it('should show the wrapper element containing the detail object',() => { + expect(fixture.debugElement.query(By.css('ds-workspaceitem-my-dspace-result-detail-element'))).toBeDefined(); + }) +}); diff --git a/src/app/shared/object-detail/wrapper-detail-element/wrapper-detail-element.component.ts b/src/app/shared/object-detail/wrapper-detail-element/wrapper-detail-element.component.ts new file mode 100644 index 0000000000..92b30f9ce7 --- /dev/null +++ b/src/app/shared/object-detail/wrapper-detail-element/wrapper-detail-element.component.ts @@ -0,0 +1,55 @@ +import { Component, Injector, Input, OnInit } from '@angular/core'; + +import { ViewMode } from '../../../core/shared/view-mode.model'; +import { GenericConstructor } from '../../../core/shared/generic-constructor'; +import { rendersDSOType } from '../../object-collection/shared/dso-element-decorator'; +import { ListableObject } from '../../object-collection/shared/listable-object.model'; +import { SetViewMode } from '../../view-mode'; + +/** + * This component renders a wrapper for an object in the detail view. + */ +@Component({ + selector: 'ds-wrapper-detail-element', + styleUrls: ['./wrapper-detail-element.component.scss'], + templateUrl: './wrapper-detail-element.component.html' +}) +export class WrapperDetailElementComponent implements OnInit { + + /** + * The listable object. + */ + @Input() object: ListableObject; + + /** + * The instance of the injector. + */ + objectInjector: Injector; + + /** + * Initialize instance variables + * + * @param {Injector} injector + */ + constructor(private injector: Injector) { + } + + /** + * Initialize injector + */ + ngOnInit(): void { + this.objectInjector = Injector.create({ + providers: [{ provide: 'objectElementProvider', useFactory: () => (this.object), deps:[] }], + parent: this.injector + }); + + } + + /** + * Return class name for the object to inject + */ + getDetailElement(): string { + const f: GenericConstructor = this.object.constructor as GenericConstructor; + return rendersDSOType(f, SetViewMode.Detail); + } +} diff --git a/src/app/shared/object-grid/search-result-grid-element/collection-search-result/collection-search-result-grid-element.component.spec.ts b/src/app/shared/object-grid/search-result-grid-element/collection-search-result/collection-search-result-grid-element.component.spec.ts index e8f8b1330e..07f3960d55 100644 --- a/src/app/shared/object-grid/search-result-grid-element/collection-search-result/collection-search-result-grid-element.component.spec.ts +++ b/src/app/shared/object-grid/search-result-grid-element/collection-search-result/collection-search-result-grid-element.component.spec.ts @@ -17,7 +17,7 @@ const truncatableServiceStub: any = { const mockCollectionWithAbstract: CollectionSearchResult = new CollectionSearchResult(); mockCollectionWithAbstract.hitHighlights = {}; -mockCollectionWithAbstract.dspaceObject = Object.assign(new Collection(), { +mockCollectionWithAbstract.indexableObject = Object.assign(new Collection(), { metadata: { 'dc.description.abstract': [ { @@ -30,7 +30,7 @@ mockCollectionWithAbstract.dspaceObject = Object.assign(new Collection(), { const mockCollectionWithoutAbstract: CollectionSearchResult = new CollectionSearchResult(); mockCollectionWithoutAbstract.hitHighlights = {}; -mockCollectionWithoutAbstract.dspaceObject = Object.assign(new Collection(), { +mockCollectionWithoutAbstract.indexableObject = Object.assign(new Collection(), { metadata: { 'dc.title': [ { @@ -63,7 +63,7 @@ describe('CollectionSearchResultGridElementComponent', () => { describe('When the collection has an abstract', () => { beforeEach(() => { - collectionSearchResultGridElementComponent.dso = mockCollectionWithAbstract.dspaceObject; + collectionSearchResultGridElementComponent.dso = mockCollectionWithAbstract.indexableObject; fixture.detectChanges(); }); @@ -75,7 +75,7 @@ describe('CollectionSearchResultGridElementComponent', () => { describe('When the collection has no abstract', () => { beforeEach(() => { - collectionSearchResultGridElementComponent.dso = mockCollectionWithoutAbstract.dspaceObject; + collectionSearchResultGridElementComponent.dso = mockCollectionWithoutAbstract.indexableObject; fixture.detectChanges(); }); diff --git a/src/app/shared/object-grid/search-result-grid-element/community-search-result/community-search-result-grid-element.component.spec.ts b/src/app/shared/object-grid/search-result-grid-element/community-search-result/community-search-result-grid-element.component.spec.ts index e111e624c5..567b2e1d0e 100644 --- a/src/app/shared/object-grid/search-result-grid-element/community-search-result/community-search-result-grid-element.component.spec.ts +++ b/src/app/shared/object-grid/search-result-grid-element/community-search-result/community-search-result-grid-element.component.spec.ts @@ -17,7 +17,7 @@ const truncatableServiceStub: any = { const mockCommunityWithAbstract: CommunitySearchResult = new CommunitySearchResult(); mockCommunityWithAbstract.hitHighlights = {}; -mockCommunityWithAbstract.dspaceObject = Object.assign(new Community(), { +mockCommunityWithAbstract.indexableObject = Object.assign(new Community(), { metadata: { 'dc.description.abstract': [ { @@ -30,7 +30,7 @@ mockCommunityWithAbstract.dspaceObject = Object.assign(new Community(), { const mockCommunityWithoutAbstract: CommunitySearchResult = new CommunitySearchResult(); mockCommunityWithoutAbstract.hitHighlights = {}; -mockCommunityWithoutAbstract.dspaceObject = Object.assign(new Community(), { +mockCommunityWithoutAbstract.indexableObject = Object.assign(new Community(), { metadata: { 'dc.title': [ { @@ -63,7 +63,7 @@ describe('CommunitySearchResultGridElementComponent', () => { describe('When the community has an abstract', () => { beforeEach(() => { - communitySearchResultGridElementComponent.dso = mockCommunityWithAbstract.dspaceObject; + communitySearchResultGridElementComponent.dso = mockCommunityWithAbstract.indexableObject; fixture.detectChanges(); }); @@ -75,7 +75,7 @@ describe('CommunitySearchResultGridElementComponent', () => { describe('When the community has no abstract', () => { beforeEach(() => { - communitySearchResultGridElementComponent.dso = mockCommunityWithoutAbstract.dspaceObject; + communitySearchResultGridElementComponent.dso = mockCommunityWithoutAbstract.indexableObject; fixture.detectChanges(); }); diff --git a/src/app/shared/object-grid/search-result-grid-element/item-search-result/item-search-result-grid-element.component.spec.ts b/src/app/shared/object-grid/search-result-grid-element/item-search-result/item-search-result-grid-element.component.spec.ts index 0103fa5c49..655fd268a7 100644 --- a/src/app/shared/object-grid/search-result-grid-element/item-search-result/item-search-result-grid-element.component.spec.ts +++ b/src/app/shared/object-grid/search-result-grid-element/item-search-result/item-search-result-grid-element.component.spec.ts @@ -18,7 +18,7 @@ const truncatableServiceStub: any = { const mockItemWithAuthorAndDate: ItemSearchResult = new ItemSearchResult(); mockItemWithAuthorAndDate.hitHighlights = {}; -mockItemWithAuthorAndDate.dspaceObject = Object.assign(new Item(), { +mockItemWithAuthorAndDate.indexableObject = Object.assign(new Item(), { bitstreams: observableOf({}), metadata: { 'dc.contributor.author': [ @@ -38,7 +38,7 @@ mockItemWithAuthorAndDate.dspaceObject = Object.assign(new Item(), { const mockItemWithoutAuthorAndDate: ItemSearchResult = new ItemSearchResult(); mockItemWithoutAuthorAndDate.hitHighlights = {}; -mockItemWithoutAuthorAndDate.dspaceObject = Object.assign(new Item(), { +mockItemWithoutAuthorAndDate.indexableObject = Object.assign(new Item(), { bitstreams: observableOf({}), metadata: { 'dc.title': [ @@ -78,7 +78,7 @@ describe('ItemSearchResultGridElementComponent', () => { describe('When the item has an author', () => { beforeEach(() => { - itemSearchResultGridElementComponent.dso = mockItemWithAuthorAndDate.dspaceObject; + itemSearchResultGridElementComponent.dso = mockItemWithAuthorAndDate.indexableObject; fixture.detectChanges(); }); @@ -90,7 +90,7 @@ describe('ItemSearchResultGridElementComponent', () => { describe('When the item has no author', () => { beforeEach(() => { - itemSearchResultGridElementComponent.dso = mockItemWithoutAuthorAndDate.dspaceObject; + itemSearchResultGridElementComponent.dso = mockItemWithoutAuthorAndDate.indexableObject; fixture.detectChanges(); }); @@ -102,7 +102,7 @@ describe('ItemSearchResultGridElementComponent', () => { describe('When the item has an issuedate', () => { beforeEach(() => { - itemSearchResultGridElementComponent.dso = mockItemWithAuthorAndDate.dspaceObject; + itemSearchResultGridElementComponent.dso = mockItemWithAuthorAndDate.indexableObject; fixture.detectChanges(); }); @@ -114,7 +114,7 @@ describe('ItemSearchResultGridElementComponent', () => { describe('When the item has no issuedate', () => { beforeEach(() => { - itemSearchResultGridElementComponent.dso = mockItemWithoutAuthorAndDate.dspaceObject; + itemSearchResultGridElementComponent.dso = mockItemWithoutAuthorAndDate.indexableObject; fixture.detectChanges(); }); diff --git a/src/app/shared/object-grid/search-result-grid-element/search-result-grid-element.component.ts b/src/app/shared/object-grid/search-result-grid-element/search-result-grid-element.component.ts index 844d0bc165..0961dc96ee 100644 --- a/src/app/shared/object-grid/search-result-grid-element/search-result-grid-element.component.ts +++ b/src/app/shared/object-grid/search-result-grid-element/search-result-grid-element.component.ts @@ -18,7 +18,7 @@ export class SearchResultGridElementComponent, K exten public constructor(@Inject('objectElementProvider') public listableObject: ListableObject, private truncatableService: TruncatableService) { super(listableObject); - this.dso = this.object.dspaceObject; + this.dso = this.object.indexableObject; } /** diff --git a/src/app/shared/object-list/item-list-element/item-types/typed-item-search-result-list-element.component.spec.ts b/src/app/shared/object-list/item-list-element/item-types/typed-item-search-result-list-element.component.spec.ts index 49d6ead11a..f320ff2efc 100644 --- a/src/app/shared/object-list/item-list-element/item-types/typed-item-search-result-list-element.component.spec.ts +++ b/src/app/shared/object-list/item-list-element/item-types/typed-item-search-result-list-element.component.spec.ts @@ -19,7 +19,7 @@ const mockItem: Item = Object.assign(new Item(), { relationships: createRelationshipsObservable() }); const mockSearchResult = { - dspaceObject: mockItem as Item, + indexableObject: mockItem as Item, hitHighlights: new MetadataMap() } as ItemSearchResult; @@ -50,7 +50,7 @@ describe('ItemSearchResultComponent', () => { it('should initiate item, object and dso correctly', () => { expect(comp.item).toBe(mockItem); expect(comp.dso).toBe(mockItem); - expect(comp.object.dspaceObject).toBe(mockItem); + expect(comp.object.indexableObject).toBe(mockItem); }) }); @@ -77,7 +77,7 @@ describe('ItemSearchResultComponent', () => { it('should initiate item, object and dso correctly', () => { expect(comp.item).toBe(mockItem); expect(comp.dso).toBe(mockItem); - expect(comp.object.dspaceObject).toBe(mockItem); + expect(comp.object.indexableObject).toBe(mockItem); }) }); }); diff --git a/src/app/shared/object-list/item-list-element/item-types/typed-item-search-result-list-element.component.ts b/src/app/shared/object-list/item-list-element/item-types/typed-item-search-result-list-element.component.ts index af9474935c..37ac426f35 100644 --- a/src/app/shared/object-list/item-list-element/item-types/typed-item-search-result-list-element.component.ts +++ b/src/app/shared/object-list/item-list-element/item-types/typed-item-search-result-list-element.component.ts @@ -24,10 +24,10 @@ export class TypedItemSearchResultListElementComponent extends SearchResultListE super(undefined, truncatableService); if (hasValue((obj as any).dspaceObject)) { this.object = obj as ItemSearchResult; - this.dso = this.object.dspaceObject; + this.dso = this.object.indexableObject; } else { this.object = { - dspaceObject: obj as Item, + indexableObject: obj as Item, hitHighlights: new MetadataMap() }; this.dso = obj as Item; diff --git a/src/app/shared/object-list/my-dspace-result-list-element/claimed-my-dspace-result/claimed-my-dspace-result-list-element.component.html b/src/app/shared/object-list/my-dspace-result-list-element/claimed-my-dspace-result/claimed-my-dspace-result-list-element.component.html new file mode 100644 index 0000000000..5ec4c9a5b5 --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/claimed-my-dspace-result/claimed-my-dspace-result-list-element.component.html @@ -0,0 +1,7 @@ + + + diff --git a/src/app/shared/object-list/my-dspace-result-list-element/claimed-my-dspace-result/claimed-my-dspace-result-list-element.component.spec.ts b/src/app/shared/object-list/my-dspace-result-list-element/claimed-my-dspace-result/claimed-my-dspace-result-list-element.component.spec.ts new file mode 100644 index 0000000000..7c30b2ef8c --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/claimed-my-dspace-result/claimed-my-dspace-result-list-element.component.spec.ts @@ -0,0 +1,89 @@ +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; + +import { of as observableOf } from 'rxjs'; + +import { Item } from '../../../../core/shared/item.model'; +import { ClaimedMyDSpaceResultListElementComponent } from './claimed-my-dspace-result-list-element.component'; +import { ClaimedTaskMyDSpaceResult } from '../../../object-collection/shared/claimed-task-my-dspace-result.model'; +import { ClaimedTask } from '../../../../core/tasks/models/claimed-task-object.model'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { Workflowitem } from '../../../../core/submission/models/workflowitem.model'; + +let component: ClaimedMyDSpaceResultListElementComponent; +let fixture: ComponentFixture; + +const compIndex = 1; + +const mockResultObject: ClaimedTaskMyDSpaceResult = new ClaimedTaskMyDSpaceResult(); +mockResultObject.hitHighlights = {}; + +const item = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ], + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); +const rdItem = new RemoteData(false, false, true, null, item); +const workflowitem = Object.assign(new Workflowitem(), { item: observableOf(rdItem) }); +const rdWorkflowitem = new RemoteData(false, false, true, null, workflowitem); +mockResultObject.indexableObject = Object.assign(new ClaimedTask(), { workflowitem: observableOf(rdWorkflowitem) }); + +describe('ClaimedMyDSpaceResultListElementComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [NoopAnimationsModule], + declarations: [ClaimedMyDSpaceResultListElementComponent], + providers: [ + { provide: 'objectElementProvider', useValue: (mockResultObject) }, + { provide: 'indexElementProvider', useValue: (compIndex) } + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(ClaimedMyDSpaceResultListElementComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(async(() => { + fixture = TestBed.createComponent(ClaimedMyDSpaceResultListElementComponent); + component = fixture.componentInstance; + })); + + beforeEach(() => { + component.dso = mockResultObject.indexableObject; + fixture.detectChanges(); + }); + + it('should init item properly', () => { + expect(component.workflowitem).toEqual(workflowitem); + }); + + it('should have properly status', () => { + expect(component.status).toEqual(MyDspaceItemStatusType.VALIDATION); + }); +}); diff --git a/src/app/shared/object-list/my-dspace-result-list-element/claimed-my-dspace-result/claimed-my-dspace-result-list-element.component.ts b/src/app/shared/object-list/my-dspace-result-list-element/claimed-my-dspace-result/claimed-my-dspace-result-list-element.component.ts new file mode 100644 index 0000000000..0725f98897 --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/claimed-my-dspace-result/claimed-my-dspace-result-list-element.component.ts @@ -0,0 +1,64 @@ +import { Component } from '@angular/core'; +import { Location, LocationStrategy, PathLocationStrategy } from '@angular/common'; + +import { Observable } from 'rxjs'; +import { find } from 'rxjs/operators'; + +import { renderElementsFor } from '../../../object-collection/shared/dso-element-decorator'; +import { MyDSpaceResultListElementComponent, } from '../my-dspace-result-list-element.component'; +import { ViewMode } from '../../../../core/shared/view-mode.model'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { isNotUndefined } from '../../../empty.util'; +import { Workflowitem } from '../../../../core/submission/models/workflowitem.model'; +import { ClaimedTask } from '../../../../core/tasks/models/claimed-task-object.model'; +import { ClaimedTaskMyDSpaceResult } from '../../../object-collection/shared/claimed-task-my-dspace-result.model'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { SetViewMode } from '../../../view-mode'; + +/** + * This component renders claimed task object for the mydspace result in the list view. + */ +@Component({ + selector: 'ds-claimed-my-dspace-result-list-element', + styleUrls: ['../my-dspace-result-list-element.component.scss'], + templateUrl: './claimed-my-dspace-result-list-element.component.html', + providers: [Location, { provide: LocationStrategy, useClass: PathLocationStrategy }] +}) + +@renderElementsFor(ClaimedTaskMyDSpaceResult, SetViewMode.List) +@renderElementsFor(ClaimedTask, SetViewMode.List) +export class ClaimedMyDSpaceResultListElementComponent extends MyDSpaceResultListElementComponent { + + /** + * A boolean representing if to show submitter information + */ + public showSubmitter = true; + + /** + * Represent item's status + */ + public status = MyDspaceItemStatusType.VALIDATION; + + /** + * The workflowitem object that belonging to the result object + */ + public workflowitem: Workflowitem; + + /** + * Initialize all instance variables + */ + ngOnInit() { + this.initWorkflowItem(this.dso.workflowitem as Observable>); + } + + /** + * Retrieve workflowitem from result object + */ + initWorkflowItem(wfi$: Observable>) { + wfi$.pipe( + find((rd: RemoteData) => (rd.hasSucceeded && isNotUndefined(rd.payload))) + ).subscribe((rd: RemoteData) => { + this.workflowitem = rd.payload; + }); + } +} diff --git a/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.html b/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.html new file mode 100644 index 0000000000..bcd5c3c027 --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.html @@ -0,0 +1,32 @@ + + + + + + + + + + ( + ) + + {{'mydspace.results.no-authors' | translate}} + + + + + + + + + + + + + + + + diff --git a/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.scss b/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.scss new file mode 100644 index 0000000000..e69de29bb2 diff --git a/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.spec.ts b/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.spec.ts new file mode 100644 index 0000000000..17b0279c7a --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.spec.ts @@ -0,0 +1,131 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { By } from '@angular/platform-browser'; + +import { of as observableOf } from 'rxjs'; + +import { TruncatePipe } from '../../../utils/truncate.pipe'; +import { Item } from '../../../../core/shared/item.model'; +import { ItemListPreviewComponent } from './item-list-preview.component'; +import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; +import { MockTranslateLoader } from '../../../mocks/mock-translate-loader'; + +let component: ItemListPreviewComponent; +let fixture: ComponentFixture; + +const mockItemWithAuthorAndDate: Item = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); +const mockItemWithoutAuthorAndDate: Item = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ] + } +}); + +describe('ItemListPreviewComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ + TranslateModule.forRoot({ + loader: { + provide: TranslateLoader, + useClass: MockTranslateLoader + } + }), + ], + declarations: [ItemListPreviewComponent, TruncatePipe], + providers: [ + { provide: 'objectElementProvider', useValue: { mockItemWithAuthorAndDate } } + + ], + + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(ItemListPreviewComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(async(() => { + fixture = TestBed.createComponent(ItemListPreviewComponent); + component = fixture.componentInstance; + + })); + + beforeEach(() => { + component.object = { hitHighlights: {} } as any; + }); + + describe('When the item has an author', () => { + beforeEach(() => { + component.item = mockItemWithAuthorAndDate; + fixture.detectChanges(); + }); + + it('should show the author paragraph', () => { + const itemAuthorField = fixture.debugElement.query(By.css('span.item-list-authors')); + expect(itemAuthorField).not.toBeNull(); + }); + }); + + describe('When the item has no author', () => { + beforeEach(() => { + component.item = mockItemWithoutAuthorAndDate; + fixture.detectChanges(); + }); + + it('should not show the author paragraph', () => { + const itemAuthorField = fixture.debugElement.query(By.css('span.item-list-authors')); + expect(itemAuthorField).toBeNull(); + }); + }); + + describe('When the item has an issuedate', () => { + beforeEach(() => { + component.item = mockItemWithAuthorAndDate; + fixture.detectChanges(); + }); + + it('should show the issuedate span', () => { + const dateField = fixture.debugElement.query(By.css('span.item-list-date')); + expect(dateField).not.toBeNull(); + }); + }); + + describe('When the item has no issuedate', () => { + beforeEach(() => { + component.item = mockItemWithoutAuthorAndDate; + fixture.detectChanges(); + }); + + it('should show the issuedate empty placeholder', () => { + const dateField = fixture.debugElement.query(By.css('span.item-list-date')); + expect(dateField).not.toBeNull(); + }); + }); +}); diff --git a/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.ts b/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.ts new file mode 100644 index 0000000000..13876ab46a --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component.ts @@ -0,0 +1,39 @@ +import { Component, Input } from '@angular/core'; + +import { Item } from '../../../../core/shared/item.model'; +import { fadeInOut } from '../../../animations/fade'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { MyDSpaceResult } from '../../../../+my-dspace-page/my-dspace-result.model'; + +/** + * This component show metadata for the given item object in the list view. + */ +@Component({ + selector: 'ds-item-list-preview', + styleUrls: ['item-list-preview.component.scss'], + templateUrl: 'item-list-preview.component.html', + animations: [fadeInOut] +}) +export class ItemListPreviewComponent { + + /** + * The item to display + */ + @Input() item: Item; + + /** + * The mydspace result object + */ + @Input() object: MyDSpaceResult; + + /** + * Represent item's status + */ + @Input() status: MyDspaceItemStatusType; + + /** + * A boolean representing if to show submitter information + */ + @Input() showSubmitter = false; + +} diff --git a/src/app/shared/object-list/my-dspace-result-list-element/item-my-dspace-result/item-my-dspace-result-list-element.component.html b/src/app/shared/object-list/my-dspace-result-list-element/item-my-dspace-result/item-my-dspace-result-list-element.component.html new file mode 100644 index 0000000000..e1b1435481 --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/item-my-dspace-result/item-my-dspace-result-list-element.component.html @@ -0,0 +1,5 @@ + + + diff --git a/src/app/shared/object-list/my-dspace-result-list-element/item-my-dspace-result/item-my-dspace-result-list-element.component.scss b/src/app/shared/object-list/my-dspace-result-list-element/item-my-dspace-result/item-my-dspace-result-list-element.component.scss new file mode 100644 index 0000000000..1d0786105c --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/item-my-dspace-result/item-my-dspace-result-list-element.component.scss @@ -0,0 +1 @@ +@import '../../../../../styles/variables'; diff --git a/src/app/shared/object-list/my-dspace-result-list-element/item-my-dspace-result/item-my-dspace-result-list-element.component.spec.ts b/src/app/shared/object-list/my-dspace-result-list-element/item-my-dspace-result/item-my-dspace-result-list-element.component.spec.ts new file mode 100644 index 0000000000..ea4f2d24f3 --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/item-my-dspace-result/item-my-dspace-result-list-element.component.spec.ts @@ -0,0 +1,78 @@ +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; + +import { of as observableOf } from 'rxjs'; + +import { Item } from '../../../../core/shared/item.model'; +import { ItemMyDSpaceResultListElementComponent } from './item-my-dspace-result-list-element.component'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { ItemMyDSpaceResult } from '../../../object-collection/shared/item-my-dspace-result.model'; + +let component: ItemMyDSpaceResultListElementComponent; +let fixture: ComponentFixture; + +const compIndex = 1; + +const mockResultObject: ItemMyDSpaceResult = new ItemMyDSpaceResult(); +mockResultObject.hitHighlights = {}; + +mockResultObject.indexableObject = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ], + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); + +describe('ItemMyDSpaceResultListElementComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [NoopAnimationsModule], + declarations: [ItemMyDSpaceResultListElementComponent], + providers: [ + { provide: 'objectElementProvider', useValue: (mockResultObject) }, + { provide: 'indexElementProvider', useValue: (compIndex) } + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(ItemMyDSpaceResultListElementComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(async(() => { + fixture = TestBed.createComponent(ItemMyDSpaceResultListElementComponent); + component = fixture.componentInstance; + })); + + beforeEach(() => { + component.dso = mockResultObject.indexableObject; + fixture.detectChanges(); + }); + + it('should have properly status', () => { + expect(component.status).toEqual(MyDspaceItemStatusType.ARCHIVED); + }); +}); diff --git a/src/app/shared/object-list/my-dspace-result-list-element/item-my-dspace-result/item-my-dspace-result-list-element.component.ts b/src/app/shared/object-list/my-dspace-result-list-element/item-my-dspace-result/item-my-dspace-result-list-element.component.ts new file mode 100644 index 0000000000..3f2a439603 --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/item-my-dspace-result/item-my-dspace-result-list-element.component.ts @@ -0,0 +1,27 @@ +import { Component } from '@angular/core'; + +import { renderElementsFor } from '../../../object-collection/shared/dso-element-decorator'; +import { MyDSpaceResultListElementComponent, } from '../my-dspace-result-list-element.component'; +import { Item } from '../../../../core/shared/item.model'; +import { ItemMyDSpaceResult } from '../../../object-collection/shared/item-my-dspace-result.model'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { SetViewMode } from '../../../view-mode'; + +/** + * This component renders item object for the mydspace result in the list view. + */ +@Component({ + selector: 'ds-workspaceitem-my-dspace-result-list-element', + styleUrls: ['../my-dspace-result-list-element.component.scss', './item-my-dspace-result-list-element.component.scss'], + templateUrl: './item-my-dspace-result-list-element.component.html' +}) + +@renderElementsFor(ItemMyDSpaceResult, SetViewMode.List) +export class ItemMyDSpaceResultListElementComponent extends MyDSpaceResultListElementComponent { + + /** + * Represent item's status + */ + public status = MyDspaceItemStatusType.ARCHIVED; + +} diff --git a/src/app/shared/object-list/my-dspace-result-list-element/my-dspace-result-list-element.component.scss b/src/app/shared/object-list/my-dspace-result-list-element/my-dspace-result-list-element.component.scss new file mode 100644 index 0000000000..4cd8a2b697 --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/my-dspace-result-list-element.component.scss @@ -0,0 +1 @@ +@import '../search-result-list-element/search-result-list-element.component.scss'; diff --git a/src/app/shared/object-list/my-dspace-result-list-element/my-dspace-result-list-element.component.ts b/src/app/shared/object-list/my-dspace-result-list-element/my-dspace-result-list-element.component.ts new file mode 100644 index 0000000000..b2a5bf14fd --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/my-dspace-result-list-element.component.ts @@ -0,0 +1,58 @@ +import { Component, Inject } from '@angular/core'; + +import { MyDSpaceResult } from '../../../+my-dspace-page/my-dspace-result.model'; +import { AbstractListableElementComponent } from '../../object-collection/shared/object-collection-element/abstract-listable-element.component'; +import { ListableObject } from '../../object-collection/shared/listable-object.model'; +import { DSpaceObject } from '../../../core/shared/dspace-object.model'; +import { Metadata } from '../../../core/shared/metadata.utils'; + +@Component({ + selector: 'ds-my-dspace-result-list-element', + template: `` +}) +export class MyDSpaceResultListElementComponent, K extends DSpaceObject> extends AbstractListableElementComponent { + + /** + * The result element object + */ + dso: K; + + /** + * The array index of the result element + */ + dsoIndex: number; + + /** + * Initialize instance variables + * + * @param {ListableObject} listable + * @param {number} index + */ + public constructor(@Inject('objectElementProvider') public listable: ListableObject, + @Inject('indexElementProvider') public index: number) { + super(listable); + this.dso = this.object.indexableObject; + this.dsoIndex = this.index; + } + + /** + * Gets all matching metadata string values from hitHighlights or dso metadata, preferring hitHighlights. + * + * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. + * @returns {string[]} the matching string values or an empty array. + */ + allMetadataValues(keyOrKeys: string | string[]): string[] { + return Metadata.allValues([this.object.hitHighlights, this.dso.metadata], keyOrKeys); + } + + /** + * Gets the first matching metadata string value from hitHighlights or dso metadata, preferring hitHighlights. + * + * @param {string|string[]} keyOrKeys The metadata key(s) in scope. Wildcards are supported; see [[Metadata]]. + * @returns {string} the first matching string value, or `undefined`. + */ + firstMetadataValue(keyOrKeys: string | string[]): string { + return Metadata.firstValue([this.object.hitHighlights, this.dso.metadata], keyOrKeys); + } + +} diff --git a/src/app/shared/object-list/my-dspace-result-list-element/pool-my-dspace-result/pool-my-dspace-result-list-element.component.html b/src/app/shared/object-list/my-dspace-result-list-element/pool-my-dspace-result/pool-my-dspace-result-list-element.component.html new file mode 100644 index 0000000000..5f0f1bb6d4 --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/pool-my-dspace-result/pool-my-dspace-result-list-element.component.html @@ -0,0 +1,7 @@ + + + diff --git a/src/app/shared/object-list/my-dspace-result-list-element/pool-my-dspace-result/pool-my-dspace-result-list-element.component.spec.ts b/src/app/shared/object-list/my-dspace-result-list-element/pool-my-dspace-result/pool-my-dspace-result-list-element.component.spec.ts new file mode 100644 index 0000000000..36eb8f253a --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/pool-my-dspace-result/pool-my-dspace-result-list-element.component.spec.ts @@ -0,0 +1,89 @@ +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; + +import { of as observableOf } from 'rxjs'; + +import { Item } from '../../../../core/shared/item.model'; +import { PoolMyDSpaceResultListElementComponent } from './pool-my-dspace-result-list-element.component'; +import { PoolTaskMyDSpaceResult } from '../../../object-collection/shared/pool-task-my-dspace-result.model'; +import { PoolTask } from '../../../../core/tasks/models/pool-task-object.model'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { Workflowitem } from '../../../../core/submission/models/workflowitem.model'; + +let component: PoolMyDSpaceResultListElementComponent; +let fixture: ComponentFixture; + +const compIndex = 1; + +const mockResultObject: PoolTaskMyDSpaceResult = new PoolTaskMyDSpaceResult(); +mockResultObject.hitHighlights = {}; + +const item = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ], + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); +const rdItem = new RemoteData(false, false, true, null, item); +const workflowitem = Object.assign(new Workflowitem(), { item: observableOf(rdItem) }); +const rdWorkflowitem = new RemoteData(false, false, true, null, workflowitem); +mockResultObject.indexableObject = Object.assign(new PoolTask(), { workflowitem: observableOf(rdWorkflowitem) }); + +describe('PoolMyDSpaceResultListElementComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [NoopAnimationsModule], + declarations: [PoolMyDSpaceResultListElementComponent], + providers: [ + { provide: 'objectElementProvider', useValue: (mockResultObject) }, + { provide: 'indexElementProvider', useValue: (compIndex) } + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(PoolMyDSpaceResultListElementComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(async(() => { + fixture = TestBed.createComponent(PoolMyDSpaceResultListElementComponent); + component = fixture.componentInstance; + })); + + beforeEach(() => { + component.dso = mockResultObject.indexableObject; + fixture.detectChanges(); + }); + + it('should init item properly', () => { + expect(component.workflowitem).toEqual(workflowitem); + }); + + it('should have properly status', () => { + expect(component.status).toEqual(MyDspaceItemStatusType.WAITING_CONTROLLER); + }); +}); diff --git a/src/app/shared/object-list/my-dspace-result-list-element/pool-my-dspace-result/pool-my-dspace-result-list-element.component.ts b/src/app/shared/object-list/my-dspace-result-list-element/pool-my-dspace-result/pool-my-dspace-result-list-element.component.ts new file mode 100644 index 0000000000..2d78a7e2e8 --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/pool-my-dspace-result/pool-my-dspace-result-list-element.component.ts @@ -0,0 +1,68 @@ +import { Component, Inject, OnInit } from '@angular/core'; + +import { Observable } from 'rxjs'; +import { find } from 'rxjs/operators'; + +import { renderElementsFor } from '../../../object-collection/shared/dso-element-decorator'; +import { MyDSpaceResultListElementComponent, } from '../my-dspace-result-list-element.component'; +import { ViewMode } from '../../../../core/shared/view-mode.model'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { isNotUndefined } from '../../../empty.util'; +import { ListableObject } from '../../../object-collection/shared/listable-object.model'; +import { Workflowitem } from '../../../../core/submission/models/workflowitem.model'; +import { PoolTask } from '../../../../core/tasks/models/pool-task-object.model'; +import { PoolTaskMyDSpaceResult } from '../../../object-collection/shared/pool-task-my-dspace-result.model'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { SetViewMode } from '../../../view-mode'; + +/** + * This component renders pool task object for the mydspace result in the list view. + */ +@Component({ + selector: 'ds-pool-my-dspace-result-list-element', + styleUrls: ['../my-dspace-result-list-element.component.scss'], + templateUrl: './pool-my-dspace-result-list-element.component.html', +}) + +@renderElementsFor(PoolTaskMyDSpaceResult, SetViewMode.List) +@renderElementsFor(PoolTask, SetViewMode.List) +export class PoolMyDSpaceResultListElementComponent extends MyDSpaceResultListElementComponent implements OnInit { + + /** + * A boolean representing if to show submitter information + */ + public showSubmitter = true; + + /** + * Represent item's status + */ + public status = MyDspaceItemStatusType.WAITING_CONTROLLER; + + /** + * The workflowitem object that belonging to the result object + */ + public workflowitem: Workflowitem; + + constructor(@Inject('objectElementProvider') public listable: ListableObject, + @Inject('indexElementProvider') public index: number) { + super(listable, index); + } + + /** + * Initialize all instance variables + */ + ngOnInit() { + this.initWorkflowItem(this.dso.workflowitem as Observable>); + } + + /** + * Retrieve workflowitem from result object + */ + initWorkflowItem(wfi$: Observable>) { + wfi$.pipe( + find((rd: RemoteData) => (rd.hasSucceeded && isNotUndefined(rd.payload))) + ).subscribe((rd: RemoteData) => { + this.workflowitem = rd.payload; + }); + } +} diff --git a/src/app/shared/object-list/my-dspace-result-list-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-list-element.component.html b/src/app/shared/object-list/my-dspace-result-list-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-list-element.component.html new file mode 100644 index 0000000000..782c5f9e56 --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-list-element.component.html @@ -0,0 +1,6 @@ + + + + diff --git a/src/app/shared/object-list/my-dspace-result-list-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-list-element.component.spec.ts b/src/app/shared/object-list/my-dspace-result-list-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-list-element.component.spec.ts new file mode 100644 index 0000000000..2bcd4d46b0 --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-list-element.component.spec.ts @@ -0,0 +1,86 @@ +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; + +import { of as observableOf } from 'rxjs'; + +import { Item } from '../../../../core/shared/item.model'; +import { WorkflowitemMyDSpaceResultListElementComponent } from './workflowitem-my-dspace-result-list-element.component'; +import { WorkflowitemMyDSpaceResult } from '../../../object-collection/shared/workflowitem-my-dspace-result.model'; +import { Workflowitem } from '../../../../core/submission/models/workflowitem.model'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; + +let component: WorkflowitemMyDSpaceResultListElementComponent; +let fixture: ComponentFixture; + +const compIndex = 1; + +const mockResultObject: WorkflowitemMyDSpaceResult = new WorkflowitemMyDSpaceResult(); +mockResultObject.hitHighlights = {}; + +const item = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ], + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); +const rd = new RemoteData(false, false, true, null, item); +mockResultObject.indexableObject = Object.assign(new Workflowitem(), { item: observableOf(rd) }); + +describe('WorkflowitemMyDSpaceResultListElementComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [NoopAnimationsModule], + declarations: [WorkflowitemMyDSpaceResultListElementComponent], + providers: [ + { provide: 'objectElementProvider', useValue: (mockResultObject) }, + { provide: 'indexElementProvider', useValue: (compIndex) } + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(WorkflowitemMyDSpaceResultListElementComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(async(() => { + fixture = TestBed.createComponent(WorkflowitemMyDSpaceResultListElementComponent); + component = fixture.componentInstance; + })); + + beforeEach(() => { + component.dso = mockResultObject.indexableObject; + fixture.detectChanges(); + }); + + it('should init item properly', () => { + expect(component.item).toEqual(item); + }); + + it('should have properly status', () => { + expect(component.status).toEqual(MyDspaceItemStatusType.WORKFLOW); + }); +}); diff --git a/src/app/shared/object-list/my-dspace-result-list-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-list-element.component.ts b/src/app/shared/object-list/my-dspace-result-list-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-list-element.component.ts new file mode 100644 index 0000000000..9a5038225c --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/workflowitem-my-dspace-result/workflowitem-my-dspace-result-list-element.component.ts @@ -0,0 +1,58 @@ +import { Component } from '@angular/core'; + +import { Observable } from 'rxjs'; +import { find } from 'rxjs/operators'; + +import { renderElementsFor } from '../../../object-collection/shared/dso-element-decorator'; +import { MyDSpaceResultListElementComponent, } from '../my-dspace-result-list-element.component'; +import { ViewMode } from '../../../../core/shared/view-mode.model'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { isNotUndefined } from '../../../empty.util'; +import { WorkflowitemMyDSpaceResult } from '../../../object-collection/shared/workflowitem-my-dspace-result.model'; +import { Workflowitem } from '../../../../core/submission/models/workflowitem.model'; +import { Item } from '../../../../core/shared/item.model'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { SetViewMode } from '../../../view-mode'; + +/** + * This component renders workflowitem object for the mydspace result in the list view. + */ +@Component({ + selector: 'ds-workflowitem-my-dspace-result-list-element', + styleUrls: ['../my-dspace-result-list-element.component.scss'], + templateUrl: './workflowitem-my-dspace-result-list-element.component.html', +}) + +@renderElementsFor(WorkflowitemMyDSpaceResult, SetViewMode.List) +@renderElementsFor(Workflowitem, SetViewMode.List) +export class WorkflowitemMyDSpaceResultListElementComponent extends MyDSpaceResultListElementComponent { + + /** + * The item object that belonging to the result object + */ + public item: Item; + + /** + * Represent item's status + */ + public status = MyDspaceItemStatusType.WORKFLOW; + + /** + * Initialize all instance variables + */ + ngOnInit() { + this.initItem(this.dso.item as Observable>); + } + + /** + * Retrieve item from result object + */ + initItem(item$: Observable>) { + item$.pipe( + find((rd: RemoteData) => rd.hasSucceeded && isNotUndefined(rd.payload)) + ).subscribe((rd: RemoteData) => { + this.item = rd.payload; + }); + } + +} diff --git a/src/app/shared/object-list/my-dspace-result-list-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-list-element.component.html b/src/app/shared/object-list/my-dspace-result-list-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-list-element.component.html new file mode 100644 index 0000000000..79a31770d6 --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-list-element.component.html @@ -0,0 +1,7 @@ + + + diff --git a/src/app/shared/object-list/my-dspace-result-list-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-list-element.component.scss b/src/app/shared/object-list/my-dspace-result-list-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-list-element.component.scss new file mode 100644 index 0000000000..a32ecc6925 --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-list-element.component.scss @@ -0,0 +1,20 @@ +@import '../../../../../styles/variables'; + +::-webkit-scrollbar-track +{ + -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3); + background-color: #F5F5F5; +} + +::-webkit-scrollbar +{ + width: 12px; + background-color: #F5F5F5; +} + +::-webkit-scrollbar-thumb +{ + -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3); + background-color: #555; +} + diff --git a/src/app/shared/object-list/my-dspace-result-list-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-list-element.component.spec.ts b/src/app/shared/object-list/my-dspace-result-list-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-list-element.component.spec.ts new file mode 100644 index 0000000000..789b69da1b --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-list-element.component.spec.ts @@ -0,0 +1,86 @@ +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; + +import { of as observableOf } from 'rxjs'; + +import { Item } from '../../../../core/shared/item.model'; +import { WorkspaceitemMyDSpaceResultListElementComponent } from './workspaceitem-my-dspace-result-list-element.component'; +import { WorkspaceitemMyDSpaceResult } from '../../../object-collection/shared/workspaceitem-my-dspace-result.model'; +import { Workspaceitem } from '../../../../core/submission/models/workspaceitem.model'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; + +let component: WorkspaceitemMyDSpaceResultListElementComponent; +let fixture: ComponentFixture; + +const compIndex = 1; + +const mockResultObject: WorkspaceitemMyDSpaceResult = new WorkspaceitemMyDSpaceResult(); +mockResultObject.hitHighlights = {}; + +const item = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ], + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); +const rd = new RemoteData(false, false, true, null, item); +mockResultObject.indexableObject = Object.assign(new Workspaceitem(), { item: observableOf(rd) }); + +describe('WorkspaceitemMyDSpaceResultListElementComponent', () => { + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [NoopAnimationsModule], + declarations: [WorkspaceitemMyDSpaceResultListElementComponent], + providers: [ + { provide: 'objectElementProvider', useValue: (mockResultObject) }, + { provide: 'indexElementProvider', useValue: (compIndex) } + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(WorkspaceitemMyDSpaceResultListElementComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); + + beforeEach(async(() => { + fixture = TestBed.createComponent(WorkspaceitemMyDSpaceResultListElementComponent); + component = fixture.componentInstance; + })); + + beforeEach(() => { + component.dso = mockResultObject.indexableObject; + fixture.detectChanges(); + }); + + it('should init item properly', () => { + expect(component.item).toEqual(item); + }); + + it('should have properly status', () => { + expect(component.status).toEqual(MyDspaceItemStatusType.WORKSPACE); + }); +}); diff --git a/src/app/shared/object-list/my-dspace-result-list-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-list-element.component.ts b/src/app/shared/object-list/my-dspace-result-list-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-list-element.component.ts new file mode 100644 index 0000000000..9ea647b4ba --- /dev/null +++ b/src/app/shared/object-list/my-dspace-result-list-element/workspaceitem-my-dspace-result/workspaceitem-my-dspace-result-list-element.component.ts @@ -0,0 +1,56 @@ +import { Component } from '@angular/core'; + +import { Observable } from 'rxjs'; +import { find } from 'rxjs/operators'; + +import { renderElementsFor } from '../../../object-collection/shared/dso-element-decorator'; +import { MyDSpaceResultListElementComponent, } from '../my-dspace-result-list-element.component'; +import { ViewMode } from '../../../../core/shared/view-mode.model'; +import { Workspaceitem } from '../../../../core/submission/models/workspaceitem.model'; +import { WorkspaceitemMyDSpaceResult } from '../../../object-collection/shared/workspaceitem-my-dspace-result.model'; +import { RemoteData } from '../../../../core/data/remote-data'; +import { isNotUndefined } from '../../../empty.util'; +import { Item } from '../../../../core/shared/item.model'; +import { MyDspaceItemStatusType } from '../../../object-collection/shared/mydspace-item-status/my-dspace-item-status-type'; +import { SetViewMode } from '../../../view-mode'; + +/** + * This component renders workspaceitem object for the mydspace result in the list view. + */ +@Component({ + selector: 'ds-workspaceitem-my-dspace-result-list-element', + styleUrls: ['../my-dspace-result-list-element.component.scss', './workspaceitem-my-dspace-result-list-element.component.scss'], + templateUrl: './workspaceitem-my-dspace-result-list-element.component.html', +}) + +@renderElementsFor(WorkspaceitemMyDSpaceResult, SetViewMode.List) +export class WorkspaceitemMyDSpaceResultListElementComponent extends MyDSpaceResultListElementComponent { + + /** + * The item object that belonging to the result object + */ + item: Item; + + /** + * Represent item's status + */ + status = MyDspaceItemStatusType.WORKSPACE; + + /** + * Initialize all instance variables + */ + ngOnInit() { + this.initItem(this.dso.item as Observable>); + } + + /** + * Retrieve item from result object + */ + initItem(item$: Observable>) { + item$.pipe( + find((rd: RemoteData) => rd.hasSucceeded && isNotUndefined(rd.payload)) + ).subscribe((rd: RemoteData) => { + this.item = rd.payload; + }); + } +} diff --git a/src/app/shared/object-list/object-list.component.html b/src/app/shared/object-list/object-list.component.html index 420886668a..1fdc06d5bf 100644 --- a/src/app/shared/object-list/object-list.component.html +++ b/src/app/shared/object-list/object-list.component.html @@ -11,8 +11,8 @@ (sortFieldChange)="onSortFieldChange($event)" (paginationChange)="onPaginationChange($event)"> - - + + diff --git a/src/app/shared/object-list/object-list.component.spec.ts b/src/app/shared/object-list/object-list.component.spec.ts index 7e0b704a19..12ad032e98 100644 --- a/src/app/shared/object-list/object-list.component.spec.ts +++ b/src/app/shared/object-list/object-list.component.spec.ts @@ -6,7 +6,7 @@ import { By } from '@angular/platform-browser'; describe('ObjectListComponent', () => { let comp: ObjectListComponent; let fixture: ComponentFixture; - const testEvent = {test: 'test'} + const testEvent = {test: 'test'}; beforeEach(async(() => { TestBed.configureTestingModule({ diff --git a/src/app/shared/object-list/object-list.component.ts b/src/app/shared/object-list/object-list.component.ts index b0296d5ae1..afc376034f 100644 --- a/src/app/shared/object-list/object-list.component.ts +++ b/src/app/shared/object-list/object-list.component.ts @@ -25,6 +25,7 @@ export class ObjectListComponent { @Input() config: PaginationComponentOptions; @Input() sortConfig: SortOptions; + @Input() hasBorder = false; @Input() hideGear = false; @Input() hidePagerWhenSinglePage = true; private _objects: RemoteData>; diff --git a/src/app/shared/object-list/search-result-list-element/collection-search-result/collection-search-result-list-element.component.spec.ts b/src/app/shared/object-list/search-result-list-element/collection-search-result/collection-search-result-list-element.component.spec.ts index e897071a00..7f5aaf5d9c 100644 --- a/src/app/shared/object-list/search-result-list-element/collection-search-result/collection-search-result-list-element.component.spec.ts +++ b/src/app/shared/object-list/search-result-list-element/collection-search-result/collection-search-result-list-element.component.spec.ts @@ -17,7 +17,7 @@ const truncatableServiceStub: any = { const mockCollectionWithAbstract: CollectionSearchResult = new CollectionSearchResult(); mockCollectionWithAbstract.hitHighlights = {}; -mockCollectionWithAbstract.dspaceObject = Object.assign(new Collection(), { +mockCollectionWithAbstract.indexableObject = Object.assign(new Collection(), { metadata: { 'dc.description.abstract': [ { @@ -30,7 +30,7 @@ mockCollectionWithAbstract.dspaceObject = Object.assign(new Collection(), { const mockCollectionWithoutAbstract: CollectionSearchResult = new CollectionSearchResult(); mockCollectionWithoutAbstract.hitHighlights = {}; -mockCollectionWithoutAbstract.dspaceObject = Object.assign(new Collection(), { +mockCollectionWithoutAbstract.indexableObject = Object.assign(new Collection(), { metadata: { 'dc.title': [ { @@ -63,7 +63,7 @@ describe('CollectionSearchResultListElementComponent', () => { describe('When the collection has an abstract', () => { beforeEach(() => { - collectionSearchResultListElementComponent.dso = mockCollectionWithAbstract.dspaceObject; + collectionSearchResultListElementComponent.dso = mockCollectionWithAbstract.indexableObject; fixture.detectChanges(); }); @@ -75,7 +75,7 @@ describe('CollectionSearchResultListElementComponent', () => { describe('When the collection has no abstract', () => { beforeEach(() => { - collectionSearchResultListElementComponent.dso = mockCollectionWithoutAbstract.dspaceObject; + collectionSearchResultListElementComponent.dso = mockCollectionWithoutAbstract.indexableObject; fixture.detectChanges(); }); diff --git a/src/app/shared/object-list/search-result-list-element/community-search-result/community-search-result-list-element.component.spec.ts b/src/app/shared/object-list/search-result-list-element/community-search-result/community-search-result-list-element.component.spec.ts index 75d5966767..691a69dde4 100644 --- a/src/app/shared/object-list/search-result-list-element/community-search-result/community-search-result-list-element.component.spec.ts +++ b/src/app/shared/object-list/search-result-list-element/community-search-result/community-search-result-list-element.component.spec.ts @@ -17,7 +17,7 @@ const truncatableServiceStub: any = { const mockCommunityWithAbstract: CommunitySearchResult = new CommunitySearchResult(); mockCommunityWithAbstract.hitHighlights = {}; -mockCommunityWithAbstract.dspaceObject = Object.assign(new Community(), { +mockCommunityWithAbstract.indexableObject = Object.assign(new Community(), { metadata: { 'dc.description.abstract': [ { @@ -30,7 +30,7 @@ mockCommunityWithAbstract.dspaceObject = Object.assign(new Community(), { const mockCommunityWithoutAbstract: CommunitySearchResult = new CommunitySearchResult(); mockCommunityWithoutAbstract.hitHighlights = {}; -mockCommunityWithoutAbstract.dspaceObject = Object.assign(new Community(), { +mockCommunityWithoutAbstract.indexableObject = Object.assign(new Community(), { metadata: { 'dc.title': [ { @@ -63,7 +63,7 @@ describe('CommunitySearchResultListElementComponent', () => { describe('When the community has an abstract', () => { beforeEach(() => { - communitySearchResultListElementComponent.dso = mockCommunityWithAbstract.dspaceObject; + communitySearchResultListElementComponent.dso = mockCommunityWithAbstract.indexableObject; fixture.detectChanges(); }); @@ -75,7 +75,7 @@ describe('CommunitySearchResultListElementComponent', () => { describe('When the community has no abstract', () => { beforeEach(() => { - communitySearchResultListElementComponent.dso = mockCommunityWithoutAbstract.dspaceObject; + communitySearchResultListElementComponent.dso = mockCommunityWithoutAbstract.indexableObject; fixture.detectChanges(); }); diff --git a/src/app/shared/object-list/search-result-list-element/item-search-result/item-search-result-list-element.component.html b/src/app/shared/object-list/search-result-list-element/item-search-result/item-search-result-list-element.component.html index 74aeeeeda7..a2617a956f 100644 --- a/src/app/shared/object-list/search-result-list-element/item-search-result/item-search-result-list-element.component.html +++ b/src/app/shared/object-list/search-result-list-element/item-search-result/item-search-result-list-element.component.html @@ -1,4 +1,4 @@ - + {{ type.toLowerCase() + '.listelement.badge' | translate }} diff --git a/src/app/shared/object-list/search-result-list-element/item-search-result/item-search-result-list-element.component.spec.ts b/src/app/shared/object-list/search-result-list-element/item-search-result/item-search-result-list-element.component.spec.ts index d25effefe4..8bbb621312 100644 --- a/src/app/shared/object-list/search-result-list-element/item-search-result/item-search-result-list-element.component.spec.ts +++ b/src/app/shared/object-list/search-result-list-element/item-search-result/item-search-result-list-element.component.spec.ts @@ -1,92 +1,126 @@ -import { TranslateModule } from '@ngx-translate/core'; -import { Item } from '../../../../core/shared/item.model'; -import { of as observableOf } from 'rxjs'; -import { RemoteData } from '../../../../core/data/remote-data'; -import { PaginatedList } from '../../../../core/data/paginated-list'; -import { PageInfo } from '../../../../core/shared/page-info.model'; -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; -import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; import { ItemSearchResultListElementComponent } from './item-search-result-list-element.component'; +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { of as observableOf } from 'rxjs'; +import { ChangeDetectionStrategy, NO_ERRORS_SCHEMA } from '@angular/core'; import { By } from '@angular/platform-browser'; -import { TruncatableService } from '../../../truncatable/truncatable.service'; import { TruncatePipe } from '../../../utils/truncate.pipe'; -import { createRelationshipsObservable } from '../../../../+item-page/simple/item-types/shared/item.component.spec'; +import { Item } from '../../../../core/shared/item.model'; +import { TruncatableService } from '../../../truncatable/truncatable.service'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { ItemSearchResult } from '../../../object-collection/shared/item-search-result.model'; -import { MetadataMap } from '../../../../core/shared/metadata.models'; -const mockItem: Item = Object.assign(new Item(), { - bitstreams: observableOf(new RemoteData(false, false, true, null, new PaginatedList(new PageInfo(), []))), - metadata: new MetadataMap(), - relationships: createRelationshipsObservable() +let itemSearchResultListElementComponent: ItemSearchResultListElementComponent; +let fixture: ComponentFixture; + +const truncatableServiceStub: any = { + isCollapsed: (id: number) => observableOf(true), +}; + +const mockItemWithAuthorAndDate: ItemSearchResult = new ItemSearchResult(); +mockItemWithAuthorAndDate.hitHighlights = {}; +mockItemWithAuthorAndDate.indexableObject = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.contributor.author': [ + { + language: 'en_US', + value: 'Smith, Donald' + } + ], + 'dc.date.issued': [ + { + language: null, + value: '2015-06-26' + } + ] + } +}); + +const mockItemWithoutAuthorAndDate: ItemSearchResult = new ItemSearchResult(); +mockItemWithoutAuthorAndDate.hitHighlights = {}; +mockItemWithoutAuthorAndDate.indexableObject = Object.assign(new Item(), { + bitstreams: observableOf({}), + metadata: { + 'dc.title': [ + { + language: 'en_US', + value: 'This is just another title' + } + ], + 'dc.type': [ + { + language: null, + value: 'Article' + } + ] + } }); describe('ItemSearchResultListElementComponent', () => { - let comp: ItemSearchResultListElementComponent; - let fixture: ComponentFixture; + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [NoopAnimationsModule], + declarations: [ItemSearchResultListElementComponent, TruncatePipe], + providers: [ + { provide: TruncatableService, useValue: truncatableServiceStub }, + { provide: 'objectElementProvider', useValue: (mockItemWithoutAuthorAndDate) } + ], + schemas: [NO_ERRORS_SCHEMA] + }).overrideComponent(ItemSearchResultListElementComponent, { + set: { changeDetection: ChangeDetectionStrategy.Default } + }).compileComponents(); + })); - const truncatableServiceStub: any = { - isCollapsed: (id: number) => observableOf(true), - }; + beforeEach(async(() => { + fixture = TestBed.createComponent(ItemSearchResultListElementComponent); + itemSearchResultListElementComponent = fixture.componentInstance; + })); - const mockItemWithAuthorAndDate: ItemSearchResult = new ItemSearchResult(); - mockItemWithAuthorAndDate.hitHighlights = new MetadataMap(); - mockItemWithAuthorAndDate.dspaceObject = Object.assign(new Item(), { - bitstreams: observableOf({}), - metadata: [ - { - key: 'dc.contributor.author', - language: 'en_US', - value: 'Smith, Donald' - }, - { - key: 'dc.date.issued', - language: null, - value: '2015-06-26' - }] - }); - - const mockItemWithoutAuthorAndDate: ItemSearchResult = new ItemSearchResult(); - mockItemWithoutAuthorAndDate.hitHighlights = new MetadataMap(); - mockItemWithoutAuthorAndDate.dspaceObject = Object.assign(new Item(), { - bitstreams: observableOf({}), - metadata: [ - { - key: 'dc.title', - language: 'en_US', - value: 'This is just another title' - }, - { - key: 'dc.type', - language: null, - value: 'Article' - }] - }); - - describe('ItemSearchResultListElementComponent', () => { - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [TranslateModule.forRoot()], - declarations: [ItemSearchResultListElementComponent, TruncatePipe], - providers: [ - { provide: TruncatableService, useValue: {} }, - { provide: 'objectElementProvider', useValue: mockItem } - ], - schemas: [NO_ERRORS_SCHEMA] - }).overrideComponent(ItemSearchResultListElementComponent, { - set: { changeDetection: ChangeDetectionStrategy.Default } - }).compileComponents(); - })); - - beforeEach(async(() => { - fixture = TestBed.createComponent(ItemSearchResultListElementComponent); - comp = fixture.componentInstance; + describe('When the item has an author', () => { + beforeEach(() => { + itemSearchResultListElementComponent.dso = mockItemWithAuthorAndDate.indexableObject; fixture.detectChanges(); - })); - - it('should call an item-type-switcher component and pass the item', () => { - const itemTypeSwitcher = fixture.debugElement.query(By.css('ds-item-type-switcher')).componentInstance; - expect(itemTypeSwitcher.object).toBe(mockItem); }); + it('should show the author paragraph', () => { + const itemAuthorField = fixture.debugElement.query(By.css('span.item-list-authors')); + expect(itemAuthorField).not.toBeNull(); + }); + }); + + describe('When the item has no author', () => { + beforeEach(() => { + itemSearchResultListElementComponent.dso = mockItemWithoutAuthorAndDate.indexableObject; + fixture.detectChanges(); + }); + + it('should not show the author paragraph', () => { + const itemAuthorField = fixture.debugElement.query(By.css('span.item-list-authors')); + expect(itemAuthorField).toBeNull(); + }); + }); + + describe('When the item has an issuedate', () => { + beforeEach(() => { + itemSearchResultListElementComponent.dso = mockItemWithAuthorAndDate.indexableObject; + fixture.detectChanges(); + }); + + it('should show the issuedate span', () => { + const itemAuthorField = fixture.debugElement.query(By.css('span.item-list-date')); + expect(itemAuthorField).not.toBeNull(); + }); + }); + + describe('When the item has no issuedate', () => { + beforeEach(() => { + itemSearchResultListElementComponent.dso = mockItemWithoutAuthorAndDate.indexableObject; + fixture.detectChanges(); + }); + + it('should not show the issuedate span', () => { + const dateField = fixture.debugElement.query(By.css('span.item-list-date')); + expect(dateField).toBeNull(); + }); }); }); diff --git a/src/app/shared/object-list/search-result-list-element/search-result-list-element.component.ts b/src/app/shared/object-list/search-result-list-element/search-result-list-element.component.ts index 0836fc27e8..227d375f2a 100644 --- a/src/app/shared/object-list/search-result-list-element/search-result-list-element.component.ts +++ b/src/app/shared/object-list/search-result-list-element/search-result-list-element.component.ts @@ -20,7 +20,7 @@ export class SearchResultListElementComponent, K exten public constructor(@Inject('objectElementProvider') public listable: ListableObject, protected truncatableService: TruncatableService) { super(listable); if (hasValue(this.object)) { - this.dso = this.object.dspaceObject; + this.dso = this.object.indexableObject; } } diff --git a/src/app/shared/object-list/wrapper-list-element/wrapper-list-element.component.ts b/src/app/shared/object-list/wrapper-list-element/wrapper-list-element.component.ts index c8d3316983..17e6f0fd85 100644 --- a/src/app/shared/object-list/wrapper-list-element/wrapper-list-element.component.ts +++ b/src/app/shared/object-list/wrapper-list-element/wrapper-list-element.component.ts @@ -11,13 +11,17 @@ import { ListableObject } from '../../object-collection/shared/listable-object.m }) export class WrapperListElementComponent implements OnInit { @Input() object: ListableObject; + @Input() index: number; objectInjector: Injector; constructor(private injector: Injector) {} ngOnInit(): void { this.objectInjector = Injector.create({ - providers: [{ provide: 'objectElementProvider', useFactory: () => (this.object), deps:[] }], + providers: [ + { provide: 'objectElementProvider', useFactory: () => (this.object), deps:[] }, + { provide: 'indexElementProvider', useFactory: () => (this.index), deps:[] } + ], parent: this.injector }); } diff --git a/src/app/shared/pagination/pagination-component-options.model.ts b/src/app/shared/pagination/pagination-component-options.model.ts index 30ed2becd2..4f8a3c5c8c 100644 --- a/src/app/shared/pagination/pagination-component-options.model.ts +++ b/src/app/shared/pagination/pagination-component-options.model.ts @@ -12,11 +12,19 @@ export class PaginationComponentOptions extends NgbPaginationConfig { */ currentPage = 1; + /** + * Maximum number of pages to display. + */ + maxSize = 10; + /** * A number array that represents options for a context pagination limit. */ - pageSizeOptions: number[] = [5, 10, 20, 40, 60, 80, 100]; + pageSizeOptions: number[] = [1, 5, 10, 20, 40, 60, 80, 100]; + /** + * Number of items per page. + */ pageSize: number; } diff --git a/src/app/shared/pagination/pagination.component.html b/src/app/shared/pagination/pagination.component.html index 7336866e5c..22a58dd7fc 100644 --- a/src/app/shared/pagination/pagination.component.html +++ b/src/app/shared/pagination/pagination.component.html @@ -1,7 +1,7 @@ - + {{ 'pagination.showing.label' | translate }} {{ 'pagination.showing.detail' | translate:getShowingDetails(collectionSize)}} diff --git a/src/app/shared/pagination/pagination.component.spec.ts b/src/app/shared/pagination/pagination.component.spec.ts index 7b340b2eed..dfbef9123a 100644 --- a/src/app/shared/pagination/pagination.component.spec.ts +++ b/src/app/shared/pagination/pagination.component.spec.ts @@ -262,7 +262,7 @@ describe('Pagination component', () => { changePage(testFixture, 3); tick(); - expect(routerStub.navigate).toHaveBeenCalledWith([], { queryParams: { pageId: 'test', page: 3, pageSize: 10, sortDirection: 'ASC', sortField: 'dc.title' }, queryParamsHandling: 'merge' }); + expect(routerStub.navigate).toHaveBeenCalledWith([], { queryParams: { pageId: 'test', page: '3', pageSize: 10, sortDirection: 'ASC', sortField: 'dc.title' }, queryParamsHandling: 'merge' }); })); diff --git a/src/app/shared/pagination/pagination.component.ts b/src/app/shared/pagination/pagination.component.ts index 0f2907a7bf..e5cb1f448a 100644 --- a/src/app/shared/pagination/pagination.component.ts +++ b/src/app/shared/pagination/pagination.component.ts @@ -8,16 +8,19 @@ import { Output, ViewEncapsulation } from '@angular/core' - import { ActivatedRoute, Router } from '@angular/router'; import { Subscription, Observable } from 'rxjs'; +import { isNumeric } from 'rxjs/internal-compatibility'; +import { isEqual, isObject, transform } from 'lodash'; + import { HostWindowService } from '../host-window.service'; import { HostWindowState } from '../host-window.reducer'; import { PaginationComponentOptions } from './pagination-component-options.model'; import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model'; import { hasValue, isNotEmpty } from '../empty.util'; import { PageInfo } from '../../core/shared/page-info.model'; +import { difference } from '../object.util'; /** * The default pagination controls component. @@ -76,11 +79,16 @@ export class PaginationComponent implements OnDestroy, OnInit { @Output() sortFieldChange: EventEmitter = new EventEmitter(); /** - * An event fired when the sort field is changed. + * An event fired when the pagination is changed. * Event's payload equals to the newly selected sort field. */ @Output() paginationChange: EventEmitter = new EventEmitter(); + /** + * Option for hiding the pagination detail + */ + @Input() public hidePaginationDetail = false; + /** * Option for hiding the gear */ @@ -168,7 +176,7 @@ export class PaginationComponent implements OnDestroy, OnInit { this.subs.push(this.route.queryParams .subscribe((queryParams) => { if (this.isEmptyPaginationParams(queryParams)) { - this.initializeConfig(); + this.initializeConfig(queryParams); } else { this.currentQueryParams = queryParams; const fixedProperties = this.validateParams(queryParams); @@ -197,7 +205,7 @@ export class PaginationComponent implements OnDestroy, OnInit { /** * Initializes all default variables */ - private initializeConfig() { + private initializeConfig(queryParams: any = {}) { // Set initial values this.id = this.paginationOptions.id || null; this.pageSizeOptions = this.paginationOptions.pageSizeOptions; @@ -207,13 +215,13 @@ export class PaginationComponent implements OnDestroy, OnInit { this.sortDirection = this.sortOptions.direction; this.sortField = this.sortOptions.field; } - this.currentQueryParams = { + this.currentQueryParams = Object.assign({}, queryParams, { pageId: this.id, page: this.currentPage, pageSize: this.pageSize, sortDirection: this.sortDirection, sortField: this.sortField - }; + }); } /** @@ -235,7 +243,7 @@ export class PaginationComponent implements OnDestroy, OnInit { * The page being navigated to. */ public doPageChange(page: number) { - this.updateRoute({ page: page }); + this.updateRoute({ page: page.toString() }); } /** @@ -333,10 +341,23 @@ export class PaginationComponent implements OnDestroy, OnInit { * Method to update the route parameters */ private updateRoute(params: {}) { - this.router.navigate([], { - queryParams: Object.assign({}, this.currentQueryParams, params), - queryParamsHandling: 'merge' - }); + if (isNotEmpty(difference(params, this.currentQueryParams))) { + this.router.navigate([], { + queryParams: Object.assign({}, this.currentQueryParams, params), + queryParamsHandling: 'merge' + }); + } + } + + private difference(object, base) { + const changes = (o, b) => { + return transform(o, (result, value, key) => { + if (!isEqual(value, b[key]) && isNotEmpty(value)) { + result[key] = (isObject(value) && isObject(b[key])) ? changes(value, b[key]) : value; + } + }); + }; + return changes(object, base); } /** @@ -418,7 +439,7 @@ export class PaginationComponent implements OnDestroy, OnInit { */ private validatePage(page: any): number { let result = this.currentPage; - if (!isNaN(page)) { + if (isNumeric(page)) { result = +page; } return result; diff --git a/src/app/shared/roles/role.directive.ts b/src/app/shared/roles/role.directive.ts new file mode 100644 index 0000000000..d71e520e35 --- /dev/null +++ b/src/app/shared/roles/role.directive.ts @@ -0,0 +1,114 @@ +import { + ChangeDetectorRef, + Directive, + Input, + OnChanges, + OnDestroy, + SimpleChanges, + TemplateRef, + ViewContainerRef +} from '@angular/core'; + +import { combineLatest, Observable, Subscription } from 'rxjs'; +import { filter, first, map } from 'rxjs/operators'; + +import { hasValue } from '../empty.util'; +import { RoleService } from '../../core/roles/role.service'; +import { RoleType } from '../../core/roles/role-types'; + +@Directive({ + selector: '[dsShowOnlyForRole],[dsShowExceptForRole]' +}) +/** + * Structural Directive for showing or hiding a template based on current user role + */ +export class RoleDirective implements OnChanges, OnDestroy { + + /** + * The role or list of roles that can show template + */ + @Input() dsShowOnlyForRole: RoleType | RoleType[]; + + /** + * The role or list of roles that cannot show template + */ + @Input() dsShowExceptForRole: RoleType | RoleType[]; + + private subs: Subscription[] = []; + + constructor( + private roleService: RoleService, + private viewContainer: ViewContainerRef, + private changeDetector: ChangeDetectorRef, + private templateRef: TemplateRef + ) { + } + + ngOnChanges(changes: SimpleChanges): void { + const onlyChanges = changes.dsShowOnlyForRole; + const exceptChanges = changes.dsShowExceptForRole; + this.hasRoles(this.dsShowOnlyForRole); + if (changes.dsShowOnlyForRole) { + this.validateOnly() + } else if (changes.dsShowExceptForRole) { + this.validateExcept() + } + } + + ngOnDestroy(): void { + this.subs + .filter((subscription) => hasValue(subscription)) + .forEach((subscription) => subscription.unsubscribe()); + } + + /** + * Show template in view container + */ + private showTemplateBlockInView(): void { + this.viewContainer.clear(); + if (!this.templateRef) { + return; + } + + this.viewContainer.createEmbeddedView(this.templateRef); + this.changeDetector.markForCheck(); + } + + /** + * Validate the list of roles that can show template + */ + private validateOnly(): void { + this.subs.push(this.hasRoles(this.dsShowOnlyForRole).pipe(filter((hasRole) => hasRole)) + .subscribe((hasRole) => { + this.showTemplateBlockInView(); + })); + } + + /** + * Validate the list of roles that cannot show template + */ + private validateExcept(): void { + this.subs.push(this.hasRoles(this.dsShowExceptForRole).pipe(filter((hasRole) => !hasRole)) + .subscribe((hasRole) => { + this.showTemplateBlockInView(); + })); + } + + /** + * Check if current user role is included in the specified role list + * + * @param roles + * The role or the list of roles + * @returns {Observable} + * observable of true if current user role is included in the specified role list, observable of false otherwise + */ + private hasRoles(roles: RoleType | RoleType[]): Observable { + const toValidate: RoleType[] = (Array.isArray(roles)) ? roles : [roles]; + const checks: Array> = toValidate.map((role) => this.roleService.checkRole(role)); + + return combineLatest(checks).pipe( + map((permissions: boolean[]) => permissions.includes(true)), + first() + ) + } +} diff --git a/src/app/shared/search-form/search-form.component.ts b/src/app/shared/search-form/search-form.component.ts index 21a90daed4..ea96bd8114 100644 --- a/src/app/shared/search-form/search-form.component.ts +++ b/src/app/shared/search-form/search-form.component.ts @@ -3,6 +3,7 @@ import { DSpaceObject } from '../../core/shared/dspace-object.model'; import { Router } from '@angular/router'; import { hasValue, isNotEmpty } from '../empty.util'; import { QueryParamsHandling } from '@angular/router/src/config'; +import { MYDSPACE_ROUTE } from '../../+my-dspace-page/my-dspace-page.component'; /** * This component renders a simple item page. @@ -64,7 +65,7 @@ export class SearchFormComponent { updateSearch(data: any) { const newUrl = hasValue(this.currentUrl) ? this.currentUrl : '/search'; let handling: QueryParamsHandling = '' ; - if (this.currentUrl === '/search') { + if (this.currentUrl === '/search' || this.currentUrl === MYDSPACE_ROUTE) { handling = 'merge'; } this.router.navigate([newUrl], { diff --git a/src/app/shared/services/route.service.spec.ts b/src/app/shared/services/route.service.spec.ts index 7d249cb12a..c9b3710ee6 100644 --- a/src/app/shared/services/route.service.spec.ts +++ b/src/app/shared/services/route.service.spec.ts @@ -29,6 +29,9 @@ describe('RouteService', () => { select: jasmine.createSpy('select') }); + const router = new MockRouter(); + router.setParams(convertToParamMap(paramObject)); + paramObject[paramName1] = paramValue1; paramObject[paramName2] = [paramValue2a, paramValue2b]; @@ -42,7 +45,7 @@ describe('RouteService', () => { queryParamMap: observableOf(convertToParamMap(paramObject)) }, }, - { provide: Router, useValue: new MockRouter() }, + { provide: Router, useValue: router }, { provide: Store, useValue: store }, ] }); diff --git a/src/app/shared/services/route.service.ts b/src/app/shared/services/route.service.ts index 41dd37e59c..a5e6c5c47b 100644 --- a/src/app/shared/services/route.service.ts +++ b/src/app/shared/services/route.service.ts @@ -1,9 +1,10 @@ import { distinctUntilChanged, map, mergeMap, filter } from 'rxjs/operators'; import { Injectable } from '@angular/core'; -import { ActivatedRoute, NavigationEnd, Params, Router, } from '@angular/router'; +import { ActivatedRoute, NavigationEnd, Params, Router, RouterStateSnapshot, } from '@angular/router'; import { Observable } from 'rxjs'; import { select, Store } from '@ngrx/store'; +import { isEqual } from 'lodash'; import { AppState } from '../../app.reducer'; import { AddUrlToHistoryAction } from '../history/history.actions'; @@ -26,8 +27,8 @@ export class RouteService { * @param paramName The name of the parameter to look for */ getQueryParameterValues(paramName: string): Observable { - return this.route.queryParamMap.pipe( - map((paramMap) => [...paramMap.getAll(paramName)]), + return this.getQueryParamMap().pipe( + map((params) => [...params.getAll(paramName)]), distinctUntilChanged((a, b) => JSON.stringify(a) === JSON.stringify(b)) ); } @@ -37,8 +38,8 @@ export class RouteService { * @param paramName The name of the parameter to look for */ getQueryParameterValue(paramName: string): Observable { - return this.route.queryParamMap.pipe( - map((paramMap) => paramMap.get(paramName)), + return this.getQueryParamMap().pipe( + map((params) => params.get(paramName)), distinctUntilChanged() ); } @@ -48,8 +49,8 @@ export class RouteService { * @param paramName The name of the parameter to look for */ hasQueryParam(paramName: string): Observable { - return this.route.queryParamMap.pipe( - map((paramMap) => paramMap.has(paramName)), + return this.getQueryParamMap().pipe( + map((params) => params.has(paramName)), distinctUntilChanged() ); } @@ -60,8 +61,8 @@ export class RouteService { * @param paramValue The value of the parameter to look for */ hasQueryParamWithValue(paramName: string, paramValue: string): Observable { - return this.route.queryParamMap.pipe( - map((paramMap) => paramMap.getAll(paramName).indexOf(paramValue) > -1), + return this.getQueryParamMap().pipe( + map((params) => params.getAll(paramName).indexOf(paramValue) > -1), distinctUntilChanged() ); } @@ -79,13 +80,13 @@ export class RouteService { * @param prefix The prefix of the parameter name to look for */ getQueryParamsWithPrefix(prefix: string): Observable { - return this.route.queryParamMap.pipe( - map((paramMap) => { + return this.getQueryParamMap().pipe( + map((qparams) => { const params = {}; - paramMap.keys + qparams.keys .filter((key) => key.startsWith(prefix)) .forEach((key) => { - params[key] = [...paramMap.getAll(key)]; + params[key] = [...qparams.getAll(key)]; }); return params; }), @@ -93,6 +94,19 @@ export class RouteService { ); } + public getQueryParamMap(): Observable { + return this.route.queryParamMap.pipe( + map((paramMap) => { + const snapshot: RouterStateSnapshot = this.router.routerState.snapshot; + // Due to an Angular bug, sometimes change of QueryParam is not detected so double checks with route snapshot + if (!isEqual(paramMap, snapshot.root.queryParamMap)) { + return snapshot.root.queryParamMap; + } else { + return paramMap; + } + })) + } + public saveRouting(): void { this.router.events .pipe(filter((event) => event instanceof NavigationEnd)) diff --git a/src/app/shared/shared.module.ts b/src/app/shared/shared.module.ts index 329a588f43..4331b5e7e0 100644 --- a/src/app/shared/shared.module.ts +++ b/src/app/shared/shared.module.ts @@ -87,6 +87,20 @@ import { DsDatePickerComponent } from './form/builder/ds-dynamic-form-ui/models/ import { DsDynamicLookupComponent } from './form/builder/ds-dynamic-form-ui/models/lookup/dynamic-lookup.component'; import { MockAdminGuard } from './mocks/mock-admin-guard.service'; import { AlertComponent } from './alert/alert.component'; +import { MyDSpaceResultListElementComponent } from './object-list/my-dspace-result-list-element/my-dspace-result-list-element.component'; +import { MyDSpaceResultDetailElementComponent } from './object-detail/my-dspace-result-detail-element/my-dspace-result-detail-element.component'; +import { ClaimedTaskActionsComponent } from './mydspace-actions/claimed-task/claimed-task-actions.component'; +import { PoolTaskActionsComponent } from './mydspace-actions/pool-task/pool-task-actions.component'; +import { ObjectDetailComponent } from './object-detail/object-detail.component'; +import { WrapperDetailElementComponent } from './object-detail/wrapper-detail-element/wrapper-detail-element.component'; +import { ItemDetailPreviewComponent } from './object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview.component'; +import { MyDSpaceItemStatusComponent } from './object-collection/shared/mydspace-item-status/my-dspace-item-status.component'; +import { WorkspaceitemActionsComponent } from './mydspace-actions/workspaceitem/workspaceitem-actions.component'; +import { WorkflowitemActionsComponent } from './mydspace-actions/workflowitem/workflowitem-actions.component'; +import { ItemSubmitterComponent } from './object-collection/shared/mydspace-item-submitter/item-submitter.component'; +import { ItemActionsComponent } from './mydspace-actions/item/item-actions.component'; +import { ClaimedTaskActionsApproveComponent } from './mydspace-actions/claimed-task/approve/claimed-task-actions-approve.component'; +import { ClaimedTaskActionsRejectComponent } from './mydspace-actions/claimed-task/reject/claimed-task-actions-reject.component'; import { ObjNgFor } from './utils/object-ngfor.pipe'; import { BrowseByComponent } from './browse-by/browse-by.component'; import { BrowseEntryListElementComponent } from './object-list/browse-entry-list-element/browse-entry-list-element.component'; @@ -125,7 +139,13 @@ import { ItemSearchResultListElementComponent } from './object-list/search-resul import { EditItemSelectorComponent } from './dso-selector/modal-wrappers/edit-item-selector/edit-item-selector.component'; import { EditCommunitySelectorComponent } from './dso-selector/modal-wrappers/edit-community-selector/edit-community-selector.component'; import { EditCollectionSelectorComponent } from './dso-selector/modal-wrappers/edit-collection-selector/edit-collection-selector.component'; -import { DSOSelectorModalWrapperComponent } from './dso-selector/modal-wrappers/dso-selector-modal-wrapper.component'; +import { ItemListPreviewComponent } from './object-list/my-dspace-result-list-element/item-list-preview/item-list-preview.component'; +import { MetadataFieldWrapperComponent } from '../+item-page/field-components/metadata-field-wrapper/metadata-field-wrapper.component'; +import { MetadataValuesComponent } from '../+item-page/field-components/metadata-values/metadata-values.component'; +import { RoleDirective } from './roles/role.directive'; +import { UserMenuComponent } from './auth-nav-menu/user-menu/user-menu.component'; +import { ClaimedTaskActionsReturnToPoolComponent } from './mydspace-actions/claimed-task/return-to-pool/claimed-task-actions-return-to-pool.component'; +import { ItemDetailPreviewFieldComponent } from './object-detail/my-dspace-result-detail-element/item-detail-preview/item-detail-preview-field/item-detail-preview-field.component'; const MODULES = [ // Do NOT include UniversalModule, HttpModule, or JsonpModule here @@ -172,6 +192,7 @@ const COMPONENTS = [ // put shared components here AlertComponent, AuthNavMenuComponent, + UserMenuComponent, ChipsComponent, ComcolPageContentComponent, ComcolPageHeaderComponent, @@ -201,9 +222,11 @@ const COMPONENTS = [ LogOutComponent, NumberPickerComponent, ObjectListComponent, + ObjectDetailComponent, + ObjectGridComponent, AbstractListableElementComponent, WrapperListElementComponent, - ObjectGridComponent, + WrapperDetailElementComponent, WrapperGridElementComponent, ObjectCollectionComponent, PaginationComponent, @@ -212,6 +235,19 @@ const COMPONENTS = [ GridThumbnailComponent, UploaderComponent, WrapperListElementComponent, + ItemListPreviewComponent, + MyDSpaceItemStatusComponent, + ItemSubmitterComponent, + ItemDetailPreviewComponent, + ItemDetailPreviewFieldComponent, + ClaimedTaskActionsComponent, + ClaimedTaskActionsApproveComponent, + ClaimedTaskActionsRejectComponent, + ClaimedTaskActionsReturnToPoolComponent, + ItemActionsComponent, + PoolTaskActionsComponent, + WorkflowitemActionsComponent, + WorkspaceitemActionsComponent, ViewModeSwitchComponent, TruncatableComponent, TruncatablePartComponent, @@ -237,6 +273,7 @@ const ENTRY_COMPONENTS = [ ItemListElementComponent, CollectionListElementComponent, CommunityListElementComponent, + MyDSpaceResultListElementComponent, SearchResultListElementComponent, CommunitySearchResultListElementComponent, CollectionSearchResultListElementComponent, @@ -255,6 +292,8 @@ const ENTRY_COMPONENTS = [ JournalVolumeListElementComponent, JournalIssueListElementComponent, BrowseEntryListElementComponent, + MyDSpaceResultDetailElementComponent, + SearchResultGridElementComponent, DsDynamicListComponent, DsDynamicLookupComponent, DsDynamicScrollableDropdownComponent, @@ -280,6 +319,11 @@ const ENTRY_COMPONENTS = [ MetadataRepresentationListElementComponent ]; +const SHARED_ITEM_PAGE_COMPONENTS = [ + MetadataFieldWrapperComponent, + MetadataValuesComponent, +]; + const PROVIDERS = [ TruncatableService, MockAdminGuard, @@ -296,7 +340,8 @@ const DIRECTIVES = [ ClickOutsideDirective, AuthorityConfidenceStateDirective, InListValidator, - AutoFocusDirective + AutoFocusDirective, + RoleDirective ]; @NgModule({ @@ -309,6 +354,7 @@ const DIRECTIVES = [ ...COMPONENTS, ...DIRECTIVES, ...ENTRY_COMPONENTS, + ...SHARED_ITEM_PAGE_COMPONENTS ], providers: [ ...PROVIDERS @@ -317,6 +363,7 @@ const DIRECTIVES = [ ...MODULES, ...PIPES, ...COMPONENTS, + ...SHARED_ITEM_PAGE_COMPONENTS, ...DIRECTIVES ], entryComponents: [ diff --git a/src/app/shared/testing/eperson-mock.ts b/src/app/shared/testing/eperson-mock.ts index ef27f4983d..c822fc15d6 100644 --- a/src/app/shared/testing/eperson-mock.ts +++ b/src/app/shared/testing/eperson-mock.ts @@ -13,26 +13,30 @@ export const EPersonMock: EPerson = Object.assign(new EPerson(),{ id: 'testid', uuid: 'testid', type: 'eperson', - metadata: [ - { - key: 'dc.title', - language: null, - value: 'User Test' - }, - { - key: 'eperson.firstname', - language: null, - value: 'User' - }, - { - key: 'eperson.lastname', - language: null, - value: 'Test' - }, - { - key: 'eperson.language', - language: null, - value: 'en' - } - ] + metadata: { + 'dc.title': [ + { + language: null, + value: 'User Test' + } + ], + 'eperson.firstname': [ + { + language: null, + value: 'User' + } + ], + 'eperson.lastname': [ + { + language: null, + value: 'Test' + }, + ], + 'eperson.language': [ + { + language: null, + value: 'en' + }, + ] + } }); diff --git a/src/app/shared/testing/route-service-stub.ts b/src/app/shared/testing/route-service-stub.ts new file mode 100644 index 0000000000..e872d0703b --- /dev/null +++ b/src/app/shared/testing/route-service-stub.ts @@ -0,0 +1,26 @@ +import { of as observableOf } from 'rxjs/internal/observable/of'; + +export const routeServiceStub: any = { + /* tslint:disable:no-empty */ + hasQueryParamWithValue: (param: string, value: string) => { + }, + hasQueryParam: (param: string) => { + }, + removeQueryParameterValue: (param: string, value: string) => { + }, + addQueryParameterValue: (param: string, value: string) => { + }, + getQueryParameterValues: (param: string) => { + return observableOf({}); + }, + getQueryParamsWithPrefix: (param: string) => { + return observableOf({}); + }, + getQueryParamMap: () => { + return observableOf(new Map()) + }, + getQueryParameterValue: () => { + return observableOf({}) + } + /* tslint:enable:no-empty */ +}; diff --git a/src/app/shared/testing/router-stub.ts b/src/app/shared/testing/router-stub.ts index 7e0315698c..8630e16b2e 100644 --- a/src/app/shared/testing/router-stub.ts +++ b/src/app/shared/testing/router-stub.ts @@ -1,6 +1,7 @@ import { of as observableOf } from 'rxjs'; export class RouterStub { url: string; + routeReuseStrategy = {shouldReuseRoute: {}}; //noinspection TypeScriptUnresolvedFunction navigate = jasmine.createSpy('navigate'); parseUrl = jasmine.createSpy('parseUrl'); diff --git a/src/app/shared/testing/search-configuration-service-stub.ts b/src/app/shared/testing/search-configuration-service-stub.ts new file mode 100644 index 0000000000..4c9402afb1 --- /dev/null +++ b/src/app/shared/testing/search-configuration-service-stub.ts @@ -0,0 +1,19 @@ +import { BehaviorSubject, of as observableOf } from 'rxjs'; + +export class SearchConfigurationServiceStub { + + private searchOptions: BehaviorSubject = new BehaviorSubject({}); + private paginatedSearchOptions: BehaviorSubject
{{'submission.general.discard.confirm.info' | translate}}