import { AfterViewInit, Component, ViewContainerRef, ViewEncapsulation } from '@angular/core'; import { FormControl, FormGroup } from '@angular/forms'; import { MatDialog, MatSnackBar } from '@angular/material'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { TdDialogService } from '@covalent/core'; import { TranslateService } from '@ngx-translate/core'; import * as FileSaver from 'file-saver'; import { Observable } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { BaseComponent } from '../../core/common/base/base.component'; import { BaseCriteria } from '../../models/criteria/BaseCriteria'; import { DatasetProfileCriteria } from '../../models/criteria/dataset-profile/DatasetProfileCriteria'; import { DataManagementPlanProfileCriteria } from '../../models/criteria/dmp-profile/DataManagementPlanProfileCriteria'; import { ProjectCriteria } from '../../models/criteria/project/ProjectCriteria'; import { RequestItem } from '../../models/criteria/RequestItem'; import { DataManagementPlanProfileListingModel } from '../../models/data-management-plan-profile/DataManagementPlanProfileListingModel'; import { DataManagementPlanModel, DataManagementPlanStatus } from '../../models/data-managemnt-plans/DataManagementPlanModel'; import { DatasetListingModel } from '../../models/datasets/DatasetListingModel'; import { DatasetProfileModel } from '../../models/datasets/DatasetProfileModel'; import { DmpUsersModel } from '../../models/dmpUsers/DmpUsersModel'; import { BaseErrorModel } from '../../models/error/BaseErrorModel'; import { ExternalSourcesItemModel } from '../../models/external-sources/ExternalSourcesItemModel'; import { DataManagementPlanProfileService } from '../../services/data-management-plan-profile/datamanagement-profile.service'; import { DataManagementPlanService } from '../../services/data-management-plan/data-management-plan.service'; import { ExternalSourcesService } from '../../services/external-sources/external-sources.service'; import { LanguageResolverService } from '../../services/language-resolver/language-resolver.service'; import { ProjectService } from '../../services/project/project.service'; import { AddResearchersComponent } from '../../shared/components/add-researchers/add-researchers.component'; import { MultipleAutoCompleteConfiguration } from '../../shared/components/autocompletes/multiple/multiple-auto-complete-configuration'; import { SingleAutoCompleteConfiguration } from '../../shared/components/autocompletes/single/single-auto-complete-configuration'; import { AvailableProfilesComponent } from '../../shared/components/available-profiles/available-profiles.component'; import { BreadcrumbItem } from '../../shared/components/breadcrumb/definition/breadcrumb-item'; import { IBreadCrumbComponent } from '../../shared/components/breadcrumb/definition/IBreadCrumbComponent'; import { SnackBarNotificationComponent } from '../../shared/components/notificaiton/snack-bar-notification.component'; import { JsonSerializer } from '../../utilities/JsonSerializer'; import { DMPFinaliseDialogComponent } from './dmp-finalise-dialog/dmp-finalise-dialog.component'; @Component({ selector: 'app-dmp-editor-component', templateUrl: 'dmp-editor.component.html', styleUrls: ['./dmp-editor.component.scss'], encapsulation: ViewEncapsulation.None }) export class DataManagementPlanEditorComponent extends BaseComponent implements AfterViewInit, IBreadCrumbComponent { editMode = true; breadCrumbs: Observable; isNew = true; textCtrl = new FormControl(); dataManagementPlan: DataManagementPlanModel; formGroup: FormGroup = null; filteringOrganisationsAsync = false; filteringResearchersAsync = false; filteredProfilesAsync = false; filteredOrganisations: ExternalSourcesItemModel[]; filteredResearchers: ExternalSourcesItemModel[]; filteredProfiles: DatasetProfileModel[]; projectAutoCompleteConfiguration: SingleAutoCompleteConfiguration; profilesAutoCompleteConfiguration: MultipleAutoCompleteConfiguration; organisationsAutoCompleteConfiguration: MultipleAutoCompleteConfiguration; researchersAutoCompleteConfiguration: MultipleAutoCompleteConfiguration; createNewVersion; associatedUsers: Array; filteredOptions: Observable; constructor( private dmpProfileService: DataManagementPlanProfileService, private dataManagementPlanService: DataManagementPlanService, private projectService: ProjectService, private externalSourcesService: ExternalSourcesService, private route: ActivatedRoute, public snackBar: MatSnackBar, public router: Router, public language: TranslateService, private _service: DataManagementPlanService, public dialog: MatDialog, private _dialogService: TdDialogService, private _viewContainerRef: ViewContainerRef, private languageResolverService: LanguageResolverService ) { super(); this.filteredOptions = dmpProfileService.getAll({ criteria: new DataManagementPlanProfileCriteria() }); } ngAfterViewInit() { this.route.params .pipe(takeUntil(this._destroyed)) .subscribe((params: Params) => { const itemId = params['id']; 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), items: this.searchProject(''), displayFn: (item) => item['label'], titleFn: (item) => item['label'], //mapFn: (item) => new JsonSerializer().fromJSONArray(item, ProjectReference).map(item => item.toDropdownList()), loadDataOnStart: true }; 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'], //mapFn: (item) => new JsonSerializer().fromJSONArray(item, ProjectReference).map(item => item.toDropdownList()), loadDataOnStart: true }; 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'], loadDataOnStart: true }; 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'], loadDataOnStart: true }; if (itemId != null) { this.isNew = false; this.dataManagementPlanService.getSingle(itemId).map(data => data as DataManagementPlanModel) .pipe(takeUntil(this._destroyed)) .subscribe(async data => { this.dataManagementPlan = JsonSerializer.fromJSONObject(data, DataManagementPlanModel); this.formGroup = this.dataManagementPlan.buildForm(); this.editMode = this.dataManagementPlan.status !== 1; if (!this.editMode) { this.formGroup.disable(); } if (this.formGroup.get('profile') && this.formGroup.get('profile').value) { this.textCtrl.patchValue(this.formGroup.get('profile').value); } this.breadCrumbs = Observable.of([ { parentComponentName: 'DataManagementPlanListingComponent', label: 'DMPs', url: 'dmps', notFoundResolver: [await this.projectService.getSingle(this.dataManagementPlan.project.id).map(x => ({ label: x.label, url: '/projects/edit/' + x.id }) as BreadcrumbItem).toPromise()] }] ); this.associatedUsers = data.associatedUsers; }); } else { this.dataManagementPlan = new DataManagementPlanModel(); setTimeout(async () => { this.formGroup = this.dataManagementPlan.buildForm(); if (this.formGroup.get('profile') && this.formGroup.get('profile').value) { this.textCtrl.patchValue(this.formGroup.get('profile').value); } this.breadCrumbs = Observable.of([ { parentComponentName: 'DataManagementPlanListingComponent', label: 'DMPs', url: 'dmps', } ]); }); } }); this.route .queryParams .pipe(takeUntil(this._destroyed)) .subscribe(params => { this.createNewVersion = params['clone']; }); } 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.dataManagementPlanService.createDataManagementPlan(this.formGroup.value) .pipe(takeUntil(this._destroyed)) .subscribe( complete => this.onCallbackSuccess(), error => this.onCallbackError(error) ); } onCallbackSuccess(): void { this.snackBar.openFromComponent(SnackBarNotificationComponent, { data: { message: this.isNew ? 'GENERAL.SNACK-BAR.SUCCESSFUL-CREATION' : 'GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE', language: this.language }, duration: 3000, }); this.router.navigate(['/dmps']); } onCallbackError(error: any) { this.setErrorModel(error.error); //this.validateAllFormFields(this.formGroup); } public setErrorModel(errorModel: BaseErrorModel) { Object.keys(errorModel).forEach(item => { (this.dataManagementPlan.errorModel)[item] = (errorModel)[item]; }); } public cancel(): void { this.router.navigate(['/dmps']); } public invite(): void { this.router.navigate(['/invite/' + this.dataManagementPlan.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(AddResearchersComponent, { height: '255px', width: '700px', data: { dmpId: rowId, dmpName: rowName } }); } availableProfiles() { const dialogRef = this.dialog.open(AvailableProfilesComponent, { height: '355px', width: '700px', data: { profiles: this.formGroup.get('profiles') } }); return false; } openConfirm(dmpLabel, id): void { this._dialogService.openConfirm({ message: 'Are you sure you want to delete the "' + dmpLabel + '"', disableClose: true || false, viewContainerRef: this._viewContainerRef, title: 'Confirm', cancelButton: 'No', acceptButton: 'Yes' }).afterClosed() .pipe(takeUntil(this._destroyed)) .subscribe((accept: boolean) => { if (accept) { this.dataManagementPlanService.delete(id) .pipe(takeUntil(this._destroyed)) .subscribe(() => { this.router.navigate(['/dmps']); }); } else { // DO SOMETHING ELSE } }); } selectOption(option: any) { this.dataManagementPlan.definition = null; this.formGroup.get('profile').patchValue(option, { emitEvent: false }); this.dmpProfileService.getSingle(option.id) .pipe(takeUntil(this._destroyed)) .subscribe(result => { this.dataManagementPlan.definition = result.definition; }); } displayWith(item: any) { if (!item) { return null; } return item['label']; } redirectToProject() { this.router.navigate(['projects/edit/' + this.dataManagementPlan.project.id]); } redirectToDatasets() { this.router.navigate(['datasets/dmp/' + this.dataManagementPlan.id]); } newVersion(id: String, label: String) { this.router.navigate(['/dmps/new_version/' + id, { dmpLabel: label }]); } clone(id: String) { this.router.navigate(['/dmps/clone/' + id]); } viewVersions(rowId: String, rowLabel: String) { this.router.navigate(['/dmps/viewversions/' + rowId], { queryParams: { groupLabel: rowLabel } }); } downloadXml(id: string) { this.dataManagementPlanService.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.dataManagementPlanService.downloadDocx(id) .pipe(takeUntil(this._destroyed)) .subscribe(response => { const blob = new Blob([response.body], { type: 'application/octet-stream' }); const filename = this.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition')); FileSaver.saveAs(blob, filename); }); } downloadPDF(id: string) { this.dataManagementPlanService.downloadPDF(id) .pipe(takeUntil(this._destroyed)) .subscribe(response => { const blob = new Blob([response.body], { type: 'application/octet-stream' }); 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 !== DataManagementPlanStatus.Finalised) { this.editMode = true; this.formGroup.enable(); } else { this.dataManagementPlanService.unlock(this.formGroup.get('id').value) .pipe(takeUntil(this._destroyed)) .subscribe(x => { this.editMode = true; this.formGroup.get('status').patchValue(DataManagementPlanStatus.Draft); this.formGroup.enable(); }); } } public disableForm() { this.editMode = false; this.formGroup.disable(); } saveAndFinalize() { const dialogRef = this.dialog.open(DMPFinaliseDialogComponent, { data: { submitFunction: (items: DatasetListingModel[]) => { this.formGroup.get('status').setValue('1'); this.formGroup.addControl('datasets', new FormControl(items)); this.formSubmit(); dialogRef.close(); }, dmp: this.dataManagementPlan } }); } }