[CST-5249] Added suggestions from openaire

This commit is contained in:
Luca Giamminonni
2022-03-29 16:16:22 +02:00
parent e75cb5f64a
commit 5d8d3e35d5
57 changed files with 5112 additions and 8 deletions

View File

@@ -0,0 +1,9 @@
import { URLCombiner } from '../../core/url-combiner/url-combiner';
import { getNotificationsModuleRoute } from '../admin-routing-paths';
export const NOTIFICATIONS_EDIT_PATH = 'openaire-broker';
export const NOTIFICATIONS_RECITER_SUGGESTION_PATH = 'suggestion-targets';
export function getNotificationsOpenairebrokerRoute(id: string) {
return new URLCombiner(getNotificationsModuleRoute(), NOTIFICATIONS_EDIT_PATH, id).toString();
}

View File

@@ -0,0 +1,42 @@
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { AuthenticatedGuard } from '../../core/auth/authenticated.guard';
import { I18nBreadcrumbResolver } from '../../core/breadcrumbs/i18n-breadcrumb.resolver';
import { I18nBreadcrumbsService } from '../../core/breadcrumbs/i18n-breadcrumbs.service';
import { NOTIFICATIONS_EDIT_PATH, NOTIFICATIONS_RECITER_SUGGESTION_PATH } from './admin-notifications-routing-paths';
import { AdminNotificationsSuggestionTargetsPageComponent } from './admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page.component';
import { AdminNotificationsSuggestionTargetsPageResolver } from './admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page-resolver.service';
@NgModule({
imports: [
RouterModule.forChild([
{
canActivate: [ AuthenticatedGuard ],
path: `${NOTIFICATIONS_RECITER_SUGGESTION_PATH}`,
component: AdminNotificationsSuggestionTargetsPageComponent,
pathMatch: 'full',
resolve: {
breadcrumb: I18nBreadcrumbResolver,
reciterSuggestionTargetParams: AdminNotificationsSuggestionTargetsPageResolver
},
data: {
title: 'admin.notifications.recitersuggestion.page.title',
breadcrumbKey: 'admin.notifications.recitersuggestion',
showBreadcrumbsFluid: false
}
},
])
],
providers: [
I18nBreadcrumbResolver,
I18nBreadcrumbsService,
AdminNotificationsSuggestionTargetsPageResolver
]
})
/**
* Routing module for the Notifications section of the admin sidebar
*/
export class AdminNotificationsRoutingModule {
}

View File

@@ -0,0 +1,32 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
/**
* Interface for the route parameters.
*/
export interface AdminNotificationsSuggestionTargetsPageParams {
pageId?: string;
pageSize?: number;
currentPage?: number;
}
/**
* This class represents a resolver that retrieve the route data before the route is activated.
*/
@Injectable()
export class AdminNotificationsSuggestionTargetsPageResolver implements Resolve<AdminNotificationsSuggestionTargetsPageParams> {
/**
* Method for resolving the parameters in the current route.
* @param {ActivatedRouteSnapshot} route The current ActivatedRouteSnapshot
* @param {RouterStateSnapshot} state The current RouterStateSnapshot
* @returns AdminNotificationsSuggestionTargetsPageParams Emits the route parameters
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): AdminNotificationsSuggestionTargetsPageParams {
return {
pageId: route.queryParams.pageId,
pageSize: parseInt(route.queryParams.pageSize, 10),
currentPage: parseInt(route.queryParams.page, 10)
};
}
}

View File

@@ -0,0 +1 @@
<ds-suggestion-target [source]="'oaire'"></ds-suggestion-target>

View File

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

View File

@@ -0,0 +1,10 @@
import { Component } from '@angular/core';
@Component({
selector: 'ds-admin-notifications-reciter-page',
templateUrl: './admin-notifications-suggestion-targets-page.component.html',
styleUrls: ['./admin-notifications-suggestion-targets-page.component.scss']
})
export class AdminNotificationsSuggestionTargetsPageComponent {
}

View File

@@ -0,0 +1,27 @@
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { CoreModule } from '../../core/core.module';
import { SharedModule } from '../../shared/shared.module';
import { AdminNotificationsRoutingModule } from './admin-notifications-routing.module';
import { OpenaireModule } from '../../openaire/openaire.module';
import { AdminNotificationsSuggestionTargetsPageComponent } from './admin-notifications-suggestion-targets-page/admin-notifications-suggestion-targets-page.component';
@NgModule({
imports: [
CommonModule,
SharedModule,
CoreModule.forRoot(),
AdminNotificationsRoutingModule,
OpenaireModule
],
declarations: [
AdminNotificationsSuggestionTargetsPageComponent
],
entryComponents: []
})
/**
* This module handles all components related to the notifications pages
*/
export class AdminNotificationsModule {
}

View File

@@ -2,7 +2,12 @@ import { URLCombiner } from '../core/url-combiner/url-combiner';
import { getAdminModuleRoute } from '../app-routing-paths'; import { getAdminModuleRoute } from '../app-routing-paths';
export const REGISTRIES_MODULE_PATH = 'registries'; export const REGISTRIES_MODULE_PATH = 'registries';
export const NOTIFICATIONS_MODULE_PATH = 'notifications';
export function getRegistriesModuleRoute() { export function getRegistriesModuleRoute() {
return new URLCombiner(getAdminModuleRoute(), REGISTRIES_MODULE_PATH).toString(); return new URLCombiner(getAdminModuleRoute(), REGISTRIES_MODULE_PATH).toString();
} }
export function getNotificationsModuleRoute() {
return new URLCombiner(getAdminModuleRoute(), NOTIFICATIONS_MODULE_PATH).toString();
}

View File

@@ -6,11 +6,16 @@ import { I18nBreadcrumbResolver } from '../core/breadcrumbs/i18n-breadcrumb.reso
import { AdminWorkflowPageComponent } from './admin-workflow-page/admin-workflow-page.component'; import { AdminWorkflowPageComponent } from './admin-workflow-page/admin-workflow-page.component';
import { I18nBreadcrumbsService } from '../core/breadcrumbs/i18n-breadcrumbs.service'; import { I18nBreadcrumbsService } from '../core/breadcrumbs/i18n-breadcrumbs.service';
import { AdminCurationTasksComponent } from './admin-curation-tasks/admin-curation-tasks.component'; import { AdminCurationTasksComponent } from './admin-curation-tasks/admin-curation-tasks.component';
import { REGISTRIES_MODULE_PATH } from './admin-routing-paths'; import { REGISTRIES_MODULE_PATH, NOTIFICATIONS_MODULE_PATH } from './admin-routing-paths';
@NgModule({ @NgModule({
imports: [ imports: [
RouterModule.forChild([ RouterModule.forChild([
{
path: NOTIFICATIONS_MODULE_PATH,
loadChildren: () => import('./admin-notifications/admin-notifications.module')
.then((m) => m.AdminNotificationsModule),
},
{ {
path: REGISTRIES_MODULE_PATH, path: REGISTRIES_MODULE_PATH,
loadChildren: () => import('./admin-registries/admin-registries.module') loadChildren: () => import('./admin-registries/admin-registries.module')

View File

@@ -22,6 +22,7 @@ import { CSSVariableService } from '../../shared/sass-helper/sass-helper.service
import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service'; import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service';
import { FeatureID } from '../../core/data/feature-authorization/feature-id'; import { FeatureID } from '../../core/data/feature-authorization/feature-id';
import { Router, ActivatedRoute } from '@angular/router'; import { Router, ActivatedRoute } from '@angular/router';
import {NOTIFICATIONS_RECITER_SUGGESTION_PATH} from "../admin-notifications/admin-notifications-routing-paths";
/** /**
* Component representing the admin sidebar * Component representing the admin sidebar
@@ -277,7 +278,7 @@ export class AdminSidebarComponent extends MenuComponent implements OnInit {
// link: '' // link: ''
// } as LinkMenuItemModel, // } as LinkMenuItemModel,
// icon: 'chart-bar', // icon: 'chart-bar',
// index: 8 // index: 9
// }, // },
/* Control Panel */ /* Control Panel */
@@ -292,7 +293,7 @@ export class AdminSidebarComponent extends MenuComponent implements OnInit {
// link: '' // link: ''
// } as LinkMenuItemModel, // } as LinkMenuItemModel,
// icon: 'cogs', // icon: 'cogs',
// index: 9 // index: 10
// }, // },
/* Processes */ /* Processes */
@@ -306,7 +307,7 @@ export class AdminSidebarComponent extends MenuComponent implements OnInit {
link: '/processes' link: '/processes'
} as LinkMenuItemModel, } as LinkMenuItemModel,
icon: 'terminal', icon: 'terminal',
index: 10 index: 12
}, },
]; ];
menuList.forEach((menuSection) => this.menuService.addSection(this.menuID, Object.assign(menuSection, { menuList.forEach((menuSection) => this.menuService.addSection(this.menuID, Object.assign(menuSection, {
@@ -465,6 +466,29 @@ export class AdminSidebarComponent extends MenuComponent implements OnInit {
createSiteAdministratorMenuSections() { createSiteAdministratorMenuSections() {
this.authorizationService.isAuthorized(FeatureID.AdministratorOf).subscribe((authorized) => { this.authorizationService.isAuthorized(FeatureID.AdministratorOf).subscribe((authorized) => {
const menuList = [ const menuList = [
/* Notifications */
{
id: 'notifications',
active: false,
visible: authorized,
model: {
type: MenuItemType.TEXT,
text: 'menu.section.notifications'
} as TextMenuItemModel,
icon: 'bell',
index: 4
},
{
id: 'notifications_reciter',
parentID: 'notifications',
active: false,
visible: authorized,
model: {
type: MenuItemType.LINK,
text: 'menu.section.notifications_reciter',
link: '/admin/notifications/' + NOTIFICATIONS_RECITER_SUGGESTION_PATH
} as LinkMenuItemModel,
},
/* Admin Search */ /* Admin Search */
{ {
id: 'admin_search', id: 'admin_search',
@@ -476,7 +500,7 @@ export class AdminSidebarComponent extends MenuComponent implements OnInit {
link: '/admin/search' link: '/admin/search'
} as LinkMenuItemModel, } as LinkMenuItemModel,
icon: 'search', icon: 'search',
index: 5 index: 6
}, },
/* Registries */ /* Registries */
{ {
@@ -488,7 +512,7 @@ export class AdminSidebarComponent extends MenuComponent implements OnInit {
text: 'menu.section.registries' text: 'menu.section.registries'
} as TextMenuItemModel, } as TextMenuItemModel,
icon: 'list', icon: 'list',
index: 6 index: 7
}, },
{ {
id: 'registries_metadata', id: 'registries_metadata',
@@ -524,7 +548,7 @@ export class AdminSidebarComponent extends MenuComponent implements OnInit {
link: 'admin/curation-tasks' link: 'admin/curation-tasks'
} as LinkMenuItemModel, } as LinkMenuItemModel,
icon: 'filter', icon: 'filter',
index: 7 index: 8
}, },
/* Workflow */ /* Workflow */
@@ -601,7 +625,7 @@ export class AdminSidebarComponent extends MenuComponent implements OnInit {
text: 'menu.section.access_control' text: 'menu.section.access_control'
} as TextMenuItemModel, } as TextMenuItemModel,
icon: 'key', icon: 'key',
index: 4 index: 5
}, },
]; ];

View File

@@ -30,6 +30,7 @@ import { ThemedForbiddenComponent } from './forbidden/themed-forbidden.component
import { GroupAdministratorGuard } from './core/data/feature-authorization/feature-authorization-guard/group-administrator.guard'; import { GroupAdministratorGuard } from './core/data/feature-authorization/feature-authorization-guard/group-administrator.guard';
import { ThemedPageInternalServerErrorComponent } from './page-internal-server-error/themed-page-internal-server-error.component'; import { ThemedPageInternalServerErrorComponent } from './page-internal-server-error/themed-page-internal-server-error.component';
import { ServerCheckGuard } from './core/server-check/server-check.guard'; import { ServerCheckGuard } from './core/server-check/server-check.guard';
import { SUGGESTION_MODULE_PATH } from './suggestions-page/suggestions-page-routing-paths';
@NgModule({ @NgModule({
imports: [ imports: [
@@ -190,6 +191,11 @@ import { ServerCheckGuard } from './core/server-check/server-check.guard';
.then((m) => m.ProcessPageModule), .then((m) => m.ProcessPageModule),
canActivate: [AuthenticatedGuard, EndUserAgreementCurrentUserGuard] canActivate: [AuthenticatedGuard, EndUserAgreementCurrentUserGuard]
}, },
{ path: SUGGESTION_MODULE_PATH,
loadChildren: () => import('./suggestions-page/suggestions-page.module')
.then((m) => m.SuggestionsPageModule),
canActivate: [AuthenticatedGuard, EndUserAgreementCurrentUserGuard]
},
{ {
path: INFO_MODULE_PATH, path: INFO_MODULE_PATH,
loadChildren: () => import('./info/info.module').then((m) => m.InfoModule) loadChildren: () => import('./info/info.module').then((m) => m.InfoModule)

View File

@@ -162,6 +162,9 @@ import { SearchConfig } from './shared/search/search-filters/search-config.model
import { SequenceService } from './shared/sequence.service'; import { SequenceService } from './shared/sequence.service';
import { GroupDataService } from './eperson/group-data.service'; import { GroupDataService } from './eperson/group-data.service';
import { SubmissionAccessesModel } from './config/models/config-submission-accesses.model'; import { SubmissionAccessesModel } from './config/models/config-submission-accesses.model';
import { OpenaireSuggestionTarget } from './openaire/reciter-suggestions/models/openaire-suggestion-target.model';
import { OpenaireSuggestion } from './openaire/reciter-suggestions/models/openaire-suggestion.model';
import { OpenaireSuggestionSource } from './openaire/reciter-suggestions/models/openaire-suggestion-source.model';
/** /**
* When not in production, endpoint responses can be mocked for testing purposes * When not in production, endpoint responses can be mocked for testing purposes
@@ -343,6 +346,9 @@ export const models =
ShortLivedToken, ShortLivedToken,
Registration, Registration,
UsageReport, UsageReport,
OpenaireSuggestion,
OpenaireSuggestionTarget,
OpenaireSuggestionSource,
Root, Root,
SearchConfig, SearchConfig,
SubmissionAccessesModel SubmissionAccessesModel

View File

@@ -0,0 +1,25 @@
import { ResourceType } from '../../../shared/resource-type';
/**
* The resource type for the Suggestion Target object
*
* Needs to be in a separate file to prevent circular
* dependencies in webpack.
*/
export const SUGGESTION_TARGET = new ResourceType('suggestiontarget');
/**
* The resource type for the Suggestion Source object
*
* Needs to be in a separate file to prevent circular
* dependencies in webpack.
*/
export const SUGGESTION_SOURCE = new ResourceType('suggestionsource');
/**
* The resource type for the Suggestion object
*
* Needs to be in a separate file to prevent circular
* dependencies in webpack.
*/
export const SUGGESTION = new ResourceType('suggestion');

View File

@@ -0,0 +1,47 @@
import { autoserialize, deserialize } from 'cerialize';
import { CacheableObject } from '../../../cache/object-cache.reducer';
import { SUGGESTION_SOURCE } from './openaire-suggestion-objects.resource-type';
import { excludeFromEquals } from '../../../utilities/equals.decorators';
import { ResourceType } from '../../../shared/resource-type';
import { HALLink } from '../../../shared/hal-link.model';
import { typedObject } from '../../../cache/builders/build-decorators';
/**
* The interface representing the Suggestion Source model
*/
@typedObject
export class OpenaireSuggestionSource implements CacheableObject {
/**
* A string representing the kind of object, e.g. community, item, …
*/
static type = SUGGESTION_SOURCE;
/**
* The Suggestion Target id
*/
@autoserialize
id: string;
/**
* The total number of suggestions provided by Suggestion Target for
*/
@autoserialize
total: number;
/**
* The type of this ConfigObject
*/
@excludeFromEquals
@autoserialize
type: ResourceType;
/**
* The links to all related resources returned by the rest api.
*/
@deserialize
_links: {
self: HALLink,
suggestiontargets: HALLink
};
}

View File

@@ -0,0 +1,60 @@
import { autoserialize, deserialize } from 'cerialize';
import { CacheableObject } from '../../../cache/object-cache.reducer';
import { SUGGESTION_TARGET } from './openaire-suggestion-objects.resource-type';
import { excludeFromEquals } from '../../../utilities/equals.decorators';
import { ResourceType } from '../../../shared/resource-type';
import { HALLink } from '../../../shared/hal-link.model';
import { typedObject } from '../../../cache/builders/build-decorators';
/**
* The interface representing the Suggestion Target model
*/
@typedObject
export class OpenaireSuggestionTarget implements CacheableObject {
/**
* A string representing the kind of object, e.g. community, item, …
*/
static type = SUGGESTION_TARGET;
/**
* The Suggestion Target id
*/
@autoserialize
id: string;
/**
* The Suggestion Target name to display
*/
@autoserialize
display: string;
/**
* The Suggestion Target source to display
*/
@autoserialize
source: string;
/**
* The total number of suggestions provided by Suggestion Target for
*/
@autoserialize
total: number;
/**
* The type of this ConfigObject
*/
@excludeFromEquals
@autoserialize
type: ResourceType;
/**
* The links to all related resources returned by the rest api.
*/
@deserialize
_links: {
self: HALLink,
suggestions: HALLink,
target: HALLink
};
}

View File

@@ -0,0 +1,85 @@
import { autoserialize, autoserializeAs, deserialize } from 'cerialize';
import { CacheableObject } from '../../../cache/object-cache.reducer';
import { SUGGESTION } from './openaire-suggestion-objects.resource-type';
import { excludeFromEquals } from '../../../utilities/equals.decorators';
import { ResourceType } from '../../../shared/resource-type';
import { HALLink } from '../../../shared/hal-link.model';
import { typedObject } from '../../../cache/builders/build-decorators';
import { MetadataMap, MetadataMapSerializer } from '../../../shared/metadata.models';
export interface SuggestionEvidences {
[sectionId: string]: {
score: string;
notes: string
};
}
/**
* The interface representing the Suggestion Source model
*/
@typedObject
export class OpenaireSuggestion implements CacheableObject {
/**
* A string representing the kind of object, e.g. community, item, …
*/
static type = SUGGESTION;
/**
* The Suggestion id
*/
@autoserialize
id: string;
/**
* The Suggestion name to display
*/
@autoserialize
display: string;
/**
* The Suggestion source to display
*/
@autoserialize
source: string;
/**
* The Suggestion external source uri
*/
@autoserialize
externalSourceUri: string;
/**
* The Total Score of the suggestion
*/
@autoserialize
score: string;
/**
* The total number of suggestions provided by Suggestion Target for
*/
@autoserialize
evidences: SuggestionEvidences;
/**
* All metadata of this suggestion object
*/
@excludeFromEquals
@autoserializeAs(MetadataMapSerializer)
metadata: MetadataMap;
/**
* The type of this ConfigObject
*/
@excludeFromEquals
@autoserialize
type: ResourceType;
/**
* The links to all related resources returned by the rest api.
*/
@deserialize
_links: {
self: HALLink,
target: HALLink
};
}

View File

@@ -0,0 +1,301 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { CoreState } from '../../core.reducers';
import { HALEndpointService } from '../../shared/hal-endpoint.service';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.service';
import { ObjectCacheService } from '../../cache/object-cache.service';
import { dataService } from '../../cache/builders/build-decorators';
import { RequestService } from '../../data/request.service';
import { FindListOptions } from '../../data/request.models';
import { DataService } from '../../data/data.service';
import { ChangeAnalyzer } from '../../data/change-analyzer';
import { DefaultChangeAnalyzer } from '../../data/default-change-analyzer.service';
import { RemoteData } from '../../data/remote-data';
import { SUGGESTION_TARGET } from './models/openaire-suggestion-objects.resource-type';
import { FollowLinkConfig } from '../../../shared/utils/follow-link-config.model';
import { PaginatedList } from '../../data/paginated-list.model';
import { OpenaireSuggestionSource } from './models/openaire-suggestion-source.model';
import { OpenaireSuggestionTarget } from './models/openaire-suggestion-target.model';
import { OpenaireSuggestion } from './models/openaire-suggestion.model';
import { RequestParam } from '../../cache/models/request-param.model';
import { NoContent } from '../../shared/NoContent.model';
/* tslint:disable:max-classes-per-file */
/**
* A private DataService implementation to delegate specific methods to.
*/
class SuggestionDataServiceImpl extends DataService<OpenaireSuggestion> {
/**
* The REST endpoint.
*/
protected linkPath = 'suggestions';
/**
* Initialize service variables
* @param {RequestService} requestService
* @param {RemoteDataBuildService} rdbService
* @param {Store<CoreState>} store
* @param {ObjectCacheService} objectCache
* @param {HALEndpointService} halService
* @param {NotificationsService} notificationsService
* @param {HttpClient} http
* @param {ChangeAnalyzer<OpenaireSuggestion>} comparator
*/
constructor(
protected requestService: RequestService,
protected rdbService: RemoteDataBuildService,
protected store: Store<CoreState>,
protected objectCache: ObjectCacheService,
protected halService: HALEndpointService,
protected notificationsService: NotificationsService,
protected http: HttpClient,
protected comparator: ChangeAnalyzer<OpenaireSuggestion>) {
super();
}
}
/**
* A private DataService implementation to delegate specific methods to.
*/
class SuggestionTargetsDataServiceImpl extends DataService<OpenaireSuggestionTarget> {
/**
* The REST endpoint.
*/
protected linkPath = 'suggestiontargets';
/**
* Initialize service variables
* @param {RequestService} requestService
* @param {RemoteDataBuildService} rdbService
* @param {Store<CoreState>} store
* @param {ObjectCacheService} objectCache
* @param {HALEndpointService} halService
* @param {NotificationsService} notificationsService
* @param {HttpClient} http
* @param {ChangeAnalyzer<OpenaireSuggestionTarget>} comparator
*/
constructor(
protected requestService: RequestService,
protected rdbService: RemoteDataBuildService,
protected store: Store<CoreState>,
protected objectCache: ObjectCacheService,
protected halService: HALEndpointService,
protected notificationsService: NotificationsService,
protected http: HttpClient,
protected comparator: ChangeAnalyzer<OpenaireSuggestionTarget>) {
super();
}
}
/**
* A private DataService implementation to delegate specific methods to.
*/
class SuggestionSourcesDataServiceImpl extends DataService<OpenaireSuggestionSource> {
/**
* The REST endpoint.
*/
protected linkPath = 'suggestionsources';
/**
* Initialize service variables
* @param {RequestService} requestService
* @param {RemoteDataBuildService} rdbService
* @param {Store<CoreState>} store
* @param {ObjectCacheService} objectCache
* @param {HALEndpointService} halService
* @param {NotificationsService} notificationsService
* @param {HttpClient} http
* @param {ChangeAnalyzer<OpenaireSuggestionSource>} comparator
*/
constructor(
protected requestService: RequestService,
protected rdbService: RemoteDataBuildService,
protected store: Store<CoreState>,
protected objectCache: ObjectCacheService,
protected halService: HALEndpointService,
protected notificationsService: NotificationsService,
protected http: HttpClient,
protected comparator: ChangeAnalyzer<OpenaireSuggestionSource>) {
super();
}
}
/**
* The service handling all Suggestion Target REST requests.
*/
@Injectable()
@dataService(SUGGESTION_TARGET)
export class OpenaireSuggestionsDataService {
protected searchFindBySourceMethod = 'findBySource';
protected searchFindByTargetMethod = 'findByTarget';
protected searchFindByTargetAndSourceMethod = 'findByTargetAndSource';
/**
* A private DataService implementation to delegate specific methods to.
*/
private suggestionsDataService: SuggestionDataServiceImpl;
/**
* A private DataService implementation to delegate specific methods to.
*/
private suggestionSourcesDataService: SuggestionSourcesDataServiceImpl;
/**
* A private DataService implementation to delegate specific methods to.
*/
private suggestionTargetsDataService: SuggestionTargetsDataServiceImpl;
/**
* Initialize service variables
* @param {RequestService} requestService
* @param {RemoteDataBuildService} rdbService
* @param {ObjectCacheService} objectCache
* @param {HALEndpointService} halService
* @param {NotificationsService} notificationsService
* @param {HttpClient} http
* @param {DefaultChangeAnalyzer<OpenaireSuggestion>} comparatorSuggestions
* @param {DefaultChangeAnalyzer<OpenaireSuggestionSource>} comparatorSources
* @param {DefaultChangeAnalyzer<OpenaireSuggestionTarget>} comparatorTargets
*/
constructor(
protected requestService: RequestService,
protected rdbService: RemoteDataBuildService,
protected objectCache: ObjectCacheService,
protected halService: HALEndpointService,
protected notificationsService: NotificationsService,
protected http: HttpClient,
protected comparatorSuggestions: DefaultChangeAnalyzer<OpenaireSuggestion>,
protected comparatorSources: DefaultChangeAnalyzer<OpenaireSuggestionSource>,
protected comparatorTargets: DefaultChangeAnalyzer<OpenaireSuggestionTarget>,
) {
this.suggestionsDataService = new SuggestionDataServiceImpl(requestService, rdbService, null, objectCache, halService, notificationsService, http, comparatorSuggestions);
this.suggestionSourcesDataService = new SuggestionSourcesDataServiceImpl(requestService, rdbService, null, objectCache, halService, notificationsService, http, comparatorSources);
this.suggestionTargetsDataService = new SuggestionTargetsDataServiceImpl(requestService, rdbService, null, objectCache, halService, notificationsService, http, comparatorTargets);
}
/**
* Return the list of Suggestion Target
*
* @param options
* Find list options object.
* @return Observable<RemoteData<PaginatedList<OpenaireSuggestionSource>>>
* The list of Suggestion Sources.
*/
public getSources(options: FindListOptions = {}): Observable<RemoteData<PaginatedList<OpenaireSuggestionSource>>> {
return this.suggestionSourcesDataService.findAll(options);
}
/**
* Return the list of Suggestion Target for a given source
*
* @param source
* The source for which to find targets.
* @param options
* Find list options object.
* @param linksToFollow
* List of {@link FollowLinkConfig} that indicate which {@link HALLink}s should be automatically resolved.
* @return Observable<RemoteData<PaginatedList<OpenaireSuggestionTarget>>>
* The list of Suggestion Target.
*/
public getTargets(
source: string,
options: FindListOptions = {},
...linksToFollow: FollowLinkConfig<OpenaireSuggestionTarget>[]
): Observable<RemoteData<PaginatedList<OpenaireSuggestionTarget>>> {
options.searchParams = [new RequestParam('source', source)];
return this.suggestionTargetsDataService.searchBy(this.searchFindBySourceMethod, options, true, true, ...linksToFollow);
}
/**
* Return the list of Suggestion Target for a given user
*
* @param userId
* The user Id for which to find targets.
* @param options
* Find list options object.
* @param linksToFollow
* List of {@link FollowLinkConfig} that indicate which {@link HALLink}s should be automatically resolved.
* @return Observable<RemoteData<PaginatedList<OpenaireSuggestionTarget>>>
* The list of Suggestion Target.
*/
public getTargetsByUser(
userId: string,
options: FindListOptions = {},
...linksToFollow: FollowLinkConfig<OpenaireSuggestionTarget>[]
): Observable<RemoteData<PaginatedList<OpenaireSuggestionTarget>>> {
options.searchParams = [new RequestParam('target', userId)];
return this.suggestionTargetsDataService.searchBy(this.searchFindByTargetMethod, options, true, true, ...linksToFollow);
}
/**
* Return a Suggestion Target for a given id
*
* @param targetId
* The target id to retrieve.
*
* @return Observable<RemoteData<OpenaireSuggestionTarget>>
* The list of Suggestion Target.
*/
public getTargetById(targetId: string): Observable<RemoteData<OpenaireSuggestionTarget>> {
return this.suggestionTargetsDataService.findById(targetId);
}
/**
* Used to delete Suggestion
* @suggestionId
*/
public deleteSuggestion(suggestionId: string): Observable<RemoteData<NoContent>> {
return this.suggestionsDataService.delete(suggestionId);
}
/**
* Used to fetch Suggestion notification for user
* @suggestionId
*/
public getSuggestion(suggestionId: string, ...linksToFollow: FollowLinkConfig<OpenaireSuggestion>[]): Observable<RemoteData<OpenaireSuggestion>> {
return this.suggestionsDataService.findById(suggestionId, true, true, ...linksToFollow);
}
/**
* Return the list of Suggestion for a given target and source
*
* @param target
* The target for which to find suggestions.
* @param source
* The source for which to find suggestions.
* @param options
* Find list options object.
* @param linksToFollow
* List of {@link FollowLinkConfig} that indicate which {@link HALLink}s should be automatically resolved.
* @return Observable<RemoteData<PaginatedList<OpenaireSuggestion>>>
* The list of Suggestion.
*/
public getSuggestionsByTargetAndSource(
target: string,
source: string,
options: FindListOptions = {},
...linksToFollow: FollowLinkConfig<OpenaireSuggestion>[]
): Observable<RemoteData<PaginatedList<OpenaireSuggestion>>> {
options.searchParams = [
new RequestParam('target', target),
new RequestParam('source', source)
];
return this.suggestionsDataService.searchBy(this.searchFindByTargetAndSourceMethod, options, true, true, ...linksToFollow);
}
/**
* Clear findByTargetAndSource suggestions requests from cache
*/
public clearSuggestionRequests() {
this.requestService.setStaleByHrefSubstring(this.searchFindByTargetAndSourceMethod);
}
}

View File

@@ -0,0 +1,72 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Action, StoreConfig, StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { CoreModule } from '../core/core.module';
import { SharedModule } from '../shared/shared.module';
import { storeModuleConfig } from '../app.reducer';
import { openaireReducers, OpenaireState } from './openaire.reducer';
import { SuggestionTargetsStateService } from './reciter-suggestions/suggestion-targets/suggestion-targets.state.service';
import { SuggestionsService } from './reciter-suggestions/suggestions.service';
import { OpenaireSuggestionsDataService } from '../core/openaire/reciter-suggestions/openaire-suggestions-data.service';
import { SuggestionTargetsComponent } from './reciter-suggestions/suggestion-targets/suggestion-targets.component';
import { SuggestionListElementComponent } from './reciter-suggestions/suggestion-list-element/suggestion-list-element.component';
import { SuggestionEvidencesComponent } from './reciter-suggestions/suggestion-list-element/suggestion-evidences/suggestion-evidences.component';
import { SuggestionActionsComponent } from './reciter-suggestions/suggestion-actions/suggestion-actions.component';
import { SuggestionsPopupComponent } from './reciter-suggestions/suggestions-popup/suggestions-popup.component';
import { SuggestionsNotificationComponent } from './reciter-suggestions/suggestions-notification/suggestions-notification.component';
import { TranslateModule } from '@ngx-translate/core';
import { SearchModule } from '../shared/search/search.module';
const MODULES = [
CommonModule,
SharedModule,
CoreModule.forRoot(),
StoreModule.forFeature('openaire', openaireReducers, storeModuleConfig as StoreConfig<OpenaireState, Action>),
TranslateModule
];
const COMPONENTS = [
SuggestionTargetsComponent,
SuggestionActionsComponent,
SuggestionListElementComponent,
SuggestionEvidencesComponent,
SuggestionsPopupComponent,
SuggestionsNotificationComponent
];
const DIRECTIVES = [ ];
const PROVIDERS = [
SuggestionTargetsStateService,
SuggestionsService,
OpenaireSuggestionsDataService
];
@NgModule({
imports: [
...MODULES,
SearchModule
],
declarations: [
...COMPONENTS,
...DIRECTIVES,
],
providers: [
...PROVIDERS
],
entryComponents: [
],
exports: [
...COMPONENTS,
...DIRECTIVES
]
})
/**
* This module handles all components that are necessary for the OpenAIRE components
*/
export class OpenaireModule {
}

View File

@@ -0,0 +1,19 @@
import { ActionReducerMap, createFeatureSelector } from '@ngrx/store';
import {
SuggestionTargetsReducer,
SuggestionTargetState
} from './reciter-suggestions/suggestion-targets/suggestion-targets.reducer';
/**
* The OpenAIRE State
*/
export interface OpenaireState {
'suggestionTarget': SuggestionTargetState;
}
export const openaireReducers: ActionReducerMap<OpenaireState> = {
suggestionTarget: SuggestionTargetsReducer,
};
export const openaireSelector = createFeatureSelector<OpenaireState>('openaire');

View File

@@ -0,0 +1,97 @@
import { createSelector, MemoizedSelector } from '@ngrx/store';
import { subStateSelector } from '../../shared/selector.util';
import { openaireSelector, OpenaireState } from '../openaire.reducer';
import { OpenaireSuggestionTarget } from '../../core/openaire/reciter-suggestions/models/openaire-suggestion-target.model';
import { SuggestionTargetState } from './suggestion-targets/suggestion-targets.reducer';
/**
* Returns the Reciter Suggestion Target state.
* @function _getReciterSuggestionTargetState
* @param {AppState} state Top level state.
* @return {OpenaireState}
*/
const _getReciterSuggestionTargetState = (state: any) => state.openaire;
// Reciter Suggestion Targets
// ----------------------------------------------------------------------------
/**
* Returns the Reciter Suggestion Targets State.
* @function reciterSuggestionTargetStateSelector
* @return {OpenaireState}
*/
export function reciterSuggestionTargetStateSelector(): MemoizedSelector<OpenaireState, SuggestionTargetState> {
return subStateSelector<OpenaireState, SuggestionTargetState>(openaireSelector, 'suggestionTarget');
}
/**
* Returns the Reciter Suggestion Targets list.
* @function reciterSuggestionTargetObjectSelector
* @return {OpenaireReciterSuggestionTarget[]}
*/
export function reciterSuggestionTargetObjectSelector(): MemoizedSelector<OpenaireState, OpenaireSuggestionTarget[]> {
return subStateSelector<OpenaireState, OpenaireSuggestionTarget[]>(reciterSuggestionTargetStateSelector(), 'targets');
}
/**
* Returns true if the Reciter Suggestion Targets are loaded.
* @function isReciterSuggestionTargetLoadedSelector
* @return {boolean}
*/
export const isReciterSuggestionTargetLoadedSelector = createSelector(_getReciterSuggestionTargetState,
(state: OpenaireState) => state.suggestionTarget.loaded
);
/**
* Returns true if the deduplication sets are processing.
* @function isDeduplicationSetsProcessingSelector
* @return {boolean}
*/
export const isreciterSuggestionTargetProcessingSelector = createSelector(_getReciterSuggestionTargetState,
(state: OpenaireState) => state.suggestionTarget.processing
);
/**
* Returns the total available pages of Reciter Suggestion Targets.
* @function getreciterSuggestionTargetTotalPagesSelector
* @return {number}
*/
export const getreciterSuggestionTargetTotalPagesSelector = createSelector(_getReciterSuggestionTargetState,
(state: OpenaireState) => state.suggestionTarget.totalPages
);
/**
* Returns the current page of Reciter Suggestion Targets.
* @function getreciterSuggestionTargetCurrentPageSelector
* @return {number}
*/
export const getreciterSuggestionTargetCurrentPageSelector = createSelector(_getReciterSuggestionTargetState,
(state: OpenaireState) => state.suggestionTarget.currentPage
);
/**
* Returns the total number of Reciter Suggestion Targets.
* @function getreciterSuggestionTargetTotalsSelector
* @return {number}
*/
export const getreciterSuggestionTargetTotalsSelector = createSelector(_getReciterSuggestionTargetState,
(state: OpenaireState) => state.suggestionTarget.totalElements
);
/**
* Returns Suggestion Targets for the current user.
* @function getCurrentUserReciterSuggestionTargetSelector
* @return {OpenaireSuggestionTarget[]}
*/
export const getCurrentUserSuggestionTargetsSelector = createSelector(_getReciterSuggestionTargetState,
(state: OpenaireState) => state.suggestionTarget.currentUserTargets
);
/**
* Returns whether or not the user has consulted their suggestions
* @function getCurrentUserReciterSuggestionTargetSelector
* @return {boolean}
*/
export const getCurrentUserSuggestionTargetsVisitedSelector = createSelector(_getReciterSuggestionTargetState,
(state: OpenaireState) => state.suggestionTarget.currentUserTargetsVisited
);

View File

@@ -0,0 +1,28 @@
<div class="d-inline">
<div ngbDropdown class="d-inline">
<button *ngIf="isCollectionFixed; else chooseCollection" class="btn btn-success" type="button" (click)="approveAndImportCollectionFixed()">
<i class="fa fa-check" aria-hidden="true"></i> {{ approveAndImportLabel() | translate}}
</button>
<ng-template #chooseCollection>
<button class="btn btn-success" id="dropdownSubmission" ngbDropdownToggle
type="button">
<i class="fa fa-check" aria-hidden="true"></i> {{ approveAndImportLabel() | translate}}
<span class="caret"></span>
</button>
<div ngbDropdownMenu
class="dropdown-menu"
id="entityControlsDropdownMenu"
aria-labelledby="dropdownSubmission">
<ds-entity-dropdown (selectionChange)="openDialog($event)"></ds-entity-dropdown>
</div>
</ng-template>
</div>
<button (click)="notMine()" class="btn btn-danger ml-2"><i class="fa fa-ban"></i>
{{ notMineLabel() | translate}}</button>
<button *ngIf="!isBulk" (click)="toggleSeeEvidences()" [disabled]="!hasEvidence" class="btn btn-info mt-1 ml-2"><i class="fa fa-eye"></i>
<ng-container *ngIf="!seeEvidence">{{'reciter.suggestion.seeEvidence' | translate}}</ng-container>
<ng-container *ngIf="seeEvidence">{{'reciter.suggestion.hideEvidence' | translate}}</ng-container>
</button>
</div>

View File

@@ -0,0 +1,92 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';
import { ItemType } from '../../../core/shared/item-relationships/item-type.model';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { OpenaireSuggestion } from '../../../core/openaire/reciter-suggestions/models/openaire-suggestion.model';
import { SuggestionApproveAndImport } from '../suggestion-list-element/suggestion-list-element.component';
import { Collection } from '../../../core/shared/collection.model';
import { take } from 'rxjs/operators';
import { CreateItemParentSelectorComponent } from '../../../shared/dso-selector/modal-wrappers/create-item-parent-selector/create-item-parent-selector.component';
@Component({
selector: 'ds-suggestion-actions',
styleUrls: [ './suggestion-actions.component.scss' ],
templateUrl: './suggestion-actions.component.html'
})
export class SuggestionActionsComponent {
@Input() object: OpenaireSuggestion;
@Input() isBulk = false;
@Input() hasEvidence = false;
@Input() seeEvidence = false;
@Input() isCollectionFixed = false;
/**
* The component is used to Delete suggestion
*/
@Output() notMineClicked = new EventEmitter<string>();
/**
* The component is used to approve & import
*/
@Output() approveAndImport = new EventEmitter<SuggestionApproveAndImport>();
/**
* The component is used to approve & import
*/
@Output() seeEvidences = new EventEmitter<boolean>();
constructor(private modalService: NgbModal) { }
/**
* Method called on clicking the button "approve & import", It opens a dialog for
* select a collection and it emits an approveAndImport event.
*/
openDialog(entity: ItemType) {
const modalRef = this.modalService.open(CreateItemParentSelectorComponent);
modalRef.componentInstance.emitOnly = true;
modalRef.componentInstance.entityType = entity.label;
modalRef.componentInstance.select.pipe(take(1))
.subscribe((collection: Collection) => {
this.approveAndImport.emit({
suggestion: this.isBulk ? undefined : this.object,
collectionId: collection.id
});
});
}
approveAndImportCollectionFixed() {
this.approveAndImport.emit({
suggestion: this.isBulk ? undefined : this.object,
collectionId: null
});
}
/**
* Delete the suggestion
*/
notMine() {
this.notMineClicked.emit(this.isBulk ? undefined : this.object.id);
}
/**
* Toggle See Evidence
*/
toggleSeeEvidences() {
this.seeEvidences.emit(!this.seeEvidence);
}
notMineLabel(): string {
return this.isBulk ? 'reciter.suggestion.notMine.bulk' : 'reciter.suggestion.notMine' ;
}
approveAndImportLabel(): string {
return this.isBulk ? 'reciter.suggestion.approveAndImport.bulk' : 'reciter.suggestion.approveAndImport';
}
}

View File

@@ -0,0 +1,20 @@
<div>
<div class="table-responsive" *ngIf="evidences">
<table class="table">
<thead>
<tr>
<th>{{'reciter.suggestion.evidence.score' | translate}}</th>
<th>{{'reciter.suggestion.evidence.type' | translate}}</th>
<th>{{'reciter.suggestion.evidence.notes' | translate}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let evidence of evidences | dsObjectKeys">
<td>{{evidences[evidence].score}}</td>
<td>{{evidence | translate}}</td>
<td>{{evidences[evidence].notes}}</td>
</tr>
</tbody>
</table>
</div>
</div>

View File

@@ -0,0 +1,15 @@
import { Component, Input } from '@angular/core';
import { fadeIn } from '../../../../shared/animations/fade';
import { SuggestionEvidences } from '../../../../core/openaire/reciter-suggestions/models/openaire-suggestion.model';
@Component({
selector: 'ds-suggestion-evidences',
styleUrls: [ './suggestion-evidences.component.scss' ],
templateUrl: './suggestion-evidences.component.html',
animations: [fadeIn]
})
export class SuggestionEvidencesComponent {
@Input() evidences: SuggestionEvidences;
}

View File

@@ -0,0 +1,44 @@
<div class="container">
<div class="row">
<!-- Bulk Selection Panel -->
<div class="col-1 text-center align-self-center">
<div class="">
<input type="checkbox" class="form-check-input"
[checked]="isSelected" (change)="changeSelected($event)"/>
</div>
</div>
<!-- Total Score Panel -->
<div class="col-2 text-center align-self-center">
<div class="">
<div><strong> {{'reciter.suggestion.totalScore' | translate}}</strong> </div>
<span class="suggestion-score">{{ object.score }}</span>
</div>
</div>
<!-- Suggestion Panel -->
<div class="col">
<!-- Object Preview -->
<ds-item-search-result-list-element
[showLabel]="false"
[object]="listableObject"
[linkType]="0"
[hideMetrics]="true"
></ds-item-search-result-list-element>
<!-- Actions -->
<ds-suggestion-actions class="parent mt-2" [hasEvidence]="hasEvidences()"
[seeEvidence]="seeEvidence"
[object]="object"
[isCollectionFixed]="isCollectionFixed"
(approveAndImport)="onApproveAndImport($event)"
(seeEvidences)="onSeeEvidences($event)"
(notMineClicked)="onNotMine($event)"
></ds-suggestion-actions>
</div>
</div>
<!-- Evidences Panel -->
<div *ngIf="seeEvidence" class="mt-2 row">
<div class="col offset-3">
<ds-suggestion-evidences [evidences]="object.evidences"></ds-suggestion-evidences>
</div>
</div>
</div>
<hr>

View File

@@ -0,0 +1,16 @@
.issue-date {
color: #c8c8c8;
}
.parent {
display: flex;
gap:10px;
}
.import {
flex: initial;
}
.suggestion-score {
font-size: 1.5rem;
}

View File

@@ -0,0 +1,98 @@
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { fadeIn } from '../../../shared/animations/fade';
import { OpenaireSuggestion } from '../../../core/openaire/reciter-suggestions/models/openaire-suggestion.model';
import { Item } from '../../../core/shared/item.model';
import { isNotEmpty } from '../../../shared/empty.util';
export interface SuggestionApproveAndImport {
suggestion: OpenaireSuggestion;
collectionId: string;
}
@Component({
selector: 'ds-suggestion-list-item',
styleUrls: ['./suggestion-list-element.component.scss'],
templateUrl: './suggestion-list-element.component.html',
animations: [fadeIn]
})
export class SuggestionListElementComponent implements OnInit {
@Input() object: OpenaireSuggestion;
@Input() isSelected = false;
@Input() isCollectionFixed = false;
public listableObject: any;
public seeEvidence = false;
/**
* The component is used to Delete suggestion
*/
@Output() notMineClicked = new EventEmitter();
/**
* The component is used to approve & import
*/
@Output() approveAndImport = new EventEmitter();
/**
* New value whether the element is selected
*/
@Output() selected = new EventEmitter<boolean>();
/**
* Initialize instance variables
*
* @param {NgbModal} modalService
*/
constructor(private modalService: NgbModal) { }
ngOnInit() {
this.listableObject = {
indexableObject: Object.assign(new Item(), {id: this.object.id, metadata: this.object.metadata}),
hitHighlights: {}
};
}
/**
* Approve and import the suggestion
*/
onApproveAndImport(event: SuggestionApproveAndImport) {
this.approveAndImport.emit(event);
}
/**
* Delete the suggestion
*/
onNotMine(suggestionId: string) {
this.notMineClicked.emit(suggestionId);
}
/**
* Change is selected value.
*/
changeSelected(event) {
this.isSelected = event.target.checked;
this.selected.next(this.isSelected);
}
/**
* See the Evidence
*/
hasEvidences() {
return isNotEmpty(this.object.evidences);
}
/**
* Set the see evidence variable.
*/
onSeeEvidences(seeEvidence: boolean) {
this.seeEvidence = seeEvidence;
}
}

View File

@@ -0,0 +1,154 @@
import { Action } from '@ngrx/store';
import { type } from '../../../shared/ngrx/type';
import { OpenaireSuggestionTarget } from '../../../core/openaire/reciter-suggestions/models/openaire-suggestion-target.model';
/**
* For each action type in an action group, make a simple
* enum object for all of this group's action types.
*
* The 'type' utility function coerces strings into string
* literal types and runs a simple check to guarantee all
* action types in the application are unique.
*/
export const SuggestionTargetActionTypes = {
ADD_TARGETS: type('dspace/integration/openaire/suggestions/target/ADD_TARGETS'),
CLEAR_TARGETS: type('dspace/integration/openaire/suggestions/target/CLEAR_TARGETS'),
RETRIEVE_TARGETS_BY_SOURCE: type('dspace/integration/openaire/suggestions/target/RETRIEVE_TARGETS_BY_SOURCE'),
RETRIEVE_TARGETS_BY_SOURCE_ERROR: type('dspace/integration/openaire/suggestions/target/RETRIEVE_TARGETS_BY_SOURCE_ERROR'),
ADD_USER_SUGGESTIONS: type('dspace/integration/openaire/suggestions/target/ADD_USER_SUGGESTIONS'),
REFRESH_USER_SUGGESTIONS: type('dspace/integration/openaire/suggestions/target/REFRESH_USER_SUGGESTIONS'),
MARK_USER_SUGGESTIONS_AS_VISITED: type('dspace/integration/openaire/suggestions/target/MARK_USER_SUGGESTIONS_AS_VISITED')
};
/* tslint:disable:max-classes-per-file */
/**
* An ngrx action to retrieve all the Suggestion Targets.
*/
export class RetrieveTargetsBySourceAction implements Action {
type = SuggestionTargetActionTypes.RETRIEVE_TARGETS_BY_SOURCE;
payload: {
source: string;
elementsPerPage: number;
currentPage: number;
};
/**
* Create a new RetrieveTargetsBySourceAction.
*
* @param source
* the source for which to retrieve suggestion targets
* @param elementsPerPage
* the number of targets per page
* @param currentPage
* The page number to retrieve
*/
constructor(source: string, elementsPerPage: number, currentPage: number) {
this.payload = {
source,
elementsPerPage,
currentPage
};
}
}
/**
* An ngrx action for retrieving 'all Suggestion Targets' error.
*/
export class RetrieveAllTargetsErrorAction implements Action {
type = SuggestionTargetActionTypes.RETRIEVE_TARGETS_BY_SOURCE_ERROR;
}
/**
* An ngrx action to load the Suggestion Target objects.
*/
export class AddTargetAction implements Action {
type = SuggestionTargetActionTypes.ADD_TARGETS;
payload: {
targets: OpenaireSuggestionTarget[];
totalPages: number;
currentPage: number;
totalElements: number;
};
/**
* Create a new AddTargetAction.
*
* @param targets
* the list of targets
* @param totalPages
* the total available pages of targets
* @param currentPage
* the current page
* @param totalElements
* the total available Suggestion Targets
*/
constructor(targets: OpenaireSuggestionTarget[], totalPages: number, currentPage: number, totalElements: number) {
this.payload = {
targets,
totalPages,
currentPage,
totalElements
};
}
}
/**
* An ngrx action to load the user Suggestion Target object.
* Called by the ??? effect.
*/
export class AddUserSuggestionsAction implements Action {
type = SuggestionTargetActionTypes.ADD_USER_SUGGESTIONS;
payload: {
suggestionTargets: OpenaireSuggestionTarget[];
};
/**
* Create a new AddUserSuggestionsAction.
*
* @param suggestionTargets
* the user suggestions target
*/
constructor(suggestionTargets: OpenaireSuggestionTarget[]) {
this.payload = { suggestionTargets };
}
}
/**
* An ngrx action to reload the user Suggestion Target object.
* Called by the ??? effect.
*/
export class RefreshUserSuggestionsAction implements Action {
type = SuggestionTargetActionTypes.REFRESH_USER_SUGGESTIONS;
}
/**
* An ngrx action to Mark User Suggestions As Visited.
* Called by the ??? effect.
*/
export class MarkUserSuggestionsAsVisitedAction implements Action {
type = SuggestionTargetActionTypes.MARK_USER_SUGGESTIONS_AS_VISITED;
}
/**
* An ngrx action to clear targets state.
*/
export class ClearSuggestionTargetsAction implements Action {
type = SuggestionTargetActionTypes.CLEAR_TARGETS;
}
/* tslint:enable:max-classes-per-file */
/**
* Export a type alias of all actions in this action group
* so that reducers can easily compose action types.
*/
export type SuggestionTargetsActions
= AddTargetAction
| AddUserSuggestionsAction
| ClearSuggestionTargetsAction
| MarkUserSuggestionsAsVisitedAction
| RetrieveTargetsBySourceAction
| RetrieveAllTargetsErrorAction;

View File

@@ -0,0 +1,51 @@
<div class="container">
<div class="row">
<div class="col-12">
<h3 id="header" class="border-bottom pb-2">{{'reciter.suggestion.title'| translate}}</h3>
<ds-loading class="container" *ngIf="(isTargetsLoading() | async)" message="{{'reciter.suggestion.loading' | translate}}"></ds-loading>
<ds-pagination *ngIf="!(isTargetsLoading() | async)"
[paginationOptions]="paginationConfig"
[collectionSize]="(totalElements$ | async)"
[hideGear]="false"
[hideSortOptions]="true"
[retainScrollPosition]="false"
(paginationChange)="getSuggestionTargets()">
<ds-loading class="container" *ngIf="(isTargetsProcessing() | async)" message="'reciter.suggestion.loading' | translate"></ds-loading>
<ng-container *ngIf="!(isTargetsProcessing() | async)">
<div *ngIf="!(targets$|async) || (targets$|async)?.length == 0" class="alert alert-info w-100 mb-2 mt-2" role="alert">
{{'reciter.suggestion.noTargets' | translate}}
</div>
<div *ngIf="(targets$|async) && (targets$|async)?.length != 0" class="table-responsive mt-2">
<table id="epeople" class="table table-striped table-hover table-bordered">
<thead>
<tr class="text-center">
<th scope="col">{{'reciter.suggestion.table.name' | translate}}</th>
<th scope="col">{{'reciter.suggestion.table.actions' | translate}}</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let targetElement of (targets$ | async); let i = index" class="text-center">
<td>
<a target="_blank" [routerLink]="['/items', getTargetUuid(targetElement)]">{{targetElement.display}}</a>
</td>
<td>
<div class="btn-group edit-field">
<button (click)="redirectToSuggestions(targetElement.id, targetElement.display)"
class="btn btn-outline-primary btn-sm"
title="{{'reciter.suggestion.button.review' | translate }}">
<span >{{'reciter.suggestion.button.review' | translate: { total: targetElement.total.toString() } }} </span>
<i class="fas fa-lightbulb"></i>
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</ng-container>
</ds-pagination>
</div>
</div>
</div>

View File

@@ -0,0 +1,150 @@
import { Component, Input, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable, Subscription } from 'rxjs';
import { distinctUntilChanged, take } from 'rxjs/operators';
import { OpenaireSuggestionTarget } from '../../../core/openaire/reciter-suggestions/models/openaire-suggestion-target.model';
import { hasValue } from '../../../shared/empty.util';
import { PaginationComponentOptions } from '../../../shared/pagination/pagination-component-options.model';
import { SuggestionTargetsStateService } from './suggestion-targets.state.service';
import { getSuggestionPageRoute } from '../../../suggestions-page/suggestions-page-routing-paths';
import { SuggestionsService } from '../suggestions.service';
import { PaginationService } from '../../../core/pagination/pagination.service';
/**
* Component to display the Suggestion Target list.
*/
@Component({
selector: 'ds-suggestion-target',
templateUrl: './suggestion-targets.component.html',
styleUrls: ['./suggestion-targets.component.scss'],
})
export class SuggestionTargetsComponent implements OnInit {
/**
* The source for which to list targets
*/
@Input() source: string;
/**
* The pagination system configuration for HTML listing.
* @type {PaginationComponentOptions}
*/
public paginationConfig: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), {
id: 'stp',
pageSizeOptions: [5, 10, 20, 40, 60]
});
/**
* The Suggestion Target list.
*/
public targets$: Observable<OpenaireSuggestionTarget[]>;
/**
* The total number of Suggestion Targets.
*/
public totalElements$: Observable<number>;
/**
* Array to track all the component subscriptions. Useful to unsubscribe them with 'onDestroy'.
* @type {Array}
*/
protected subs: Subscription[] = [];
/**
* Initialize the component variables.
* @param {PaginationService} paginationService
* @param {SuggestionTargetsStateService} suggestionTargetsStateService
* @param {SuggestionsService} suggestionService
* @param {Router} router
*/
constructor(
private paginationService: PaginationService,
private suggestionTargetsStateService: SuggestionTargetsStateService,
private suggestionService: SuggestionsService,
private router: Router
) {
}
/**
* Component initialization.
*/
ngOnInit(): void {
this.targets$ = this.suggestionTargetsStateService.getReciterSuggestionTargets();
this.totalElements$ = this.suggestionTargetsStateService.getReciterSuggestionTargetsTotals();
}
/**
* First Suggestion Targets loading after view initialization.
*/
ngAfterViewInit(): void {
this.subs.push(
this.suggestionTargetsStateService.isReciterSuggestionTargetsLoaded().pipe(
take(1)
).subscribe(() => {
this.getSuggestionTargets();
})
);
}
/**
* Returns the information about the loading status of the Suggestion Targets (if it's running or not).
*
* @return Observable<boolean>
* 'true' if the targets are loading, 'false' otherwise.
*/
public isTargetsLoading(): Observable<boolean> {
return this.suggestionTargetsStateService.isReciterSuggestionTargetsLoading();
}
/**
* Returns the information about the processing status of the Suggestion Targets (if it's running or not).
*
* @return Observable<boolean>
* 'true' if there are operations running on the targets (ex.: a REST call), 'false' otherwise.
*/
public isTargetsProcessing(): Observable<boolean> {
return this.suggestionTargetsStateService.isReciterSuggestionTargetsProcessing();
}
/**
* Redirect to suggestion page.
*
* @param {string} id
* the id of suggestion target
* @param {string} name
* the name of suggestion target
*/
public redirectToSuggestions(id: string, name: string) {
this.router.navigate([getSuggestionPageRoute(id)]);
}
/**
* Unsubscribe from all subscriptions.
*/
ngOnDestroy(): void {
this.suggestionTargetsStateService.dispatchClearSuggestionTargetsAction();
this.subs
.filter((sub) => hasValue(sub))
.forEach((sub) => sub.unsubscribe());
}
/**
* Dispatch the Suggestion Targets retrival.
*/
public getSuggestionTargets(): void {
this.paginationService.getCurrentPagination(this.paginationConfig.id, this.paginationConfig).pipe(
distinctUntilChanged(),
take(1)
).subscribe((options: PaginationComponentOptions) => {
this.suggestionTargetsStateService.dispatchRetrieveReciterSuggestionTargets(
this.source,
options.pageSize,
options.currentPage
);
});
}
public getTargetUuid(target: OpenaireSuggestionTarget) {
return this.suggestionService.getTargetUuid(target);
}
}

View File

@@ -0,0 +1,110 @@
import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import { Actions, Effect, ofType } from '@ngrx/effects';
import { TranslateService } from '@ngx-translate/core';
import { catchError, map, switchMap, tap } from 'rxjs/operators';
import { of } from 'rxjs';
import {
AddTargetAction,
AddUserSuggestionsAction,
RefreshUserSuggestionsAction,
RetrieveAllTargetsErrorAction,
RetrieveTargetsBySourceAction,
SuggestionTargetActionTypes,
} from './suggestion-targets.actions';
import { PaginatedList } from '../../../core/data/paginated-list.model';
import { SuggestionsService } from '../suggestions.service';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { AuthActionTypes, RetrieveAuthenticatedEpersonSuccessAction } from '../../../core/auth/auth.actions';
import { OpenaireSuggestionTarget } from '../../../core/openaire/reciter-suggestions/models/openaire-suggestion-target.model';
import { EPerson } from '../../../core/eperson/models/eperson.model';
/**
* Provides effect methods for the Suggestion Targets actions.
*/
@Injectable()
export class SuggestionTargetsEffects {
/**
* Retrieve all Suggestion Targets managing pagination and errors.
*/
@Effect() retrieveTargetsBySource$ = this.actions$.pipe(
ofType(SuggestionTargetActionTypes.RETRIEVE_TARGETS_BY_SOURCE),
switchMap((action: RetrieveTargetsBySourceAction) => {
return this.suggestionsService.getTargets(
action.payload.source,
action.payload.elementsPerPage,
action.payload.currentPage
).pipe(
map((targets: PaginatedList<OpenaireSuggestionTarget>) =>
new AddTargetAction(targets.page, targets.totalPages, targets.currentPage, targets.totalElements)
),
catchError((error: Error) => {
if (error) {
console.error(error.message);
}
return of(new RetrieveAllTargetsErrorAction());
})
);
})
);
/**
* Show a notification on error.
*/
@Effect({ dispatch: false }) retrieveAllTargetsErrorAction$ = this.actions$.pipe(
ofType(SuggestionTargetActionTypes.RETRIEVE_TARGETS_BY_SOURCE_ERROR),
tap(() => {
this.notificationsService.error(null, this.translate.get('reciter.suggestion.target.error.service.retrieve'));
})
);
/**
* Show a notification on error.
*/
@Effect() retrieveUserTargets$ = this.actions$.pipe(
ofType(AuthActionTypes.RETRIEVE_AUTHENTICATED_EPERSON_SUCCESS),
switchMap((action: RetrieveAuthenticatedEpersonSuccessAction) => {
return this.suggestionsService.retrieveCurrentUserSuggestions(action.payload).pipe(
map((suggestionTargets: OpenaireSuggestionTarget[]) => new AddUserSuggestionsAction(suggestionTargets))
);
}));
/**
* Fetch the current user suggestion
*/
@Effect() refreshUserTargets$ = this.actions$.pipe(
ofType(SuggestionTargetActionTypes.REFRESH_USER_SUGGESTIONS),
switchMap((action: RefreshUserSuggestionsAction) => {
return this.store$.select((state: any) => state.core.auth.user)
.pipe(
switchMap((user: EPerson) => {
return this.suggestionsService.retrieveCurrentUserSuggestions(user)
.pipe(
map((suggestionTargets: OpenaireSuggestionTarget[]) => new AddUserSuggestionsAction(suggestionTargets)),
catchError((errors) => of(errors))
);
}),
catchError((errors) => of(errors))
);
}));
/**
* Initialize the effect class variables.
* @param {Actions} actions$
* @param {Store<any>} store$
* @param {TranslateService} translate
* @param {NotificationsService} notificationsService
* @param {SuggestionsService} suggestionsService
*/
constructor(
private actions$: Actions,
private store$: Store<any>,
private translate: TranslateService,
private notificationsService: NotificationsService,
private suggestionsService: SuggestionsService
) {
}
}

View File

@@ -0,0 +1,100 @@
import { SuggestionTargetActionTypes, SuggestionTargetsActions } from './suggestion-targets.actions';
import { OpenaireSuggestionTarget } from '../../../core/openaire/reciter-suggestions/models/openaire-suggestion-target.model';
/**
* The interface representing the OpenAIRE suggestion targets state.
*/
export interface SuggestionTargetState {
targets: OpenaireSuggestionTarget[];
processing: boolean;
loaded: boolean;
totalPages: number;
currentPage: number;
totalElements: number;
currentUserTargets: OpenaireSuggestionTarget[];
currentUserTargetsVisited: boolean;
}
/**
* Used for the OpenAIRE Suggestion Target state initialization.
*/
const SuggestionTargetInitialState: SuggestionTargetState = {
targets: [],
processing: false,
loaded: false,
totalPages: 0,
currentPage: 0,
totalElements: 0,
currentUserTargets: null,
currentUserTargetsVisited: false
};
/**
* The OpenAIRE Broker Topic Reducer
*
* @param state
* the current state initialized with SuggestionTargetInitialState
* @param action
* the action to perform on the state
* @return SuggestionTargetState
* the new state
*/
export function SuggestionTargetsReducer(state = SuggestionTargetInitialState, action: SuggestionTargetsActions): SuggestionTargetState {
switch (action.type) {
case SuggestionTargetActionTypes.RETRIEVE_TARGETS_BY_SOURCE: {
return Object.assign({}, state, {
targets: [],
processing: true
});
}
case SuggestionTargetActionTypes.ADD_TARGETS: {
return Object.assign({}, state, {
targets: state.targets.concat(action.payload.targets),
processing: false,
loaded: true,
totalPages: action.payload.totalPages,
currentPage: state.currentPage,
totalElements: action.payload.totalElements
});
}
case SuggestionTargetActionTypes.RETRIEVE_TARGETS_BY_SOURCE_ERROR: {
return Object.assign({}, state, {
targets: [],
processing: false,
loaded: true,
totalPages: 0,
currentPage: 0,
totalElements: 0,
});
}
case SuggestionTargetActionTypes.ADD_USER_SUGGESTIONS: {
return Object.assign({}, state, {
currentUserTargets: action.payload.suggestionTargets
});
}
case SuggestionTargetActionTypes.MARK_USER_SUGGESTIONS_AS_VISITED: {
return Object.assign({}, state, {
currentUserTargetsVisited: true
});
}
case SuggestionTargetActionTypes.CLEAR_TARGETS: {
return Object.assign({}, state, {
targets: [],
processing: false,
loaded: false,
totalPages: 0,
currentPage: 0,
totalElements: 0,
});
}
default: {
return state;
}
}
}

View File

@@ -0,0 +1,164 @@
import { Injectable } from '@angular/core';
import { select, Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import {
getCurrentUserSuggestionTargetsSelector,
getCurrentUserSuggestionTargetsVisitedSelector,
getreciterSuggestionTargetCurrentPageSelector,
getreciterSuggestionTargetTotalsSelector,
isReciterSuggestionTargetLoadedSelector,
isreciterSuggestionTargetProcessingSelector,
reciterSuggestionTargetObjectSelector
} from '../selectors';
import { OpenaireSuggestionTarget } from '../../../core/openaire/reciter-suggestions/models/openaire-suggestion-target.model';
import {
ClearSuggestionTargetsAction,
MarkUserSuggestionsAsVisitedAction,
RefreshUserSuggestionsAction,
RetrieveTargetsBySourceAction
} from './suggestion-targets.actions';
import { OpenaireState } from '../../openaire.reducer';
/**
* The service handling the Suggestion targets State.
*/
@Injectable()
export class SuggestionTargetsStateService {
/**
* Initialize the service variables.
* @param {Store<OpenaireState>} store
*/
constructor(private store: Store<OpenaireState>) { }
/**
* Returns the list of Reciter Suggestion Targets from the state.
*
* @return Observable<OpenaireReciterSuggestionTarget>
* The list of Reciter Suggestion Targets.
*/
public getReciterSuggestionTargets(): Observable<OpenaireSuggestionTarget[]> {
return this.store.pipe(select(reciterSuggestionTargetObjectSelector()));
}
/**
* Returns the information about the loading status of the Reciter Suggestion Targets (if it's running or not).
*
* @return Observable<boolean>
* 'true' if the targets are loading, 'false' otherwise.
*/
public isReciterSuggestionTargetsLoading(): Observable<boolean> {
return this.store.pipe(
select(isReciterSuggestionTargetLoadedSelector),
map((loaded: boolean) => !loaded)
);
}
/**
* Returns the information about the loading status of the Reciter Suggestion Targets (whether or not they were loaded).
*
* @return Observable<boolean>
* 'true' if the targets are loaded, 'false' otherwise.
*/
public isReciterSuggestionTargetsLoaded(): Observable<boolean> {
return this.store.pipe(select(isReciterSuggestionTargetLoadedSelector));
}
/**
* Returns the information about the processing status of the Reciter Suggestion Targets (if it's running or not).
*
* @return Observable<boolean>
* 'true' if there are operations running on the targets (ex.: a REST call), 'false' otherwise.
*/
public isReciterSuggestionTargetsProcessing(): Observable<boolean> {
return this.store.pipe(select(isreciterSuggestionTargetProcessingSelector));
}
/**
* Returns, from the state, the total available pages of the Reciter Suggestion Targets.
*
* @return Observable<number>
* The number of the Reciter Suggestion Targets pages.
*/
public getReciterSuggestionTargetsTotalPages(): Observable<number> {
return this.store.pipe(select(getreciterSuggestionTargetTotalsSelector));
}
/**
* Returns the current page of the Reciter Suggestion Targets, from the state.
*
* @return Observable<number>
* The number of the current Reciter Suggestion Targets page.
*/
public getReciterSuggestionTargetsCurrentPage(): Observable<number> {
return this.store.pipe(select(getreciterSuggestionTargetCurrentPageSelector));
}
/**
* Returns the total number of the Reciter Suggestion Targets.
*
* @return Observable<number>
* The number of the Reciter Suggestion Targets.
*/
public getReciterSuggestionTargetsTotals(): Observable<number> {
return this.store.pipe(select(getreciterSuggestionTargetTotalsSelector));
}
/**
* Dispatch a request to change the Reciter Suggestion Targets state, retrieving the targets from the server.
*
* @param source
* the source for which to retrieve suggestion targets
* @param elementsPerPage
* The number of the targets per page.
* @param currentPage
* The number of the current page.
*/
public dispatchRetrieveReciterSuggestionTargets(source: string, elementsPerPage: number, currentPage: number): void {
this.store.dispatch(new RetrieveTargetsBySourceAction(source, elementsPerPage, currentPage));
}
/**
* Returns, from the state, the reciter suggestion targets for the current user.
*
* @return Observable<OpenaireReciterSuggestionTarget>
* The Reciter Suggestion Targets object.
*/
public getCurrentUserSuggestionTargets(): Observable<OpenaireSuggestionTarget[]> {
return this.store.pipe(select(getCurrentUserSuggestionTargetsSelector));
}
/**
* Returns, from the state, whether or not the user has consulted their suggestion targets.
*
* @return Observable<boolean>
* True if user already visited, false otherwise.
*/
public hasUserVisitedSuggestions(): Observable<boolean> {
return this.store.pipe(select(getCurrentUserSuggestionTargetsVisitedSelector));
}
/**
* Dispatch a new MarkUserSuggestionsAsVisitedAction
*/
public dispatchMarkUserSuggestionsAsVisitedAction(): void {
this.store.dispatch(new MarkUserSuggestionsAsVisitedAction());
}
/**
* Dispatch an action to clear the Reciter Suggestion Targets state.
*/
public dispatchClearSuggestionTargetsAction(): void {
this.store.dispatch(new ClearSuggestionTargetsAction());
}
/**
* Dispatch an action to refresh the user suggestions.
*/
public dispatchRefreshUserSuggestionsAction(): void {
this.store.dispatch(new RefreshUserSuggestionsAction());
}
}

View File

@@ -0,0 +1,8 @@
<ng-container *ngIf="(suggestionsRD$ | async) as suggestions">
<ng-container *ngFor="let suggestion of suggestions" class="alert alert-info">
<div class="alert alert-success d-block" *ngIf="suggestion.total > 0">
<div [innerHTML]="'mydspace.notification.suggestion.page' | translate: getNotificationSuggestionInterpolation(suggestion)">
</div>
</div>
</ng-container>
</ng-container>

View File

@@ -0,0 +1,42 @@
import { Component, OnInit } from '@angular/core';
import { OpenaireSuggestionTarget } from '../../../core/openaire/reciter-suggestions/models/openaire-suggestion-target.model';
import { TranslateService } from '@ngx-translate/core';
import { SuggestionTargetsStateService } from '../suggestion-targets/suggestion-targets.state.service';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { SuggestionsService } from '../suggestions.service';
import { Observable } from 'rxjs';
@Component({
selector: 'ds-suggestions-notification',
templateUrl: './suggestions-notification.component.html',
styleUrls: ['./suggestions-notification.component.scss']
})
export class SuggestionsNotificationComponent implements OnInit {
labelPrefix = 'mydspace.';
/**
* The user suggestion targets.
*/
suggestionsRD$: Observable<OpenaireSuggestionTarget[]>;
constructor(
private translateService: TranslateService,
private reciterSuggestionStateService: SuggestionTargetsStateService,
private notificationsService: NotificationsService,
private suggestionsService: SuggestionsService
) { }
ngOnInit() {
this.suggestionsRD$ = this.reciterSuggestionStateService.getCurrentUserSuggestionTargets();
}
/**
* Interpolated params to build the notification suggestions notification.
* @param suggestionTarget
*/
public getNotificationSuggestionInterpolation(suggestionTarget: OpenaireSuggestionTarget): any {
return this.suggestionsService.getNotificationSuggestionInterpolation(suggestionTarget);
}
}

View File

@@ -0,0 +1,79 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { SuggestionsPopupComponent } from './suggestions-popup.component';
import { TranslateModule } from '@ngx-translate/core';
import { SuggestionTargetsStateService } from '../suggestion-targets/suggestion-targets.state.service';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { NotificationsServiceStub } from '../../../shared/testing/notifications-service.stub';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { of as observableOf } from 'rxjs';
import { mockSuggestionTargetsObjectOne } from '../../../shared/mocks/reciter-suggestion-targets.mock';
import { SuggestionsService } from '../suggestions.service';
describe('SuggestionsPopupComponent', () => {
let component: SuggestionsPopupComponent;
let fixture: ComponentFixture<SuggestionsPopupComponent>;
const suggestionStateService = jasmine.createSpyObj('SuggestionTargetsStateService', {
hasUserVisitedSuggestions: jasmine.createSpy('hasUserVisitedSuggestions'),
getCurrentUserSuggestionTargets: jasmine.createSpy('getCurrentUserSuggestionTargets'),
dispatchMarkUserSuggestionsAsVisitedAction: jasmine.createSpy('dispatchMarkUserSuggestionsAsVisitedAction')
});
const mockNotificationInterpolation = { count: 12, source: 'source', suggestionId: 'id', displayName: 'displayName' };
const suggestionService = jasmine.createSpyObj('SuggestionService', {
getNotificationSuggestionInterpolation:
jasmine.createSpy('getNotificationSuggestionInterpolation').and.returnValue(mockNotificationInterpolation)
});
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [TranslateModule.forRoot()],
declarations: [ SuggestionsPopupComponent ],
providers: [
{ provide: SuggestionTargetsStateService, useValue: suggestionStateService },
{ provide: SuggestionsService, useValue: suggestionService },
{ provide: NotificationsService, useValue: new NotificationsServiceStub() },
],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
describe('should create', () => {
beforeEach(() => {
fixture = TestBed.createComponent(SuggestionsPopupComponent);
component = fixture.componentInstance;
spyOn(component, 'initializePopup').and.returnValue(null);
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
expect(component.initializePopup).toHaveBeenCalled();
});
});
describe('when there are publication suggestions', () => {
beforeEach(() => {
suggestionStateService.hasUserVisitedSuggestions.and.returnValue(observableOf(false));
suggestionStateService.getCurrentUserSuggestionTargets.and.returnValue(observableOf([mockSuggestionTargetsObjectOne]));
suggestionStateService.dispatchMarkUserSuggestionsAsVisitedAction.and.returnValue(observableOf(null));
fixture = TestBed.createComponent(SuggestionsPopupComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should show a notification when new publication suggestions are available', () => {
expect((component as any).notificationsService.success).toHaveBeenCalled();
expect(suggestionStateService.dispatchMarkUserSuggestionsAsVisitedAction).toHaveBeenCalled();
});
});
});

View File

@@ -0,0 +1,67 @@
import { Component, OnDestroy, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { SuggestionTargetsStateService } from '../suggestion-targets/suggestion-targets.state.service';
import { NotificationsService } from '../../../shared/notifications/notifications.service';
import { SuggestionsService } from '../suggestions.service';
import { takeUntil } from 'rxjs/operators';
import { OpenaireSuggestionTarget } from '../../../core/openaire/reciter-suggestions/models/openaire-suggestion-target.model';
import { isNotEmpty } from '../../../shared/empty.util';
import { combineLatest, Subject } from 'rxjs';
@Component({
selector: 'ds-suggestions-popup',
templateUrl: './suggestions-popup.component.html',
styleUrls: ['./suggestions-popup.component.scss']
})
export class SuggestionsPopupComponent implements OnInit, OnDestroy {
labelPrefix = 'mydspace.';
subscription;
constructor(
private translateService: TranslateService,
private reciterSuggestionStateService: SuggestionTargetsStateService,
private notificationsService: NotificationsService,
private suggestionsService: SuggestionsService
) { }
ngOnInit() {
this.initializePopup();
}
public initializePopup() {
const notifier = new Subject();
this.subscription = combineLatest([
this.reciterSuggestionStateService.getCurrentUserSuggestionTargets(),
this.reciterSuggestionStateService.hasUserVisitedSuggestions()
]).pipe(takeUntil(notifier)).subscribe(([suggestions, visited]) => {
if (isNotEmpty(suggestions)) {
if (!visited) {
suggestions.forEach((suggestionTarget: OpenaireSuggestionTarget) => this.showNotificationForNewSuggestions(suggestionTarget));
this.reciterSuggestionStateService.dispatchMarkUserSuggestionsAsVisitedAction();
notifier.next();
notifier.complete();
}
}
});
}
/**
* Show a notification to user for a new suggestions detected
* @param suggestionTarget
* @private
*/
private showNotificationForNewSuggestions(suggestionTarget: OpenaireSuggestionTarget): void {
const content = this.translateService.instant(this.labelPrefix + 'notification.suggestion',
this.suggestionsService.getNotificationSuggestionInterpolation(suggestionTarget));
this.notificationsService.success('', content, {timeOut:0}, true);
}
ngOnDestroy() {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
}

View File

@@ -0,0 +1,296 @@
import { Injectable } from '@angular/core';
import { of, forkJoin, Observable } from 'rxjs';
import { catchError, map, mergeMap, take } from 'rxjs/operators';
import { OpenaireSuggestionsDataService } from '../../core/openaire/reciter-suggestions/openaire-suggestions-data.service';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { FindListOptions } from '../../core/data/request.models';
import { RemoteData } from '../../core/data/remote-data';
import { PaginatedList } from '../../core/data/paginated-list.model';
import { OpenaireSuggestionTarget } from '../../core/openaire/reciter-suggestions/models/openaire-suggestion-target.model';
import { ResearcherProfileService } from '../../core/profile/researcher-profile.service';
import { AuthService } from '../../core/auth/auth.service';
import { EPerson } from '../../core/eperson/models/eperson.model';
import { hasValue, isNotEmpty } from '../../shared/empty.util';
import { ResearcherProfile } from '../../core/profile/model/researcher-profile.model';
import {
getAllSucceededRemoteDataPayload,
getFinishedRemoteData,
getFirstSucceededRemoteDataPayload,
getFirstSucceededRemoteListPayload
} from '../../core/shared/operators';
import { OpenaireSuggestion } from '../../core/openaire/reciter-suggestions/models/openaire-suggestion.model';
import { WorkspaceitemDataService } from '../../core/submission/workspaceitem-data.service';
import { TranslateService } from '@ngx-translate/core';
import { NoContent } from '../../core/shared/NoContent.model';
import { environment } from '../../../environments/environment';
import { SuggestionConfig } from '../../../config/layout-config.interfaces';
import { WorkspaceItem } from '../../core/submission/models/workspaceitem.model';
export interface SuggestionBulkResult {
success: number;
fails: number;
}
/**
* The service handling all Suggestion Target requests to the REST service.
*/
@Injectable()
export class SuggestionsService {
/**
* Initialize the service variables.
* @param {AuthService} authService
* @param {ResearcherProfileService} researcherProfileService
* @param {OpenaireSuggestionsDataService} suggestionsDataService
*/
constructor(
private authService: AuthService,
private researcherProfileService: ResearcherProfileService,
private suggestionsDataService: OpenaireSuggestionsDataService,
private translateService: TranslateService
) {
}
/**
* Return the list of Suggestion Target managing pagination and errors.
*
* @param source
* The source for which to retrieve targets
* @param elementsPerPage
* The number of the target per page
* @param currentPage
* The page number to retrieve
* @return Observable<PaginatedList<OpenaireReciterSuggestionTarget>>
* The list of Suggestion Targets.
*/
public getTargets(source, elementsPerPage, currentPage): Observable<PaginatedList<OpenaireSuggestionTarget>> {
const sortOptions = new SortOptions('display', SortDirection.ASC);
const findListOptions: FindListOptions = {
elementsPerPage: elementsPerPage,
currentPage: currentPage,
sort: sortOptions
};
return this.suggestionsDataService.getTargets(source, findListOptions).pipe(
getFinishedRemoteData(),
take(1),
map((rd: RemoteData<PaginatedList<OpenaireSuggestionTarget>>) => {
if (rd.hasSucceeded) {
return rd.payload;
} else {
throw new Error('Can\'t retrieve Suggestion Target from the Search Target REST service');
}
})
);
}
/**
* Return the list of review suggestions Target managing pagination and errors.
*
* @param targetId
* The target id for which to find suggestions.
* @param elementsPerPage
* The number of the target per page
* @param currentPage
* The page number to retrieve
* @param sortOptions
* The sort options
* @return Observable<RemoteData<PaginatedList<OpenaireSuggestion>>>
* The list of Suggestion.
*/
public getSuggestions(targetId: string, elementsPerPage, currentPage, sortOptions: SortOptions): Observable<PaginatedList<OpenaireSuggestion>> {
const [source, target] = targetId.split(':');
const findListOptions: FindListOptions = {
elementsPerPage: elementsPerPage,
currentPage: currentPage,
sort: sortOptions
};
return this.suggestionsDataService.getSuggestionsByTargetAndSource(target, source, findListOptions).pipe(
getAllSucceededRemoteDataPayload()
);
}
/**
* Clear suggestions requests from cache
*/
public clearSuggestionRequests() {
this.suggestionsDataService.clearSuggestionRequests();
}
/**
* Used to delete Suggestion
* @suggestionId
*/
public deleteReviewedSuggestion(suggestionId: string): Observable<RemoteData<NoContent>> {
return this.suggestionsDataService.deleteSuggestion(suggestionId).pipe(
map((response: RemoteData<NoContent>) => {
if (response.isSuccess) {
return response;
} else {
throw new Error('Can\'t delete Suggestion from the Search Target REST service');
}
}),
take(1)
);
}
/**
* Retrieve suggestion targets for the given user
*
* @param user
* The EPerson object for which to retrieve suggestion targets
*/
public retrieveCurrentUserSuggestions(user: EPerson): Observable<OpenaireSuggestionTarget[]> {
return this.researcherProfileService.findById(user.uuid).pipe(
mergeMap((profile: ResearcherProfile) => {
if (isNotEmpty(profile)) {
return this.researcherProfileService.findRelatedItemId(profile).pipe(
mergeMap((itemId: string) => {
return this.suggestionsDataService.getTargetsByUser(itemId).pipe(
getFirstSucceededRemoteListPayload()
);
})
);
} else {
return of([]);
}
}),
take(1)
);
}
/**
* Perform the approve and import operation over a single suggestion
* @param suggestion target suggestion
* @param collectionId the collectionId
* @param workspaceitemService injected dependency
* @private
*/
public approveAndImport(workspaceitemService: WorkspaceitemDataService,
suggestion: OpenaireSuggestion,
collectionId: string): Observable<WorkspaceItem> {
const resolvedCollectionId = this.resolveCollectionId(suggestion, collectionId);
return workspaceitemService.importExternalSourceEntry(suggestion.externalSourceUri, resolvedCollectionId)
.pipe(
getFirstSucceededRemoteDataPayload(),
catchError((error) => of(null))
);
}
/**
* Perform the delete operation over a single suggestion.
* @param suggestionId
*/
public notMine(suggestionId): Observable<RemoteData<NoContent>> {
return this.deleteReviewedSuggestion(suggestionId).pipe(
catchError((error) => of(null))
);
}
/**
* Perform a bulk approve and import operation.
* @param workspaceitemService injected dependency
* @param suggestions the array containing the suggestions
* @param collectionId the collectionId
*/
public approveAndImportMultiple(workspaceitemService: WorkspaceitemDataService,
suggestions: OpenaireSuggestion[],
collectionId: string): Observable<SuggestionBulkResult> {
return forkJoin(suggestions.map((suggestion: OpenaireSuggestion) =>
this.approveAndImport(workspaceitemService, suggestion, collectionId)))
.pipe(map((results: WorkspaceItem[]) => {
return {
success: results.filter((result) => result != null).length,
fails: results.filter((result) => result == null).length
};
}), take(1));
}
/**
* Perform a bulk notMine operation.
* @param suggestions the array containing the suggestions
*/
public notMineMultiple(suggestions: OpenaireSuggestion[]): Observable<SuggestionBulkResult> {
return forkJoin(suggestions.map((suggestion: OpenaireSuggestion) => this.notMine(suggestion.id)))
.pipe(map((results: RemoteData<NoContent>[]) => {
return {
success: results.filter((result) => result != null).length,
fails: results.filter((result) => result == null).length
};
}), take(1));
}
/**
* Get the researcher uuid (for navigation purpose) from a target instance.
* TODO Find a better way
* @param target
* @return the researchUuid
*/
public getTargetUuid(target: OpenaireSuggestionTarget): string {
const tokens = target.id.split(':');
return tokens.length === 2 ? tokens[1] : null;
}
/**
* Interpolated params to build the notification suggestions notification.
* @param suggestionTarget
*/
public getNotificationSuggestionInterpolation(suggestionTarget: OpenaireSuggestionTarget): any {
return {
count: suggestionTarget.total,
source: this.translateService.instant(this.translateSuggestionSource(suggestionTarget.source)),
type: this.translateService.instant(this.translateSuggestionType(suggestionTarget.source)),
suggestionId: suggestionTarget.id,
displayName: suggestionTarget.display
};
}
public translateSuggestionType(source: string): string {
return 'reciter.suggestion.type.' + source;
}
public translateSuggestionSource(source: string): string {
return 'reciter.suggestion.source.' + source;
}
/**
* If the provided collectionId ha no value, tries to resolve it by suggestion source.
* @param suggestion
* @param collectionId
*/
public resolveCollectionId(suggestion: OpenaireSuggestion, collectionId): string {
if (hasValue(collectionId)) {
return collectionId;
}
return environment.suggestion
.find((suggestionConf: SuggestionConfig) => suggestionConf.source === suggestion.source)
.collectionId;
}
/**
* Return true if all the suggestion are configured with the same fixed collection
* in the configuration.
* @param suggestions
*/
public isCollectionFixed(suggestions: OpenaireSuggestion[]): boolean {
return this.getFixedCollectionIds(suggestions).length === 1;
}
private getFixedCollectionIds(suggestions: OpenaireSuggestion[]): string[] {
const collectionIds = {};
suggestions.forEach((suggestion: OpenaireSuggestion) => {
const conf = environment.suggestion.find((suggestionConf: SuggestionConfig) => suggestionConf.source === suggestion.source);
if (hasValue(conf)) {
collectionIds[conf.collectionId] = true;
}
});
return Object.keys(collectionIds);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,42 @@
import { ResourceType } from '../../core/shared/resource-type';
import { OpenaireSuggestionTarget } from '../../core/openaire/reciter-suggestions/models/openaire-suggestion-target.model';
// REST Mock ---------------------------------------------------------------------
// -------------------------------------------------------------------------------
export const mockSuggestionTargetsObjectOne: OpenaireSuggestionTarget = {
type: new ResourceType('suggestiontarget'),
id: 'reciter:gf3d657-9d6d-4a87-b905-fef0f8cae26',
display: 'Bollini, Andrea',
source: 'reciter',
total: 31,
_links: {
target: {
href: 'https://rest.api/rest/api/core/items/gf3d657-9d6d-4a87-b905-fef0f8cae26'
},
suggestions: {
href: 'https://rest.api/rest/api/integration/suggestions/search/findByTargetAndSource?target=gf3d657-9d6d-4a87-b905-fef0f8cae26c&source=reciter'
},
self: {
href: 'https://rest.api/rest/api/integration/suggestiontargets/reciter:gf3d657-9d6d-4a87-b905-fef0f8cae26'
}
}
};
export const mockSuggestionTargetsObjectTwo: OpenaireSuggestionTarget = {
type: new ResourceType('suggestiontarget'),
id: 'reciter:nhy567-9d6d-ty67-b905-fef0f8cae26',
display: 'Digilio, Andrea',
source: 'reciter',
total: 12,
_links: {
target: {
href: 'https://rest.api/rest/api/core/items/nhy567-9d6d-ty67-b905-fef0f8cae26'
},
suggestions: {
href: 'https://rest.api/rest/api/integration/suggestions/search/findByTargetAndSource?target=nhy567-9d6d-ty67-b905-fef0f8cae26&source=reciter'
},
self: {
href: 'https://rest.api/rest/api/integration/suggestiontargets/reciter:nhy567-9d6d-ty67-b905-fef0f8cae26'
}
}
};

View File

@@ -0,0 +1,210 @@
// REST Mock ---------------------------------------------------------------------
// -------------------------------------------------------------------------------
import { OpenaireSuggestion } from '../../core/openaire/reciter-suggestions/models/openaire-suggestion.model';
import { SUGGESTION } from '../../core/openaire/reciter-suggestions/models/openaire-suggestion-objects.resource-type';
export const mockSuggestionPublicationOne: OpenaireSuggestion = {
id: '24694772',
display: 'publication one',
source: 'reciter',
externalSourceUri: 'https://dspace7.4science.cloud/server/api/integration/reciterSourcesEntry/pubmed/entryValues/24694772',
score: '48',
evidences: {
acceptedRejectedEvidence: {
score: '2.7',
notes: 'some notes, eventually empty or null'
},
authorNameEvidence: {
score: '0',
notes: 'some notes, eventually empty or null'
},
journalCategoryEvidence: {
score: '6',
notes: 'some notes, eventually empty or null'
},
affiliationEvidence: {
score: 'xxx',
notes: 'some notes, eventually empty or null'
},
relationshipEvidence: {
score: '9',
notes: 'some notes, eventually empty or null'
},
educationYearEvidence: {
score: '3.6',
notes: 'some notes, eventually empty or null'
},
personTypeEvidence: {
score: '4',
notes: 'some notes, eventually empty or null'
},
articleCountEvidence: {
score: '6.7',
notes: 'some notes, eventually empty or null'
},
averageClusteringEvidence: {
score: '7',
notes: 'some notes, eventually empty or null'
}
},
metadata: {
'dc.identifier.uri': [
{
value: 'https://publication/0000-0003-3681-2038',
language: null,
authority: null,
confidence: -1,
place: -1
} as any
],
'dc.title': [
{
value: 'publication one',
language: null,
authority: null,
confidence: -1
} as any
],
'dc.date.issued': [
{
value: '2010-11-03',
language: null,
authority: null,
confidence: -1
} as any
],
'dspace.entity.type': [
{
uuid: '95f21fe6-ce38-43d6-96d4-60ae66385a06',
language: null,
value: 'OrgUnit',
place: 0,
authority: null,
confidence: -1
} as any
],
'dc.description': [
{
uuid: '95f21fe6-ce38-43d6-96d4-60ae66385a06',
language: null,
value: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).",
place: 0,
authority: null,
confidence: -1
} as any
]
},
type: SUGGESTION,
_links: {
target: {
href: 'https://dspace7.4science.cloud/server/api/core/items/gf3d657-9d6d-4a87-b905-fef0f8cae26'
},
self: {
href: 'https://dspace7.4science.cloud/server/api/integration/suggestions/reciter:gf3d657-9d6d-4a87-b905-fef0f8cae26c:24694772'
}
}
};
export const mockSuggestionPublicationTwo: OpenaireSuggestion = {
id: '24694772',
display: 'publication two',
source: 'reciter',
externalSourceUri: 'https://dspace7.4science.cloud/server/api/integration/reciterSourcesEntry/pubmed/entryValues/24694772',
score: '48',
evidences: {
acceptedRejectedEvidence: {
score: '2.7',
notes: 'some notes, eventually empty or null'
},
authorNameEvidence: {
score: '0',
notes: 'some notes, eventually empty or null'
},
journalCategoryEvidence: {
score: '6',
notes: 'some notes, eventually empty or null'
},
affiliationEvidence: {
score: 'xxx',
notes: 'some notes, eventually empty or null'
},
relationshipEvidence: {
score: '9',
notes: 'some notes, eventually empty or null'
},
educationYearEvidence: {
score: '3.6',
notes: 'some notes, eventually empty or null'
},
personTypeEvidence: {
score: '4',
notes: 'some notes, eventually empty or null'
},
articleCountEvidence: {
score: '6.7',
notes: 'some notes, eventually empty or null'
},
averageClusteringEvidence: {
score: '7',
notes: 'some notes, eventually empty or null'
}
},
metadata: {
'dc.identifier.uri': [
{
value: 'https://publication/0000-0003-3681-2038',
language: null,
authority: null,
confidence: -1,
place: -1
} as any
],
'dc.title': [
{
value: 'publication one',
language: null,
authority: null,
confidence: -1
} as any
],
'dc.date.issued': [
{
value: '2010-11-03',
language: null,
authority: null,
confidence: -1
} as any
],
'dspace.entity.type': [
{
uuid: '95f21fe6-ce38-43d6-96d4-60ae66385a06',
language: null,
value: 'OrgUnit',
place: 0,
authority: null,
confidence: -1
} as any
],
'dc.description': [
{
uuid: '95f21fe6-ce38-43d6-96d4-60ae66385a06',
language: null,
value: "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).",
place: 0,
authority: null,
confidence: -1
} as any
]
},
type: SUGGESTION,
_links: {
target: {
href: 'https://dspace7.4science.cloud/server/api/core/items/gf3d657-9d6d-4a87-b905-fef0f8cae26'
},
self: {
href: 'https://dspace7.4science.cloud/server/api/integration/suggestions/reciter:gf3d657-9d6d-4a87-b905-fef0f8cae26c:24694772'
}
}
};

View File

@@ -0,0 +1,11 @@
import { URLCombiner } from '../core/url-combiner/url-combiner';
export const SUGGESTION_MODULE_PATH = 'suggestions';
export function getSuggestionModuleRoute() {
return `/${SUGGESTION_MODULE_PATH}`;
}
export function getSuggestionPageRoute(SuggestionId: string) {
return new URLCombiner(getSuggestionModuleRoute(), SuggestionId).toString();
}

View File

@@ -0,0 +1,36 @@
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { SuggestionsPageResolver } from './suggestions-page.resolver';
import { SuggestionsPageComponent } from './suggestions-page.component';
import { AuthenticatedGuard } from '../core/auth/authenticated.guard';
import { I18nBreadcrumbResolver } from '../core/breadcrumbs/i18n-breadcrumb.resolver';
import { SiteAdministratorGuard } from '../core/data/feature-authorization/feature-authorization-guard/site-administrator.guard';
@NgModule({
imports: [
RouterModule.forChild([
{
path: ':targetId',
resolve: {
suggestionTargets: SuggestionsPageResolver,
breadcrumb: I18nBreadcrumbResolver
},
data: {
title: 'admin.notifications.recitersuggestion.page.title',
breadcrumbKey: 'admin.notifications.recitersuggestion',
showBreadcrumbsFluid: false
},
canActivate: [AuthenticatedGuard],
runGuardsAndResolvers: 'always',
component: SuggestionsPageComponent,
},
])
],
providers: [
SuggestionsPageResolver
]
})
export class SuggestionsPageRoutingModule {
}

View File

@@ -0,0 +1,48 @@
<div class="container">
<div class="row">
<div class="col-12">
<ng-container *ngVar="(suggestionsRD$ | async) as suggestionsRD">
<div *ngIf="suggestionsRD?.pageInfo?.totalElements > 0">
<h2>
{{ translateSuggestionType() | translate }}
{{'reciter.suggestion.suggestionFor' | translate}}
<a target="_blank" [routerLink]="['/items', researcherUuid]">{{researcherName}}</a>
{{'reciter.suggestion.from.source' | translate}} {{ translateSuggestionSource() | translate }}
</h2>
<div class="mb-3 mt-3">
<button class="btn btn-light" (click)="onToggleSelectAll(suggestionsRD.page)">Select / Deselect All</button>
<em>({{ getSelectedSuggestionsCount() }})</em>
<ds-suggestion-actions *ngIf="getSelectedSuggestionsCount() > 0"
class="mt-2 ml-2"
[isBulk]="true"
[isCollectionFixed]="isCollectionFixed(suggestionsRD.page)"
(approveAndImport)="approveAndImportAllSelected($event)"
(notMineClicked)="notMineAllSelected()"></ds-suggestion-actions>
<i class='fas fa-circle-notch fa-spin' *ngIf="isBulkOperationPending"></i>
</div>
<ds-loading *ngIf="(processing$ | async)"></ds-loading>
<ds-pagination *ngIf="!(processing$ | async)"
[paginationOptions]="paginationOptions"
[sortOptions]="paginationSortConfig"
[collectionSize]="suggestionsRD?.pageInfo?.totalElements" [hideGear]="false"
[hidePagerWhenSinglePage]="false" [hidePaginationDetail]="false"
(paginationChange)="onPaginationChange()">
<ul class="list-unstyled">
<li *ngFor="let object of suggestionsRD?.page; let i = index; let last = last" class="mt-4 mb-4">
<ds-suggestion-list-item
[object]="object"
[isSelected]="selectedSuggestions[object.id]"
[isCollectionFixed]="isCollectionFixed([object])"
(notMineClicked)="notMine($event)"
(selected)="onSelected(object, $event)"
(approveAndImport)="approveAndImport($event)"></ds-suggestion-list-item>
</li>
</ul>
</ds-pagination>
</div>
</ng-container>
</div>
</div>
</div>

View File

@@ -0,0 +1,107 @@
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { TranslateModule, TranslateService } from '@ngx-translate/core';
import { of as observableOf } from 'rxjs';
import { SuggestionsPageComponent } from './suggestions-page.component';
import { SuggestionListElementComponent } from '../openaire/reciter-suggestions/suggestion-list-element/suggestion-list-element.component';
import { SuggestionsService } from '../openaire/reciter-suggestions/suggestions.service';
import { getMockOpenaireStateService, getMockSuggestionsService } from '../shared/mocks/openaire.mock';
import { buildPaginatedList, PaginatedList } from '../core/data/paginated-list.model';
import { OpenaireSuggestion } from '../core/openaire/reciter-suggestions/models/openaire-suggestion.model';
import { mockSuggestionPublicationOne, mockSuggestionPublicationTwo } from '../shared/mocks/reciter-suggestion.mock';
import { SuggestionEvidencesComponent } from '../openaire/reciter-suggestions/suggestion-list-element/suggestion-evidences/suggestion-evidences.component';
import { ObjectKeysPipe } from '../shared/utils/object-keys-pipe';
import { VarDirective } from '../shared/utils/var.directive';
import { ActivatedRoute, Router } from '@angular/router';
import { RouterStub } from '../shared/testing/router.stub';
import { mockSuggestionTargetsObjectOne } from '../shared/mocks/reciter-suggestion-targets.mock';
import { AuthService } from '../core/auth/auth.service';
import { NotificationsService } from '../shared/notifications/notifications.service';
import { NotificationsServiceStub } from '../shared/testing/notifications-service.stub';
import { getMockTranslateService } from '../shared/mocks/translate.service.mock';
import { SuggestionTargetsStateService } from '../openaire/reciter-suggestions/suggestion-targets/suggestion-targets.state.service';
import { WorkspaceitemDataService } from '../core/submission/workspaceitem-data.service';
import { createSuccessfulRemoteDataObject } from '../shared/remote-data.utils';
import { PageInfo } from '../core/shared/page-info.model';
import { TestScheduler } from 'rxjs/testing';
import { getTestScheduler } from 'jasmine-marbles';
import { PaginationServiceStub } from '../shared/testing/pagination-service.stub';
import { PaginationService } from '../core/pagination/pagination.service';
describe('SuggestionPageComponent', () => {
let component: SuggestionsPageComponent;
let fixture: ComponentFixture<SuggestionsPageComponent>;
let scheduler: TestScheduler;
const mockSuggestionsService = getMockSuggestionsService();
const mockSuggestionsTargetStateService = getMockOpenaireStateService();
const suggestionTargetsList: PaginatedList<OpenaireSuggestion> = buildPaginatedList(new PageInfo(), [mockSuggestionPublicationOne, mockSuggestionPublicationTwo]);
const router = new RouterStub();
const routeStub = {
data: observableOf({
suggestionTargets: createSuccessfulRemoteDataObject(mockSuggestionTargetsObjectOne)
}),
queryParams: observableOf({})
};
const workspaceitemServiceMock = jasmine.createSpyObj('WorkspaceitemDataService', {
importExternalSourceEntry: jasmine.createSpy('importExternalSourceEntry')
});
const authService = jasmine.createSpyObj('authService', {
isAuthenticated: observableOf(true),
setRedirectUrl: {}
});
const paginationService = new PaginationServiceStub();
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
BrowserModule,
CommonModule,
TranslateModule.forRoot()
],
declarations: [
SuggestionEvidencesComponent,
SuggestionListElementComponent,
SuggestionsPageComponent,
ObjectKeysPipe,
VarDirective
],
providers: [
{ provide: AuthService, useValue: authService },
{ provide: ActivatedRoute, useValue: routeStub },
{ provide: WorkspaceitemDataService, useValue: workspaceitemServiceMock },
{ provide: Router, useValue: router },
{ provide: SuggestionsService, useValue: mockSuggestionsService },
{ provide: SuggestionTargetsStateService, useValue: mockSuggestionsTargetStateService },
{ provide: NotificationsService, useValue: new NotificationsServiceStub() },
{ provide: TranslateService, useValue: getMockTranslateService() },
{ provide: PaginationService, useValue: paginationService },
SuggestionsPageComponent
],
schemas: [NO_ERRORS_SCHEMA]
})
.compileComponents().then();
}));
beforeEach(() => {
fixture = TestBed.createComponent(SuggestionsPageComponent);
component = fixture.componentInstance;
scheduler = getTestScheduler();
});
it('should create', () => {
spyOn(component, 'updatePage').and.stub();
scheduler.schedule(() => fixture.detectChanges());
scheduler.flush();
expect(component).toBeTruthy();
expect(component.suggestionId).toBe(mockSuggestionTargetsObjectOne.id);
expect(component.researcherName).toBe(mockSuggestionTargetsObjectOne.display);
expect(component.updatePage).toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,285 @@
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Data, Router } from '@angular/router';
import { BehaviorSubject, combineLatest, Observable } from 'rxjs';
import { distinctUntilChanged, map, switchMap, take } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';
import { SortDirection, SortOptions, } from '../core/cache/models/sort-options.model';
import { PaginatedList } from '../core/data/paginated-list.model';
import { RemoteData } from '../core/data/remote-data';
import { getFirstSucceededRemoteDataPayload, redirectOn4xx } from '../core/shared/operators';
import { SuggestionBulkResult, SuggestionsService } from '../openaire/reciter-suggestions/suggestions.service';
import { PaginationComponentOptions } from '../shared/pagination/pagination-component-options.model';
import { OpenaireSuggestion } from '../core/openaire/reciter-suggestions/models/openaire-suggestion.model';
import { OpenaireSuggestionTarget } from '../core/openaire/reciter-suggestions/models/openaire-suggestion-target.model';
import { AuthService } from '../core/auth/auth.service';
import { SuggestionApproveAndImport } from '../openaire/reciter-suggestions/suggestion-list-element/suggestion-list-element.component';
import { NotificationsService } from '../shared/notifications/notifications.service';
import { SuggestionTargetsStateService } from '../openaire/reciter-suggestions/suggestion-targets/suggestion-targets.state.service';
import { WorkspaceitemDataService } from '../core/submission/workspaceitem-data.service';
import { PaginationService } from '../core/pagination/pagination.service';
import { FindListOptions } from '../core/data/request.models';
import { WorkspaceItem } from '../core/submission/models/workspaceitem.model';
@Component({
selector: 'ds-suggestion-page',
templateUrl: './suggestions-page.component.html',
styleUrls: ['./suggestions-page.component.scss'],
})
export class SuggestionsPageComponent implements OnInit {
/**
* The pagination configuration
*/
paginationOptions: PaginationComponentOptions = Object.assign(new PaginationComponentOptions(), {
id: 'sp',
pageSizeOptions: [5, 10, 20, 40, 60]
});
/**
* The sorting configuration
*/
paginationSortConfig: SortOptions = new SortOptions('trust', SortDirection.DESC);
/**
* The FindListOptions object
*/
defaultConfig: FindListOptions = Object.assign(new FindListOptions(), {sort: this.paginationSortConfig});
/**
* A boolean representing if results are loading
*/
public processing$ = new BehaviorSubject<boolean>(false);
/**
* A list of remote data objects of suggestions
*/
suggestionsRD$: BehaviorSubject<PaginatedList<OpenaireSuggestion>> = new BehaviorSubject<PaginatedList<OpenaireSuggestion>>({} as any);
targetRD$: Observable<RemoteData<OpenaireSuggestionTarget>>;
targetId$: Observable<string>;
suggestionTarget: OpenaireSuggestionTarget;
suggestionId: any;
suggestionSource: any;
researcherName: any;
researcherUuid: any;
selectedSuggestions: { [id: string]: OpenaireSuggestion } = {};
isBulkOperationPending = false;
constructor(
private authService: AuthService,
private notificationService: NotificationsService,
private paginationService: PaginationService,
private route: ActivatedRoute,
private router: Router,
private suggestionService: SuggestionsService,
private suggestionTargetsStateService: SuggestionTargetsStateService,
private translateService: TranslateService,
private workspaceItemService: WorkspaceitemDataService
) {
}
ngOnInit(): void {
this.targetRD$ = this.route.data.pipe(
map((data: Data) => data.suggestionTargets as RemoteData<OpenaireSuggestionTarget>),
redirectOn4xx(this.router, this.authService)
);
this.targetId$ = this.targetRD$.pipe(
getFirstSucceededRemoteDataPayload(),
map((target: OpenaireSuggestionTarget) => target.id)
);
this.targetRD$.pipe(
getFirstSucceededRemoteDataPayload()
).subscribe((suggestionTarget: OpenaireSuggestionTarget) => {
this.suggestionTarget = suggestionTarget;
this.suggestionId = suggestionTarget.id;
this.researcherName = suggestionTarget.display;
this.suggestionSource = suggestionTarget.source;
this.researcherUuid = this.suggestionService.getTargetUuid(suggestionTarget);
this.updatePage();
});
this.suggestionTargetsStateService.dispatchMarkUserSuggestionsAsVisitedAction();
}
/**
* Called when one of the pagination settings is changed
*/
onPaginationChange() {
this.updatePage();
}
/**
* Update the list of suggestions
*/
updatePage() {
this.processing$.next(true);
const pageConfig$: Observable<FindListOptions> = this.paginationService.getFindListOptions(
this.paginationOptions.id,
this.defaultConfig,
).pipe(
distinctUntilChanged()
);
combineLatest([this.targetId$, pageConfig$]).pipe(
switchMap(([targetId, config]: [string, FindListOptions]) => {
return this.suggestionService.getSuggestions(
targetId,
config.elementsPerPage,
config.currentPage,
config.sort
);
}),
take(1)
).subscribe((results: PaginatedList<OpenaireSuggestion>) => {
this.processing$.next(false);
this.suggestionsRD$.next(results);
this.suggestionService.clearSuggestionRequests();
// navigate to the mydspace if no suggestions remains
// if (results.totalElements === 0) {
// const content = this.translateService.instant('reciter.suggestion.empty',
// this.suggestionService.getNotificationSuggestionInterpolation(this.suggestionTarget));
// this.notificationService.success('', content, {timeOut:0}, true);
// TODO if the target is not the current use route to the suggestion target page
// this.router.navigate(['/mydspace']);
// }
});
}
/**
* Used to delete a suggestion.
* @suggestionId
*/
notMine(suggestionId) {
this.suggestionService.notMine(suggestionId).subscribe((res) => {
this.suggestionTargetsStateService.dispatchRefreshUserSuggestionsAction();
this.updatePage();
});
}
/**
* Used to delete all selected suggestions.
*/
notMineAllSelected() {
this.isBulkOperationPending = true;
this.suggestionService
.notMineMultiple(Object.values(this.selectedSuggestions))
.subscribe((results: SuggestionBulkResult) => {
this.suggestionTargetsStateService.dispatchRefreshUserSuggestionsAction();
this.updatePage();
this.isBulkOperationPending = false;
this.selectedSuggestions = {};
if (results.success > 0) {
this.notificationService.success(
this.translateService.get('reciter.suggestion.notMine.bulk.success',
{count: results.success}));
}
if (results.fails > 0) {
this.notificationService.error(
this.translateService.get('reciter.suggestion.notMine.bulk.error',
{count: results.fails}));
}
});
}
/**
* Used to approve & import.
* @param event contains the suggestion and the target collection
*/
approveAndImport(event: SuggestionApproveAndImport) {
this.suggestionService.approveAndImport(this.workspaceItemService, event.suggestion, event.collectionId)
.subscribe((workspaceitem: WorkspaceItem) => {
const content = this.translateService.instant('reciter.suggestion.approveAndImport.success', { workspaceItemId: workspaceitem.id });
this.notificationService.success('', content, {timeOut:0}, true);
this.suggestionTargetsStateService.dispatchRefreshUserSuggestionsAction();
this.updatePage();
});
}
/**
* Used to approve & import all selected suggestions.
* @param event contains the target collection
*/
approveAndImportAllSelected(event: SuggestionApproveAndImport) {
this.isBulkOperationPending = true;
this.suggestionService
.approveAndImportMultiple(this.workspaceItemService, Object.values(this.selectedSuggestions), event.collectionId)
.subscribe((results: SuggestionBulkResult) => {
this.suggestionTargetsStateService.dispatchRefreshUserSuggestionsAction();
this.updatePage();
this.isBulkOperationPending = false;
this.selectedSuggestions = {};
if (results.success > 0) {
this.notificationService.success(
this.translateService.get('reciter.suggestion.approveAndImport.bulk.success',
{count: results.success}));
}
if (results.fails > 0) {
this.notificationService.error(
this.translateService.get('reciter.suggestion.approveAndImport.bulk.error',
{count: results.fails}));
}
});
}
/**
* When a specific suggestion is selected.
* @param object the suggestions
* @param selected the new selected value for the suggestion
*/
onSelected(object: OpenaireSuggestion, selected: boolean) {
if (selected) {
this.selectedSuggestions[object.id] = object;
} else {
delete this.selectedSuggestions[object.id];
}
}
/**
* When Toggle Select All occurs.
* @param suggestions all the visible suggestions inside the page
*/
onToggleSelectAll(suggestions: OpenaireSuggestion[]) {
if ( this.getSelectedSuggestionsCount() > 0) {
this.selectedSuggestions = {};
} else {
suggestions.forEach((suggestion) => {
this.selectedSuggestions[suggestion.id] = suggestion;
});
}
}
/**
* The current number of selected suggestions.
*/
getSelectedSuggestionsCount(): number {
return Object.keys(this.selectedSuggestions).length;
}
/**
* Return true if all the suggestion are configured with the same fixed collection in the configuration.
* @param suggestions
*/
isCollectionFixed(suggestions: OpenaireSuggestion[]): boolean {
return this.suggestionService.isCollectionFixed(suggestions);
}
/**
* Label to be used to translate the suggestion source.
*/
translateSuggestionSource() {
return this.suggestionService.translateSuggestionSource(this.suggestionSource);
}
/**
* Label to be used to translate the suggestion type.
*/
translateSuggestionType() {
return this.suggestionService.translateSuggestionType(this.suggestionSource);
}
}

View File

@@ -0,0 +1,24 @@
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { SuggestionsPageComponent } from './suggestions-page.component';
import { SharedModule } from '../shared/shared.module';
import { SuggestionsPageRoutingModule } from './suggestions-page-routing.module';
import { SuggestionsService } from '../openaire/reciter-suggestions/suggestions.service';
import { OpenaireSuggestionsDataService } from '../core/openaire/reciter-suggestions/openaire-suggestions-data.service';
import { OpenaireModule } from '../openaire/openaire.module';
@NgModule({
declarations: [SuggestionsPageComponent],
imports: [
CommonModule,
SharedModule,
OpenaireModule,
SuggestionsPageRoutingModule
],
providers: [
OpenaireSuggestionsDataService,
SuggestionsService
]
})
export class SuggestionsPageModule { }

View File

@@ -0,0 +1,32 @@
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { find } from 'rxjs/operators';
import { RemoteData } from '../core/data/remote-data';
import { hasValue } from '../shared/empty.util';
import { OpenaireSuggestionsDataService } from '../core/openaire/reciter-suggestions/openaire-suggestions-data.service';
import { OpenaireSuggestionTarget } from '../core/openaire/reciter-suggestions/models/openaire-suggestion-target.model';
/**
* This class represents a resolver that requests a specific collection before the route is activated
*/
@Injectable()
export class SuggestionsPageResolver implements Resolve<RemoteData<OpenaireSuggestionTarget>> {
constructor(private suggestionsDataService: OpenaireSuggestionsDataService) {
}
/**
* Method for resolving a suggestion target based on the parameters in the current route
* @param {ActivatedRouteSnapshot} route The current ActivatedRouteSnapshot
* @param {RouterStateSnapshot} state The current RouterStateSnapshot
* @returns Observable<<RemoteData<Collection>> Emits the found collection based on the parameters in the current route,
* or an error if something went wrong
*/
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<RemoteData<OpenaireSuggestionTarget>> {
return this.suggestionsDataService.getTargetById(route.params.targetId).pipe(
find((RD) => hasValue(RD.hasFailed) || RD.hasSucceeded),
);
}
}

View File

@@ -27,6 +27,10 @@
"404.page-not-found": "page not found", "404.page-not-found": "page not found",
"admin.notifications.recitersuggestion.breadcrumbs": "Suggestions",
"admin.notifications.recitersuggestion.page.title": "Suggestions",
"admin.curation-tasks.breadcrumbs": "System curation tasks", "admin.curation-tasks.breadcrumbs": "System curation tasks",
"admin.curation-tasks.title": "System curation tasks", "admin.curation-tasks.title": "System curation tasks",
@@ -2511,6 +2515,7 @@
"menu.section.icon.unpin": "Unpin sidebar", "menu.section.icon.unpin": "Unpin sidebar",
"menu.section.icon.notifications": "Notifictions menu section",
"menu.section.import": "Import", "menu.section.import": "Import",
@@ -2533,6 +2538,10 @@
"menu.section.new_process": "Process", "menu.section.new_process": "Process",
"menu.section.notifications": "Notifications",
"menu.section.notifications_reciter": "Publication Claim",
"menu.section.pin": "Pin sidebar", "menu.section.pin": "Pin sidebar",
@@ -2960,6 +2969,62 @@
"media-viewer.playlist": "Playlist", "media-viewer.playlist": "Playlist",
"reciter.suggestion.loading": "Loading ...",
"reciter.suggestion.title": "Suggestions",
"reciter.suggestion.targets.description": "Below you can see all the suggestions ",
"reciter.suggestion.targets": "Current Suggestions",
"reciter.suggestion.table.name": "Researcher Name",
"reciter.suggestion.table.actions": "Actions",
"reciter.suggestion.button.review": "Review {{ total }} suggestion(s)",
"reciter.suggestion.noTargets": "No target found.",
"reciter.suggestion.target.error.service.retrieve": "An error occurred while loading the Suggestion targets",
"reciter.suggestion.evidence.type": "Type",
"reciter.suggestion.evidence.score": "Score",
"reciter.suggestion.evidence.notes": "Notes",
"reciter.suggestion.approveAndImport": "Approve & import",
"reciter.suggestion.approveAndImport.success": "The suggestion has been imported successfully",
"reciter.suggestion.approveAndImport.bulk": "Approve & import Selected",
"reciter.suggestion.approveAndImport.bulk.success": "{{ count }} suggestions have been imported successfully ",
"reciter.suggestion.approveAndImport.bulk.error": "{{ count }} suggestions haven't been imported due to unexpected server errors",
"reciter.suggestion.notMine": "Not mine",
"reciter.suggestion.notMine.success": "The suggestion has been discarded",
"reciter.suggestion.notMine.bulk": "Not mine Selected",
"reciter.suggestion.notMine.bulk.success": "{{ count }} suggestions have been discarded ",
"reciter.suggestion.notMine.bulk.error": "{{ count }} suggestions haven't been discarded due to unexpected server errors",
"reciter.suggestion.seeEvidence": "See evidence",
"reciter.suggestion.hideEvidence": "Hide evidence",
"reciter.suggestion.suggestionFor": "Suggestion for",
"reciter.suggestion.source.oaire": "OpenAIRE Graph",
"reciter.suggestion.from.source": "from the ",
"reciter.suggestion.totalScore": "Total Score",
"register-email.title": "New user registration", "register-email.title": "New user registration",