import { Component, OnInit, ViewContainerRef } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { MatDialog, MatSnackBar } from '@angular/material'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import * as FileSaver from 'file-saver'; import { Observable } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { ValidationErrorModel } from '../../../common/forms/validation/error-model/validation-error-model'; import { BaseComponent } from '../../../core/common/base/base.component'; import { DmpStatus } from '../../../core/common/enum/dmp-status'; import { Status } from '../../../core/common/enum/Status'; import { DataTableRequest } from '../../../core/model/data-table/data-table-request'; import { DatasetListingModel } from '../../../core/model/dataset/dataset-listing'; import { DatasetProfileModel } from '../../../core/model/dataset/dataset-profile'; import { DmpProfileDefinition } from '../../../core/model/dmp-profile/dmp-profile'; import { DmpProfileListing } from '../../../core/model/dmp-profile/dmp-profile-listing'; import { DmpModel } from '../../../core/model/dmp/dmp'; import { ExternalSourceItemModel } from '../../../core/model/external-sources/external-source-item'; import { ProjectListingModel } from '../../../core/model/project/project-listing'; import { UserModel } from '../../../core/model/user/user'; import { BaseCriteria } from '../../../core/query/base-criteria'; import { DatasetProfileCriteria } from '../../../core/query/dataset-profile/dataset-profile-criteria'; import { DmpProfileCriteria } from '../../../core/query/dmp/dmp-profile-criteria'; import { ProjectCriteria } from '../../../core/query/project/project-criteria'; import { RequestItem } from '../../../core/query/request-item'; import { DmpProfileService } from '../../../core/services/dmp/dmp-profile.service'; import { DmpService } from '../../../core/services/dmp/dmp.service'; import { ExternalSourcesService } from '../../../core/services/external-sources/external-sources.service'; import { SnackBarNotificationLevel, UiNotificationService } from '../../../core/services/notification/ui-notification-service'; import { ProjectService } from '../../../core/services/project/project.service'; import { MultipleAutoCompleteConfiguration } from '../../../library/auto-complete/multiple/multiple-auto-complete-configuration'; import { SingleAutoCompleteConfiguration } from '../../../library/auto-complete/single/single-auto-complete-configuration'; import { ConfirmationDialogComponent } from '../../../library/confirmation-dialog/confirmation-dialog.component'; import { LanguageResolverService } from '../../../services/language-resolver/language-resolver.service'; import { BreadcrumbItem } from '../../misc/breadcrumb/definition/breadcrumb-item'; import { IBreadCrumbComponent } from '../../misc/breadcrumb/definition/IBreadCrumbComponent'; import { AddResearcherComponent } from './add-researcher/add-researcher.component'; import { AvailableProfilesComponent } from './available-profiles/available-profiles.component'; import { DmpEditorModel } from './dmp-editor.model'; import { DmpFinalizeDialogComponent } from './dmp-finalize-dialog/dmp-finalize-dialog.component'; import { AuthService } from '../../../core/services/auth/auth.service'; @Component({ selector: 'app-dmp-editor-component', templateUrl: 'dmp-editor.component.html', styleUrls: ['./dmp-editor.component.scss'] }) export class DmpEditorComponent extends BaseComponent implements OnInit, IBreadCrumbComponent { editMode = false; breadCrumbs: Observable; isNew = true; isPublic = false; dmp: DmpEditorModel; formGroup: FormGroup = null; filteringOrganisationsAsync = false; filteringResearchersAsync = false; filteredProfilesAsync = false; filteredOrganisations: ExternalSourceItemModel[]; filteredResearchers: ExternalSourceItemModel[]; filteredProfiles: DatasetProfileModel[]; projectAutoCompleteConfiguration: SingleAutoCompleteConfiguration; profilesAutoCompleteConfiguration: MultipleAutoCompleteConfiguration; organisationsAutoCompleteConfiguration: MultipleAutoCompleteConfiguration; researchersAutoCompleteConfiguration: MultipleAutoCompleteConfiguration; dmpProfileAutoCompleteConfiguration: SingleAutoCompleteConfiguration; createNewVersion; associatedUsers: Array; filteredOptions: DmpProfileListing[]; selectedDmpProfileDefinition: DmpProfileDefinition; DynamicDmpFieldResolverComponent: any; constructor( private dmpProfileService: DmpProfileService, private dmpService: DmpService, private projectService: ProjectService, private externalSourcesService: ExternalSourcesService, private route: ActivatedRoute, private snackBar: MatSnackBar, private router: Router, private language: TranslateService, private _service: DmpService, private dialog: MatDialog, private _viewContainerRef: ViewContainerRef, public languageResolverService: LanguageResolverService, private uiNotificationService: UiNotificationService, private authService: AuthService, ) { super(); } ngOnInit() { this.route.params .pipe(takeUntil(this._destroyed)) .subscribe((params: Params) => { const itemId = params['id']; const projectId = params['projectId']; const publicId = params['publicId']; const projectRequestItem: RequestItem = new RequestItem(); projectRequestItem.criteria = new ProjectCriteria(); const organisationRequestItem: RequestItem = new RequestItem(); organisationRequestItem.criteria = new BaseCriteria(); this.projectAutoCompleteConfiguration = { filterFn: this.searchProject.bind(this), initialItems: (extraData) => this.searchProject(''), displayFn: (item) => item['label'], titleFn: (item) => item['label'] }; this.dmpProfileAutoCompleteConfiguration = { filterFn: this.dmpProfileSearch.bind(this), initialItems: (extraData) => this.dmpProfileSearch(''), displayFn: (item) => item['label'], titleFn: (item) => item['label'] }; this.profilesAutoCompleteConfiguration = { filterFn: this.filterProfiles.bind(this), initialItems: (excludedItems: any[]) => this.filterProfiles('').map(result => result.filter(resultItem => excludedItems.map(x => x.id).indexOf(resultItem.id) === -1)), displayFn: (item) => item['label'], titleFn: (item) => item['label'] }; this.organisationsAutoCompleteConfiguration = { filterFn: this.filterOrganisations.bind(this), initialItems: (excludedItems: any[]) => this.filterOrganisations('').map(result => result.filter(resultItem => excludedItems.map(x => x.id).indexOf(resultItem.id) === -1)), displayFn: (item) => item['name'], titleFn: (item) => item['name'] }; this.researchersAutoCompleteConfiguration = { filterFn: this.filterResearchers.bind(this), initialItems: (excludedItems: any[]) => this.filterResearchers('').map(result => result.filter(resultItem => excludedItems.map(x => x.id).indexOf(resultItem.id) === -1)), displayFn: (item) => item['name'], titleFn: (item) => item['name'] }; if (itemId != null) { this.isNew = false; this.dmpService.getSingle(itemId).map(data => data as DmpModel) .pipe(takeUntil(this._destroyed)) .subscribe(async data => { this.dmp = new DmpEditorModel().fromModel(data); this.formGroup = this.dmp.buildForm(); this.registerFormEventsForDmpProfile(this.dmp.definition); if (!this.editMode || this.dmp.status === Status.Inactive) { this.formGroup.disable(); } if (this.isAuthenticated) { // if (!this.isAuthenticated) { this.breadCrumbs = Observable.of([ { parentComponentName: 'DmpListingComponent', label: 'DMPs', url: 'plans', notFoundResolver: [await this.projectService.getSingle(this.dmp.project.id).map(x => ({ label: x.label, url: '/projects/edit/' + x.id }) as BreadcrumbItem).toPromise()] }] ); } this.associatedUsers = data.associatedUsers; }); } else if (projectId != null) { this.isNew = true; this.projectService.getSingle(projectId).map(data => data as ProjectListingModel) .pipe(takeUntil(this._destroyed)) .subscribe(data => { this.dmp = new DmpEditorModel(); this.dmp.project = data; this.formGroup = this.dmp.buildForm(); this.registerFormEventsForDmpProfile(); this.formGroup.get('project').disable(); this.registerFormEventsForNewItem(); }); } else if (publicId != null) { this.isNew = false; this.isPublic = true; this.dmpService.getSinglePublic(publicId).map(data => data as DmpModel) .pipe(takeUntil(this._destroyed)) .subscribe(async data => { this.dmp = new DmpEditorModel().fromModel(data); this.formGroup = this.dmp.buildForm(); this.registerFormEventsForDmpProfile(this.dmp.definition); if (!this.editMode || this.dmp.status === Status.Inactive) { this.formGroup.disable(); } if (this.isAuthenticated) { // if (!this.isAuthenticated) { this.breadCrumbs = Observable.of([ { parentComponentName: 'DmpListingComponent', label: 'DMPs', url: 'plans', notFoundResolver: [await this.projectService.getSingle(this.dmp.project.id).map(x => ({ label: x.label, url: '/projects/edit/' + x.id }) as BreadcrumbItem).toPromise()] }] ); this.associatedUsers = data.associatedUsers; } }); } else { this.dmp = new DmpEditorModel(); this.formGroup = this.dmp.buildForm(); this.registerFormEventsForDmpProfile(); this.registerFormEventsForNewItem(); } }); this.route .queryParams .pipe(takeUntil(this._destroyed)) .subscribe(params => { this.createNewVersion = params['clone']; }); } registerFormEventsForDmpProfile(definitionPropertys?: DmpProfileDefinition): void { this.formGroup.get('profile').valueChanges .pipe(takeUntil(this._destroyed)) .subscribe(Option => { if (Option instanceof Object) { this.selectedDmpProfileDefinition = null; this.dmpProfileService.getSingle(Option.id) .pipe(takeUntil(this._destroyed)) .subscribe(result => { this.selectedDmpProfileDefinition = result.definition; }); } else { this.selectedDmpProfileDefinition = null; } this.selectedDmpProfileDefinition = definitionPropertys; }) } isAuthenticated() { return this.authService.current() != null; } registerFormEventsForNewItem() { this.breadCrumbs = Observable.of([ { parentComponentName: 'DmpListingComponent', label: 'DMPs', url: 'plans', } ]); } dmpProfileSearch(query: string) { let fields: Array = new Array(); var request = new DataTableRequest(0, 10, { fields: fields }); request.criteria = new DmpProfileCriteria(); return this.dmpProfileService.getPaged(request).map(x => x.data); } searchProject(query: string) { const projectRequestItem: RequestItem = new RequestItem(); projectRequestItem.criteria = new ProjectCriteria(); projectRequestItem.criteria.like = query; return this.projectService.getWithExternal(projectRequestItem); } formSubmit(): void { //this.touchAllFormFields(this.formGroup); if (!this.isFormValid()) { return; } this.onSubmit(); } public isFormValid() { return this.formGroup.valid; } onSubmit(): void { this.dmpService.createDmp(this.formGroup.getRawValue()) .pipe(takeUntil(this._destroyed)) .subscribe( complete => this.onCallbackSuccess(), error => this.onCallbackError(error) ); } onCallbackSuccess(): void { this.uiNotificationService.snackBarNotification(this.isNew ? this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-CREATION') : this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success); this.router.navigate(['/plans']); } onCallbackError(error: any) { this.setErrorModel(error.error); //this.validateAllFormFields(this.formGroup); } public setErrorModel(validationErrorModel: ValidationErrorModel) { Object.keys(validationErrorModel).forEach(item => { (this.dmp.validationErrorModel)[item] = (validationErrorModel)[item]; }); } public cancel(): void { this.router.navigate(['/plans']); } public invite(): void { this.router.navigate(['/invite/' + this.dmp.id]); } filterOrganisations(value: string): Observable { this.filteredOrganisations = undefined; this.filteringOrganisationsAsync = true; return this.externalSourcesService.searchDMPOrganizations(value); } filterResearchers(value: string): Observable { this.filteredResearchers = undefined; this.filteringResearchersAsync = true; return this.externalSourcesService.searchDMPResearchers({ criteria: { name: value, like: null } }); } filterProfiles(value: string): Observable { this.filteredProfiles = undefined; this.filteredProfilesAsync = true; const request = new RequestItem(); const criteria = new DatasetProfileCriteria(); criteria.like = value; request.criteria = criteria; return this._service.searchDMPProfiles(request); } addResearcher(rowId: any, rowName: any) { const dialogRef = this.dialog.open(AddResearcherComponent, { data: { dmpId: rowId, dmpName: rowName } }); } availableProfiles() { const dialogRef = this.dialog.open(AvailableProfilesComponent, { data: { profiles: this.formGroup.get('profiles') } }); return false; } public delete(): void { const dialogRef = this.dialog.open(ConfirmationDialogComponent, { maxWidth: '300px', data: { message: this.language.instant('GENERAL.CONFIRMATION-DIALOG.DELETE-ITEM'), confirmButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CONFIRM'), cancelButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CANCEL') } }); dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => { if (result) { this.dmpService.delete(this.dmp.id) .pipe(takeUntil(this._destroyed)) .subscribe( complete => { this.onCallbackSuccess() }, error => this.onDeleteCallbackError(error) ); } }); } onDeleteCallbackError(error) { this.uiNotificationService.snackBarNotification(error.error.message ? error.error.message : this.language.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-DELETE'), SnackBarNotificationLevel.Error); } // selectOption(option: any) { // this.dmp.definition = null; // this.formGroup.get('profile').patchValue(option, { emitEvent: false }); // this.dmpProfileService.getSingle(option.id) // .pipe(takeUntil(this._destroyed)) // .subscribe(result => { // this.selectedDmpProfileDefinition = result.definition; // }); // } displayWith(item: any) { if (!item) { return null; } return item['label']; } redirectToProject() { this.router.navigate(['projects/edit/' + this.dmp.project.id]); } redirectToDatasets() { this.router.navigate(['datasets'], { queryParams: { dmpId: this.dmp.id } }); } newVersion(id: String, label: String) { this.router.navigate(['/plans/new_version/' + id, { dmpLabel: label }]); } clone(id: String) { this.router.navigate(['/plans/clone/' + id]); } viewVersions(rowId: String, rowLabel: String) { this.router.navigate(['/plans/versions/' + rowId], { queryParams: { groupLabel: rowLabel } }); } downloadXml(id: string) { this.dmpService.downloadXML(id) .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); }); } downloadDocx(id: string) { this.dmpService.downloadDocx(id) .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); }); } downloadPDF(id: string) { this.dmpService.downloadPDF(id) .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); }); } 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; } public enableForm() { if (this.formGroup.get('status').value !== DmpStatus.Finalized) { this.editMode = true; this.formGroup.enable(); } //else { // this.dmpService.unlock(this.formGroup.get('id').value) // .pipe(takeUntil(this._destroyed)) // .subscribe(x => { // this.editMode = true; // this.formGroup.get('status').patchValue(DmpStatus.Draft); // this.formGroup.enable(); // }); // } } public disableForm() { this.editMode = false; this.formGroup.disable(); } saveAndFinalize() { const dialogRef = this.dialog.open(DmpFinalizeDialogComponent, { data: { submitFunction: (items: DatasetListingModel[]) => { this.formGroup.get('status').setValue('1'); this.formGroup.addControl('datasets', new FormControl(items)); this.formSubmit(); dialogRef.close(); }, dmp: this.dmp } }); } }