argos/dmp-frontend/src/app/ui/dashboard/recent-edited-dataset-activity/recent-edited-dataset-activ...

555 lines
20 KiB
TypeScript

import {Component, OnInit, Output, EventEmitter, Input, ViewChild} from '@angular/core';
import { DatasetListingModel } from '@app/core/model/dataset/dataset-listing';
import { DatasetService } from '@app/core/services/dataset/dataset.service';
import { DataTableRequest } from '@app/core/model/data-table/data-table-request';
import { DatasetCriteria } from '@app/core/query/dataset/dataset-criteria';
import { AuthService } from '@app/core/services/auth/auth.service';
import { BaseComponent } from '@common/base/base.component';
import { Principal } from '@app/core/model/auth/principal';
import { TranslateService } from '@ngx-translate/core';
import { EnumUtils } from '@app/core/services/utilities/enum-utils.service';
import { FormControl, FormBuilder } from '@angular/forms';
import { DatasetCopyDialogueComponent } from '@app/ui/dataset/dataset-wizard/dataset-copy-dialogue/dataset-copy-dialogue.component';
import { MatDialog } from '@angular/material/dialog';
import { debounceTime, takeUntil } from 'rxjs/operators';
import {ActivatedRoute, Router} from '@angular/router';
import { DatasetWizardService } from '@app/core/services/dataset-wizard/dataset-wizard.service';
import * as FileSaver from 'file-saver';
import { ConfirmationDialogComponent } from '@common/modules/confirmation-dialog/confirmation-dialog.component';
import { ValidationErrorModel } from '@common/forms/validation/error-model/validation-error-model';
import { UiNotificationService } from '@app/core/services/notification/ui-notification-service';
import { SnackBarNotificationLevel } from '@common/modules/notification/ui-notification-service';
import { DatasetStatus } from '@app/core/common/enum/dataset-status';
import { DmpInvitationDialogComponent } from '@app/ui/dmp/invitation/dmp-invitation-dialog.component';
import { RecentActivityOrder } from '@app/core/common/enum/recent-activity-order';
import { Role } from '@app/core/common/enum/role';
import { Location } from '@angular/common';
import { LockService } from '@app/core/services/lock/lock.service';
import { MatomoService } from '@app/core/services/matomo/matomo-service';
import { HttpClient } from '@angular/common/http';
import {ConfigurationService} from "@app/core/services/configuration/configuration.service";
@Component({
selector: 'app-recent-edited-dataset-activity',
templateUrl: './recent-edited-dataset-activity.component.html',
styleUrls: ['./recent-edited-dataset-activity.component.scss']
})
export class RecentEditedDatasetActivityComponent extends BaseComponent implements OnInit {
@Output() totalCountDatasets: EventEmitter<any> = new EventEmitter();
@ViewChild("datasets") resultsContainer;
datasetActivities: DatasetListingModel[];
totalCount: number;
startIndex: number = 0;
offsetLess: number = 0;
hasMoreResults:boolean = true;
pageSize: number = 5;
public formGroup = new FormBuilder().group({
like: new FormControl(),
order: new FormControl()
});
publicMode = false;
order = RecentActivityOrder;
page: number = 1;
@Input() isActive: boolean = false;
constructor(
private route: ActivatedRoute,
private authentication: AuthService,
private datasetService: DatasetService,
private language: TranslateService,
public enumUtils: EnumUtils,
public dialog: MatDialog,
public router: Router,
private datasetWizardService: DatasetWizardService,
private uiNotificationService: UiNotificationService,
private location: Location,
private lockService: LockService,
private httpClient: HttpClient,
private matomoService: MatomoService,
private configurationService: ConfigurationService
) {
super();
}
ngOnInit() {
this.matomoService.trackPageView('Recent Dataset Activity');
this.route.queryParams.subscribe(params => {
if(this.isActive) {
let page = (params['page'] === undefined) ? 1 : +params['page'];
this.page = (page <= 0) ? 1 : page;
this.startIndex = (this.page-1)*this.pageSize;
if(this.page > 1) {
this.offsetLess = (this.page-2)*this.pageSize;
}
let order = params['order'];
if (this.isAuthenticated()) {
if(order === undefined || (order != this.order.MODIFIED && order != this.order.LABEL && order != this.order.STATUS)) {
order = this.order.MODIFIED;
}
} else {
if(order === undefined || (order != this.order.DATASETPUBLISHED && order != this.order.LABEL)) {
order = this.order.DATASETPUBLISHED;
}
}
this.formGroup.get('order').setValue(order);
let keyword = (params['keyword'] === undefined || params['keyword'].length <= 0) ? "" : params['keyword'];
this.formGroup.get("like").setValue(keyword);
this.updateUrl();
}
});
if (this.isAuthenticated()) {
// const fields: Array<string> = ["-modified"];
if(!this.formGroup.get('order').value) {
this.formGroup.get('order').setValue(this.order.MODIFIED);
}
const fields: Array<string> = [((this.formGroup.get('order').value === 'status') || (this.formGroup.get('order').value === 'label') ? '+' : "-") + this.formGroup.get('order').value];
const datasetDataTableRequest: DataTableRequest<DatasetCriteria> = new DataTableRequest(this.startIndex, this.pageSize, { fields: fields });
datasetDataTableRequest.criteria = new DatasetCriteria();
datasetDataTableRequest.criteria.like = this.formGroup.get('like').value;
this.datasetService
.getPaged(datasetDataTableRequest)
.pipe(takeUntil(this._destroyed))
.subscribe(response => {
this.datasetActivities = response.data;
this.totalCount = response.totalCount;
this.totalCountDatasets.emit(this.datasetActivities.length)
if(this.totalCount > 0 && this.totalCount <= (this.page-1)*this.pageSize && this.page > 1) {
let queryParams = { type: "datasets", page: 1, order: this.formGroup.get("order").value };
if(this.formGroup.get("like").value) {
queryParams['keyword'] = this.formGroup.get("like").value;
}
this.router.navigate(["/home"], { queryParams: queryParams })
}
});
this.formGroup.get('like').valueChanges
.pipe(takeUntil(this._destroyed), debounceTime(500))
.subscribe(x => this.refresh());
this.formGroup.get('order').valueChanges
.pipe(takeUntil(this._destroyed))
.subscribe(x => this.refresh());
} else {
this.publicMode = true;
if(!this.formGroup.get('order').value) {
this.formGroup.get('order').setValue(this.order.DATASETPUBLISHED);
}
const dataTableRequest = this.setPublicDataTableRequest();
this.datasetService.getPaged(dataTableRequest).pipe(takeUntil(this._destroyed)).subscribe(response => {
this.datasetActivities = response.data;
this.totalCount = response.totalCount;
this.totalCountDatasets.emit(this.datasetActivities.length);
if(this.totalCount > 0 && this.totalCount <= (this.page-1)*this.pageSize && this.page > 1) {
let queryParams = { type: "datasets", page: 1, order: this.formGroup.get("order").value };
if(this.formGroup.get("like").value) {
queryParams['keyword'] = this.formGroup.get("like").value;
}
this.router.navigate(["/home"], { queryParams: queryParams })
}
});
this.formGroup.get('like').valueChanges
.pipe(takeUntil(this._destroyed), debounceTime(500))
.subscribe(x => this.refresh());
this.formGroup.get('order').valueChanges
.pipe(takeUntil(this._destroyed))
.subscribe(x => this.refresh());
}
}
ngOnChanges() {
if(this.isActive) {
this.updateUrl();
}
}
updateUrl() {
let parameters = "?type=datasets"+
(this.page != 1 ? "&page="+this.page : "") +
(((this.formGroup.get("order").value != this.order.MODIFIED && !this.publicMode) || (this.formGroup.get("order").value != this.order.DATASETPUBLISHED && this.publicMode)) ? "&order="+this.formGroup.get("order").value : "") +
(this.formGroup.get("like").value ? ("&keyword="+this.formGroup.get("like").value) : "");
this.location.go(this.router.url.split('?')[0]+parameters);
}
setPublicDataTableRequest(fields?: Array<string>, more: boolean = true): DataTableRequest<DatasetCriteria> {
const datasetCriteria = new DatasetCriteria();
datasetCriteria.allVersions = false;
datasetCriteria.isPublic = true;
datasetCriteria.like = this.formGroup.get("like").value ? this.formGroup.get("like").value : "";
if (!fields) {
fields = new Array<string>('-dmp:publishedAt|join|');
}
const dataTableRequest: DataTableRequest<DatasetCriteria> = more ? new DataTableRequest(this.startIndex, this.pageSize, { fields: fields }) : new DataTableRequest(this.offsetLess, this.pageSize, { fields: fields });
dataTableRequest.criteria = datasetCriteria;
return dataTableRequest;
}
refresh(): void {
this.startIndex = 0;
this.page = 1;
this.updateUrl();
const fields: Array<string> = [((this.formGroup.get('order').value === 'status') || (this.formGroup.get('order').value === 'label') ? '+' : "-") + this.formGroup.get('order').value];
const datasetDataTableRequest = this.isAuthenticated() ? new DataTableRequest<DatasetCriteria>(this.startIndex, this.pageSize, { fields: fields }) : this.setPublicDataTableRequest(fields);
if (this.isAuthenticated()) {
datasetDataTableRequest.criteria = new DatasetCriteria();
datasetDataTableRequest.criteria.like = this.formGroup.get("like").value ? this.formGroup.get("like").value : "";
}
this.datasetService
.getPaged(datasetDataTableRequest)
.pipe(takeUntil(this._destroyed))
.subscribe(response => {
this.datasetActivities = response.data;
this.totalCount = response.totalCount;
this.totalCountDatasets.emit(this.datasetActivities.length);
if(response.data.length< this.pageSize) {
this.hasMoreResults = false;
} else {
this.hasMoreResults = true;
}
});
}
public loadNextOrPrevious(more: boolean = true) {
this.startIndex = this.startIndex + this.pageSize;
const fields: Array<string> = [((this.formGroup.get('order').value === 'status') || (this.formGroup.get('order').value === 'label') ? '+' : "-") + this.formGroup.get('order').value];
let request;
this.startIndex = (this.page)*this.pageSize;
if(this.page > 1) {
this.offsetLess = (this.page-2)*this.pageSize;
}
if(this.isAuthenticated()) {
if(more) {
request = new DataTableRequest<DatasetCriteria>(this.startIndex, this.pageSize, { fields: fields });
} else {
request = new DataTableRequest<DatasetCriteria>(this.offsetLess, this.pageSize, { fields: fields });
}
} else {
request = this.setPublicDataTableRequest(fields, more);
}
if (this.isAuthenticated()) {
request.criteria = new DatasetCriteria();
request.criteria.like = this.formGroup.get("like").value ? this.formGroup.get("like").value : "";
}
this.datasetService.getPaged(request).pipe(takeUntil(this._destroyed)).subscribe(result => {
if (!result || !result.data || result.data.length == 0) {
this.hasMoreResults = false;
// return [];
} else {
this.page = this.page + (more ? 1 : -1);
this.updateUrl();
// this.datasetActivities = this.datasetActivities.concat(result.data);
// this.datasetActivities = this.datasetActivities.length > 0 ? this.mergeTwoSortedLists(this.datasetActivities, result.data, this.formGroup.get('order').value) : result.data;
this.datasetActivities = result.data;
if(result.data.length < this.pageSize) {
this.hasMoreResults = false;
} else {
this.hasMoreResults = true;
}
this.totalCountDatasets.emit(this.datasetActivities.length);
if (more) {
this.resultsContainer.nativeElement.scrollIntoView();
}
}
});
}
public isAuthenticated(): boolean {
return !!this.authentication.current();
}
isUserOwner(activity: DatasetListingModel): boolean {
const principal: Principal = this.authentication.current();
if (principal) return !!activity.users.find(x => (x.role === Role.Owner) && (principal.id === x.id));
}
goToOverview(id: string): string[] {
if (this.isAuthenticated()) {
return ['../datasets/overview/' + id];
} else {
return ['../explore/publicOverview', id];
}
}
roleDisplay(value: any) {
const principal: Principal = this.authentication.current();
let role: number;
if (principal) {
value.forEach(element => {
if (principal.id === element.id) {
role = element.role;
}
});
}
if (role === 0) {
return this.language.instant('DMP-LISTING.OWNER');
}
else if (role === 1) {
return this.language.instant('DMP-LISTING.MEMBER');
}
else {
return this.language.instant('DMP-LISTING.OWNER');
}
}
openDmpSearchDialogue(dataset: DatasetListingModel) {
const formControl = new FormControl();
const dialogRef = this.dialog.open(DatasetCopyDialogueComponent, {
width: '500px',
restoreFocus: false,
data: {
formControl: formControl,
datasetId: dataset.id,
datasetProfileId: dataset.profile.id,
datasetProfileExist: false,
confirmButton: this.language.instant('DATASET-WIZARD.DIALOGUE.COPY'),
cancelButton: this.language.instant('DATASET-WIZARD.DIALOGUE.CANCEL')
}
});
dialogRef.afterClosed().pipe(takeUntil(this._destroyed))
.subscribe(result => {
if (result && result.datasetProfileExist) {
const newDmpId = result.formControl.value.id;
this.router.navigate(['/datasets/copy/' + result.datasetId], { queryParams: { newDmpId: newDmpId } });
// let url = this.router.createUrlTree(['/datasets/copy/', result.datasetId, { newDmpId: newDmpId }]);
// window.open(url.toString(), '_blank');
}
});
}
deleteClicked(id: string) {
this.lockService.checkLockStatus(id).pipe(takeUntil(this._destroyed))
.subscribe(lockStatus => {
if (!lockStatus) {
this.openDeleteDialog(id);
} else {
this.openLockedByUserDialog();
}
});
}
openDeleteDialog(id: string): void {
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
maxWidth: '300px',
restoreFocus: false,
data: {
message: this.language.instant('GENERAL.CONFIRMATION-DIALOG.DELETE-ITEM'),
confirmButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.DELETE'),
cancelButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CANCEL'),
isDeleteConfirmation: true
}
});
dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
if (result) {
this.datasetWizardService.delete(id)
.pipe(takeUntil(this._destroyed))
.subscribe(
complete => this.onDeleteCallbackSuccess(),
error => this.onDeleteCallbackError(error)
);
}
});
}
openLockedByUserDialog() {
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
maxWidth: '400px',
restoreFocus: false,
data: {
message: this.language.instant('DATASET-WIZARD.ACTIONS.LOCK')
}
});
}
openShareDialog(dmpRowId: any, dmpRowName: any, activity: any) {
const dialogRef = this.dialog.open(DmpInvitationDialogComponent, {
// height: '250px',
// width: '700px',
autoFocus: false,
restoreFocus: false,
data: {
dmpId: dmpRowId,
dmpName: dmpRowName
}
});
}
getFilenameFromContentDispositionHeader(header: string): string {
const regex: RegExp = new RegExp(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/g);
const matches = header.match(regex);
let filename: string;
for (let i = 0; i < matches.length; i++) {
const match = matches[i];
if (match.includes('filename="')) {
filename = match.substring(10, match.length - 1);
break;
} else if (match.includes('filename=')) {
filename = match.substring(9);
break;
}
}
return filename;
}
downloadPDF(dataset: DatasetListingModel): void {
this.datasetWizardService.downloadPDF(dataset.id as string)
.pipe(takeUntil(this._destroyed))
.subscribe(response => {
const blob = new Blob([response.body], { type: 'application/pdf' });
const filename = this.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition'));
FileSaver.saveAs(blob, filename);
this.matomoService.trackDownload('datasets', "pdf", dataset.id);
});
}
downloadDOCX(dataset: DatasetListingModel): void {
this.datasetWizardService.downloadDOCX(dataset.id as string)
.pipe(takeUntil(this._destroyed))
.subscribe(response => {
const blob = new Blob([response.body], { type: 'application/msword' });
const filename = this.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition'));
FileSaver.saveAs(blob, filename);
this.matomoService.trackDownload('datasets', "docx", dataset.id);
});
}
downloadXML(dataset: DatasetListingModel): void {
this.datasetWizardService.downloadXML(dataset.id as string)
.pipe(takeUntil(this._destroyed))
.subscribe(response => {
const blob = new Blob([response.body], { type: 'application/xml' });
const filename = this.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition'));
FileSaver.saveAs(blob, filename);
this.matomoService.trackDownload('datasets', "xml", dataset.id);
});
}
onCallbackSuccess(id?: String): void {
this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success);
id ? this.router.navigate(['/reload']).then(() => { this.router.navigate(['/datasets', 'edit', id]); }) : this.router.navigate(['/datasets']);
}
onCallbackError(error: any) {
this.setErrorModel(error.error);
}
reloadPage(): void {
const path = this.location.path();
this.router.navigateByUrl('/reload', { skipLocationChange: true }).then(() => {
this.router.navigate([path]);
});
}
onDeleteCallbackSuccess(): void {
this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-DELETE'), SnackBarNotificationLevel.Success);
this.reloadPage();
}
onDeleteCallbackError(error) {
this.uiNotificationService.snackBarNotification(error.error.message ? this.language.instant(error.error.message) : this.language.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-DELETE'), SnackBarNotificationLevel.Error);
}
openUpdateDatasetProfileDialogue(id: string) {
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
restoreFocus: false,
data: {
message: this.language.instant('DATASET-EDITOR.VERSION-DIALOG.QUESTION'),
confirmButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CONFIRM'),
cancelButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CANCEL'),
isDeleteConfirmation: false
}
});
dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
if (result) {
this.uiNotificationService.snackBarNotification(this.language.instant('DATASET-WIZARD.MESSAGES.SUCCESS-UPDATE-DATASET-PROFILE'), SnackBarNotificationLevel.Success);
this.router.navigate(['/datasets/profileupdate/' + id]);
}
});
}
public setErrorModel(validationErrorModel: ValidationErrorModel) {
}
needsUpdate(activity: DatasetListingModel) {
if (activity.isProfileLatestVersion || (activity.status === DatasetStatus.Finalized)
|| (activity.isProfileLatestVersion == undefined && activity.status == undefined)) {
return false;
}
else {
return true;
}
}
private mergeTwoSortedLists(arr1: DatasetListingModel[], arr2: DatasetListingModel[], order: string): DatasetListingModel[] {
let merged = [];
let index1 = 0;
let index2 = 0;
let current = 0;
while (current < (arr1.length + arr2.length)) {
let isArr1Depleted = index1 >= arr1.length;
let isArr2Depleted = index2 >= arr2.length;
if (order === 'modified') {
if (!isArr1Depleted && (isArr2Depleted || (new Date(arr1[index1].modified) > new Date(arr2[index2].modified)))) {
merged[current] = arr1[index1];
index1++;
} else {
merged[current] = arr2[index2];
index2++;
}
} else if (order === 'created') {
if (!isArr1Depleted && (isArr2Depleted || (new Date(arr1[index1].created) > new Date(arr2[index2].created)))) {
merged[current] = arr1[index1];
index1++;
} else {
merged[current] = arr2[index2];
index2++;
}
} else if (order === 'label') {
if (!isArr1Depleted && (isArr2Depleted || (arr1[index1].label.localeCompare(arr2[index2].label)))) {
merged[current] = arr1[index1];
index1++;
} else {
merged[current] = arr2[index2];
index2++;
}
} else if (order === 'status') {
if (!isArr1Depleted && (isArr2Depleted || (arr1[index1].status < arr2[index2].status))) {
merged[current] = arr1[index1];
index1++;
} else {
merged[current] = arr2[index2];
index2++;
}
} else if (order === 'dmp:publishedAt|join|') {
if (!isArr1Depleted && (isArr2Depleted || (new Date(arr1[index1].dmpPublishedAt) > new Date(arr2[index2].dmpPublishedAt)))) {
merged[current] = arr1[index1];
index1++;
} else {
merged[current] = arr2[index2];
index2++;
}
}
current++;
}
return merged;
}
}