argos/dmp-frontend/src/app/ui/description/editor/description-editor.componen...

2313 lines
92 KiB
TypeScript

import { DatePipe } from '@angular/common';
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { DescriptionStatus } from '@app/core/common/enum/description-status';
import { DmpStatus } from '@app/core/common/enum/dmp-status';
import { IsActive } from '@app/core/common/enum/is-active.enum';
import { AppPermission } from '@app/core/common/enum/permission.enum';
import { Description, DescriptionPersist, DescriptionSectionPermissionResolver, DescriptionStatusPersist } from '@app/core/model/description/description';
import { AuthService } from '@app/core/services/auth/auth.service';
import { DescriptionTemplateService } from '@app/core/services/description-template/description-template.service';
import { DescriptionService } from '@app/core/services/description/description.service';
import { DmpService } from '@app/core/services/dmp/dmp.service';
import { LockService } from '@app/core/services/lock/lock.service';
import { LoggingService } from '@app/core/services/logging/logging-service';
import { MatomoService } from '@app/core/services/matomo/matomo-service';
import {
SnackBarNotificationLevel,
UiNotificationService
} from '@app/core/services/notification/ui-notification-service';
import { EnumUtils } from '@app/core/services/utilities/enum-utils.service';
import { FileUtils } from '@app/core/services/utilities/file-utils.service';
import { QueryParamsService } from '@app/core/services/utilities/query-params.service';
import { PopupNotificationDialogComponent } from '@app/library/notification/popup/popup-notification.component';
import { VisibilityRulesService } from '@app/ui/description/editor/description-form/visibility-rules/visibility-rules.service';
import { isNullOrUndefined } from '@app/utilities/enhancers/utils';
import { BaseEditor } from '@common/base/base-editor';
import { FormService } from '@common/forms/form-service';
import { ConfirmationDialogComponent } from '@common/modules/confirmation-dialog/confirmation-dialog.component';
import { HttpErrorHandlingService } from '@common/modules/errors/error-handling/http-error-handling.service';
import { FilterService } from '@common/modules/text-filter/filter-service';
import { Guid } from '@common/types/guid';
import { TranslateService } from '@ngx-translate/core';
import { map, takeUntil } from 'rxjs/operators';
import { DescriptionEditorModel, DescriptionPropertyDefinitionEditorModel } from './description-editor.model';
import { DescriptionEditorResolver } from './description-editor.resolver';
import { DescriptionEditorService } from './description-editor.service';
import { PrefillDescriptionDialogComponent } from './prefill-description/prefill-description.component';
import { ToCEntry } from './table-of-contents/models/toc-entry';
import { ToCEntryType } from './table-of-contents/models/toc-entry-type.enum';
import { TableOfContentsComponent } from './table-of-contents/table-of-contents.component';
import { FormValidationErrorsDialogComponent } from '@common/forms/form-validation-errors-dialog/form-validation-errors-dialog.component';
import { ConfigurationService } from '@app/core/services/configuration/configuration.service';
import { LockTargetType } from '@app/core/common/enum/lock-target-type';
import { FileTransformerService } from '@app/core/services/file-transformer/file-transformer.service';
@Component({
selector: 'app-description-editor-component',
templateUrl: 'description-editor.component.html',
styleUrls: ['./description-editor.component.scss'],
providers: [DescriptionEditorService]
})
export class DescriptionEditorComponent extends BaseEditor<DescriptionEditorModel, Description> implements OnInit {
isNew = true;
isDeleted = false;
item: Description;
// showInactiveDetails = false;
// selectedSystemFields: Array<DescriptionSystemFieldType> = [];
// DescriptionSectionFieldCategory = DescriptionSectionFieldCategory;
// DescriptionSystemFieldType = DescriptionSystemFieldType;
// public DescriptionSystemFieldTypeEnum = this.enumUtils.getEnumValues<DescriptionSystemFieldType>(DescriptionSystemFieldType);
// DescriptionExtraFieldDataType = DescriptionExtraFieldDataType;
// public DescriptionExtraFieldDataTypeEnum = this.enumUtils.getEnumValues<DescriptionExtraFieldDataType>(DescriptionExtraFieldDataType);
// blueprintsAutoCompleteConfiguration: MultipleAutoCompleteConfiguration = {
// filterFn: this.filterDescriptionTempaltes.bind(this),
// initialItems: (excludedItems: any[]) => this.filterDescriptionTempaltes('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))),
// displayFn: (item: DatasetProfileModel) => item.label,
// titleFn: (item: DatasetProfileModel) => item.label,
// subtitleFn: (item: DatasetProfileModel) => item.description,
// popupItemActionIcon: 'visibility'
// };
// hasChanges = false;
fieldsetIdWithFocus: string;
viewOnly = false;
lockStatus: Boolean;
@ViewChild('table0fContents') table0fContents: TableOfContentsComponent;
step: number = 0;
constructor(
// BaseFormEditor injected dependencies
protected dialog: MatDialog,
protected language: TranslateService,
protected formService: FormService,
protected router: Router,
protected uiNotificationService: UiNotificationService,
protected httpErrorHandlingService: HttpErrorHandlingService,
protected filterService: FilterService,
protected datePipe: DatePipe,
protected route: ActivatedRoute,
protected queryParamsService: QueryParamsService,
protected lockService: LockService,
protected authService: AuthService,
protected configurationService: ConfigurationService,
// Rest dependencies. Inject any other needed deps here:
public enumUtils: EnumUtils,
private descriptionService: DescriptionService,
private logger: LoggingService,
private descriptionEditorService: DescriptionEditorService,
private descriptionTemplateService: DescriptionTemplateService,
private fileUtils: FileUtils,
private matomoService: MatomoService,
private dmpService: DmpService,
public visibilityRulesService: VisibilityRulesService,
public fileTransformerService: FileTransformerService,
) {
super(dialog, language, formService, router, uiNotificationService, httpErrorHandlingService, filterService, datePipe, route, queryParamsService, lockService, authService, configurationService);
}
ngOnInit(): void {
this.matomoService.trackPageView('Description Editor');
super.ngOnInit();
// const params = this.route.snapshot.params;
// const queryParams = this.route.snapshot.queryParams;
// const data: any = this.route.snapshot.data;
// this.init();
this.route.params
.pipe(takeUntil(this._destroyed))
.subscribe((params: Params) => {
const itemId = params['id'];
const dmpId = params['dmpId'];
const dmpSectionId = params['dmpSectionId'];
const isPublicDescription = params['public'];
const newDmpId = params['newDmpId'];
// const publicId = params['publicId'];
// this.dmpId = params['dmpId'];
// this.dmpSectionIndex = parseInt(params['dmpSectionIndex']);
// this.newDmpId = queryParams['newDmpId'];
// this.publicId = params['publicId'];
// this.profileUpdateId = params['updateId'];
// this.finalize = data.finalize;
// this.itemId ? this.downloadDocumentId = this.itemId : this.downloadDocumentId = this.publicId
this.viewOnly = isPublicDescription;
// if (itemId != null) {
// this.isNew = false;
// this.isPublicView = false;
// this.descriptionService.getSingle(itemId, this.lookupFields())
// .pipe(takeUntil(this._destroyed))
// .subscribe(data => {
// this.description = data;
// this.researchers = this.referenceService.getReferencesForTypes(this.description?.dmp?.dmpReferences, [ReferenceType.Researcher]);
// // this.users = this.description.dmp.users;
// this.checkLockStatus(this.description.id);
// this.setIsUserOwner();
// }, (error: any) => {
// if (error.status === 404) {
// return this.onFetchingDeletedCallbackError('/descriptions/');
// }
// if (error.status === 403) {
// return this.onFetchingForbiddenCallbackError('/descriptions/');
// }
// });
// }
// else if (publicId != null) {
// this.isNew = false;
// this.isFinalized = true;
// this.isPublicView = true;
// this.descriptionService.getPublicSingle(publicId, this.lookupFields())
// .pipe(takeUntil(this._destroyed))
// .subscribe(data => {
// this.description = data;
// this.researchers = this.referenceService.getReferencesForTypes(this.description?.dmp?.dmpReferences, [ReferenceType.Researcher]);
// // this.users = this.description.dmp.users;
// // const breadCrumbs = [];
// // breadCrumbs.push({ parentComponentName: null, label: this.language.instant('NAV-BAR.PUBLIC DESCRIPTIONS'), url: "/explore" });
// // breadCrumbs.push({ parentComponentName: 'DescriptionListingComponent', label: this.description.label, url: '/descriptions/overview/public/' + this.description.id });
// // this.breadCrumbs = observableOf(breadCrumbs);
// }, (error: any) => {
// if (error.status === 404) {
// return this.onFetchingDeletedCallbackError('/explore-descriptions');
// }
// if (error.status === 403) {
// return this.onFetchingForbiddenCallbackError('/explore-descriptions');
// }
// });
// }
//Regular Editor case
if (itemId != null && newDmpId == null) {
this.checkLock(this.item.id, LockTargetType.Description, 'DESCRIPTION-EDITOR.LOCKED-DIALOG.TITLE', 'DESCRIPTION-EDITOR.LOCKED-DIALOG.MESSAGE');
} else if (dmpId != null && dmpSectionId != null) {
this.isNew = true;
const dialogRef = this.dialog.open(PrefillDescriptionDialogComponent, {
width: '590px',
minHeight: '200px',
restoreFocus: false,
data: {
dmp: this.item.dmp,
dmpSectionId: dmpSectionId
},
panelClass: 'custom-modalbox'
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
result.dmp = this.item.dmp;
result.dmpDescriptionTemplate = this.item.dmpDescriptionTemplate;
this.prepareForm(result);
// this.descriptionModel = this.descriptionModel.fromModel(result);
// this.descriptionModel.dmp = data;
// this.descriptionModel.dmpSectionIndex = this.dmpSectionIndex;
// this.formGroup = this.descriptionModel.buildForm();
// this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
// this.formGroup.get('dmp').disable();
// this.loadDescriptionProfiles();
// this.registerFormListeners();
}
})
}
if(this.route.snapshot.url[1] && this.route.snapshot.url[1].path == 'finalize' && !this.lockStatus && !this.viewOnly) {
setTimeout(() => {
this.finalize();
}, 0);
}
// if (this.itemId != null && this.newDmpId == null) {
// this.isNew = false;
// this.descriptionService.getSingle(this.itemId)
// .pipe(takeUntil(this._destroyed))
// .subscribe(data => {
// this.lockService.checkLockStatus(data.id).pipe(takeUntil(this._destroyed)).subscribe(lockStatus => {
// this.lockStatus = lockStatus;
// this.descriptionModel = new DescriptionEditorModel().fromModel(data);
// this.dmpSectionIndex = this.descriptionModel.dmpSectionIndex;
// this.needsUpdate();
// // this.breadCrumbs = observableOf([
// // {
// // parentComponentName: null,
// // label: this.descriptionModel.label,
// // url: '/descriptions/edit/' + this.descriptionModel.id,
// // notFoundResolver: [
// // {
// // parentComponentName: null,
// // label: this.language.instant('NAV-BAR.MY-DATASET-DESCRIPTIONS').toUpperCase(),
// // url: '/descriptions'
// // },
// // ]
// // }]);
// this.formGroup = this.descriptionModel.buildForm();
// let profiles = this.descriptionModel.dmp.profiles.filter(profile => profile.data.dmpSectionIndex.includes(this.descriptionModel.dmpSectionIndex));
// for (var profile of profiles) {
// this.availableDescriptionTemplates.push({ id: profile.descriptionTemplateId, label: profile.label, description: "" })
// }
// this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
// this.editMode = this.descriptionModel.status === DescriptionStatus.Draft;
// if (this.descriptionModel.status === DescriptionStatus.Finalized || lockStatus) {
// this.formGroup.disable();
// this.viewOnly = true;
// }
// if (!lockStatus && !isNullOrUndefined(this.authService.currentAccountIsAuthenticated())) {
// const lockedBy: UserInfoListingModel = {
// email: this.authService.getUserProfileEmail(),
// id: this.authService.userId()?.toString(),
// name: this.authService.getPrincipalName(),
// role: 0 //TODO
// //role: this.authService.getRoles()?.at(0)
// }
// this.lock = new LockModel(data.id, lockedBy);
// this.lockService.createOrUpdate(this.lock).pipe(takeUntil(this._destroyed)).subscribe(async result => {
// this.lock.id = Guid.parse(result);
// interval(this.configurationService.lockInterval).pipe(takeUntil(this._destroyed)).subscribe(() => this.pumpLock());
// });
// }
// // if (this.viewOnly) { this.formGroup.disable(); } // For future use, to make Description edit like DMP.
// this.loadDescriptionProfiles();
// this.registerFormListeners();
// if (lockStatus) {
// this.dialog.open(PopupNotificationDialogComponent, {
// data: {
// title: this.language.instant('DATASET-WIZARD.LOCKED.TITLE'),
// message: this.language.instant('DATASET-WIZARD.LOCKED.MESSAGE')
// }, maxWidth: '30em'
// });
// }
// if (this.finalize && !this.lockStatus && !this.viewOnly) {
// setTimeout(() => {
// this.saveFinalize();
// }, 0);
// }
// // this.availableProfiles = this.descriptionModel.dmp.profiles;
// });
// },
// error => {
// switch (error.status) {
// case 403:
// this.uiNotificationService.snackBarNotification(this.language.instant('DATASET-WIZARD.MESSAGES.DATASET-NOT-ALLOWED'), SnackBarNotificationLevel.Error);
// break;
// case 404:
// this.uiNotificationService.snackBarNotification(this.language.instant('DATASET-WIZARD.MESSAGES.DATASET-NOT-FOUND'), SnackBarNotificationLevel.Error);
// break;
// default:
// this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.ERRORS.HTTP-REQUEST-ERROR'), SnackBarNotificationLevel.Error);
// }
// this.router.navigate(['/descriptions/']);
// return observableOf(null);
// });
// } else if (this.dmpId != null) {
// this.isNew = true;
// this.dmpService.getSingle(this.dmpId).pipe(map(data => data as DmpModel))
// .pipe(takeUntil(this._destroyed))
// .subscribe(data => {
// this.descriptionModel = new DescriptionEditorModel();
// setTimeout(() => {
// this.descriptionModel.dmp = data;
// this.descriptionModel.dmpSectionIndex = this.dmpSectionIndex;
// this.formGroup = this.descriptionModel.buildForm();
// let profiles = this.descriptionModel.dmp.profiles.filter(profile => profile.data.dmpSectionIndex.includes(this.dmpSectionIndex));
// for (var profile of profiles) {
// this.availableDescriptionTemplates.push({ id: profile.descriptionTemplateId, label: profile.label, description: "" })
// }
// this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
// this.editMode = this.descriptionModel.status === DescriptionStatus.Draft;
// this.formGroup.get('dmp').disable();
// const dialogRef = this.dialog.open(PrefillDescriptionComponent, {
// width: '590px',
// minHeight: '200px',
// restoreFocus: false,
// data: {
// availableProfiles: this.availableDescriptionTemplates,
// descriptionFormGroup: this.formGroup
// },
// panelClass: 'custom-modalbox'
// });
// dialogRef.afterClosed().subscribe(result => {
// if (result) {
// this.descriptionModel = this.descriptionModel.fromModel(result);
// this.descriptionModel.dmp = data;
// this.descriptionModel.dmpSectionIndex = this.dmpSectionIndex;
// this.formGroup = this.descriptionModel.buildForm();
// this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
// this.formGroup.get('dmp').disable();
// this.loadDescriptionProfiles();
// this.registerFormListeners();
// }
// })
// this.loadDescriptionProfiles();
// this.registerFormListeners();
// // this.availableProfiles = data.profiles;
// // this.breadCrumbs = observableOf([
// // {
// // parentComponentName: null,
// // label: this.language.instant('NAV-BAR.MY-DATASET-DESCRIPTIONS'),
// // url: '/descriptions',
// // notFoundResolver: [
// // // {
// // // parentComponentName: null,
// // // label: this.descriptionModel.dmp.grant.label,
// // // url: '/grants/edit/' + this.descriptionModel.dmp.grant.id
// // // },
// // {
// // parentComponentName: null,
// // label: this.descriptionModel.dmp.label,
// // url: '/plans/edit/' + this.descriptionModel.dmp.id,
// // }]
// // }]);
// });
// });
// } else if (this.newDmpId != null) {
// this.isNew = false;
// this.isCopy = true;
// this.descriptionService.getSingle(this.itemId)
// .pipe(takeUntil(this._destroyed))
// .subscribe(data => {
// this.lockService.checkLockStatus(data.id).pipe(takeUntil(this._destroyed)).subscribe(lockStatus => {
// this.lockStatus = lockStatus;
// this.descriptionModel = new DescriptionEditorModel().fromModel(data);
// this.dmpSectionIndex = this.descriptionModel.dmpSectionIndex;
// this.descriptionModel.status = 0;
// this.formGroup = this.descriptionModel.buildForm();
// this.formGroup.get('id').setValue(null);
// this.dmpService.getSingleNoDescriptions(this.newDmpId).pipe(map(data => data as DmpModel))
// .pipe(takeUntil(this._destroyed))
// .subscribe(data => {
// setTimeout(() => {
// this.descriptionModel.dmp = data;
// this.formGroup.get('dmp').setValue(this.descriptionModel.dmp);
// this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
// this.loadDescriptionProfiles();
// // this.breadCrumbs = observableOf([
// // {
// // parentComponentName: null,
// // label: this.language.instant('NAV-BAR.MY-DATASET-DESCRIPTIONS'),
// // url: '/descriptions',
// // notFoundResolver: [
// // // {
// // // parentComponentName: null,
// // // label: this.descriptionModel.dmp.grant.label,
// // // url: '/grants/edit/' + this.descriptionModel.dmp.grant.id
// // // },
// // {
// // parentComponentName: null,
// // label: this.descriptionModel.dmp.label,
// // url: '/plans/edit/' + this.descriptionModel.dmp.id,
// // }
// // ]
// // }]);
// });
// });
// this.editMode = this.descriptionModel.status === DescriptionStatus.Draft;
// if (this.descriptionModel.status === DescriptionStatus.Finalized || lockStatus) {
// this.formGroup.disable();
// this.viewOnly = true;
// }
// if (!lockStatus && !isNullOrUndefined(this.authService.currentAccountIsAuthenticated())) {
// const lockedBy: UserInfoListingModel = {
// email: this.authService.getUserProfileEmail(),
// id: this.authService.userId()?.toString(),
// name: this.authService.getPrincipalName(),
// role: 0 //TODO
// //role: this.authService.getRoles()?.at(0)
// }
// this.lock = new LockModel(data.id, lockedBy);
// this.lockService.createOrUpdate(this.lock).pipe(takeUntil(this._destroyed)).subscribe(async result => {
// this.lock.id = Guid.parse(result);
// interval(this.configurationService.lockInterval).pipe(takeUntil(this._destroyed)).subscribe(() => this.pumpLock());
// });
// }
// // if (this.viewOnly) { this.formGroup.disable(); } // For future use, to make Description edit like DMP.
// this.loadDescriptionProfiles();
// // this.availableProfiles = data.dmp.profiles;
// })
// });
// } else if (this.publicId != null) { // For Finalized -> Public Descriptions
// this.isNew = false;
// this.descriptionService.getSinglePublic(this.publicId)
// .pipe(takeUntil(this._destroyed)).pipe(
// catchError((error: any) => {
// this.uiNotificationService.snackBarNotification(error.error.message, SnackBarNotificationLevel.Error);
// this.router.navigate(['/descriptions/publicEdit/' + this.publicId]);
// return observableOf(null);
// }))
// .subscribe(data => {
// if (data) {
// this.descriptionModel = new DescriptionEditorModel().fromModel(data);
// this.formGroup = this.descriptionModel.buildForm();
// this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
// this.formGroup.disable();
// this.viewOnly = true;
// this.editMode = this.descriptionModel.status === DescriptionStatus.Draft;
// this.formGroup.get('dmp').setValue(this.descriptionModel.dmp);
// const breadcrumbs = [];
// breadcrumbs.push({
// parentComponentName: null,
// label: this.language.instant('NAV-BAR.PUBLIC DATASETS'),
// url: '/explore-descriptions'
// });
// breadcrumbs.push({
// parentComponentName: null,
// label: this.descriptionModel.label,
// url: '/descriptions/publicEdit/' + this.descriptionModel.id
// });
// // this.breadCrumbs = observableOf(breadcrumbs);
// }
// });
// this.publicMode = true;
// } else if (this.profileUpdateId != null) {
// this.descriptionService.updateDescriptionProfile(this.profileUpdateId)
// .pipe(takeUntil(this._destroyed))
// .subscribe(data => {
// this.descriptionModel = new DescriptionEditorModel().fromModel(data);
// this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
// this.needsUpdate();
// // this.breadCrumbs = observableOf([
// // {
// // parentComponentName: null,
// // label: this.language.instant('NAV-BAR.MY-DATASET-DESCRIPTIONS'),
// // url: '/descriptions',
// // notFoundResolver: [
// // // {
// // // parentComponentName: null,
// // // label: this.descriptionModel.dmp.grant.label,
// // // url: '/grants/edit/' + this.descriptionModel.dmp.grant.id
// // // },
// // {
// // parentComponentName: null,
// // label: this.descriptionModel.dmp.label,
// // url: '/plans/edit/' + this.descriptionModel.dmp.id,
// // },
// // ]
// // }]);
// this.formGroup = this.descriptionModel.buildForm();
// this.editMode = this.descriptionModel.status === DescriptionStatus.Draft;
// if (this.descriptionModel.status === DescriptionStatus.Finalized) {
// this.formGroup.disable();
// this.viewOnly = true;
// }
// // if (this.viewOnly) { this.formGroup.disable(); } // For future use, to make Description edit like DMP.
// this.loadDescriptionProfiles();
// });
// } else {
// this.descriptionModel = new DescriptionEditorModel();
// this.formGroup = this.descriptionModel.buildForm();
// this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
// this.editMode = this.descriptionModel.status === DescriptionStatus.Draft;
// if (this.descriptionModel.status === DescriptionStatus.Finalized) {
// this.formGroup.disable();
// this.viewOnly = true;
// }
// //if (this.viewOnly) { this.formGroup.disable(); } // For future use, to make Description edit like DMP.
// this.registerFormListeners();
// this.dmpValueChanged(null);
// // this.breadCrumbs = observableOf([
// // {
// // parentComponentName: null,
// // label: this.language.instant('DATASET-LISTING.ACTIONS.CREATE-NEW').toUpperCase(),
// // url: '/descriptions/new/'
// // }]);
// }
});
}
getItem(itemId: Guid, successFunction: (item: Description) => void) {
this.descriptionService.getSingle(itemId, DescriptionEditorResolver.lookupFields())
.pipe(map(data => data as Description), takeUntil(this._destroyed))
.subscribe(
data => successFunction(data),
error => this.onCallbackError(error)
);
}
prepareForm(data: Description) {
try {
this.editorModel = data ? new DescriptionEditorModel().fromModel(data, data.descriptionTemplate) : new DescriptionEditorModel();
this.item = data;
this.isDeleted = data ? data.isActive === IsActive.Inactive : false;
this.buildForm();
} catch (error) {
this.logger.error('Could not parse Description item: ' + data + error);
this.uiNotificationService.snackBarNotification(this.language.instant('COMMONS.ERRORS.DEFAULT'), SnackBarNotificationLevel.Error);
}
}
buildForm() {
const descriptionSectionPermissionResolverModel: DescriptionSectionPermissionResolver = {
dmpId: this.item.dmp.id,
sectionIds: [this.item.dmpDescriptionTemplate.sectionId],
permissions: [AppPermission.EditDescription, AppPermission.DeleteDescription]
}
this.descriptionService.getDescriptionSectionPermissions(descriptionSectionPermissionResolverModel)
.pipe(takeUntil(this._destroyed)).subscribe(
permissionPerSection => {
const canedit = permissionPerSection && permissionPerSection[this.item.dmpDescriptionTemplate.sectionId.toString()] && permissionPerSection[this.item.dmpDescriptionTemplate.sectionId.toString()].some(x => x === AppPermission.EditDescription);
this.formGroup = this.editorModel.buildForm(null, this.isDeleted || !canedit);
//this.visibilityRulesService.buildVisibilityRules(this.visibilityRulesService.getVisibilityRulesFromDescriptionTempalte(this.item.descriptionTemplate), this.formGroup);
// this.selectedSystemFields = this.selectedSystemFieldDisabled();
this.descriptionEditorService.setValidationErrorModel(this.editorModel.validationErrorModel);
if (this.editorModel.status == DescriptionStatus.Finalized || this.isDeleted) {
this.viewOnly = true;
this.formGroup.disable();
}else{
this.viewOnly = false;
}
this.registerFormListeners();
},
error => this.onCallbackError(error)
);
}
refreshData(): void {
this.getItem(this.editorModel.id, (data: Description) => this.prepareForm(data));
}
refreshOnNavigateToData(id?: Guid): void {
this.formGroup.markAsPristine();
if (this.isNew) {
let route = [];
route.push('/descriptions/overview/' + id);
this.router.navigate(route, { queryParams: { 'lookup': this.queryParamsService.serializeLookup(this.lookupParams), 'lv': ++this.lv }, replaceUrl: true, relativeTo: this.route });
} else {
this.refreshData();
}
}
persistEntity(onSuccess?: (response) => void): void {
const formData = this.formService.getValue(this.formGroup.value) as DescriptionPersist;
this.descriptionService.persist(formData)
.pipe(takeUntil(this._destroyed)).subscribe(
complete => onSuccess ? onSuccess(complete) : this.onCallbackSuccess(complete),
error => this.onCallbackError(error)
);
}
formSubmit(): void {
this.formService.removeAllBackEndErrors(this.formGroup);
this.formService.touchAllFormFields(this.formGroup);
if (!this.isFormValid()) {
return;
}
this.persistEntity();
}
public delete() {
const value = this.formGroup.value;
if (value.id) {
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.descriptionService.delete(value.id).pipe(takeUntil(this._destroyed))
.subscribe(
complete => this.onCallbackSuccess(),
error => this.onCallbackError(error)
);
}
});
}
}
clearErrorModel() {
this.editorModel.validationErrorModel.clear();
this.formService.validateAllFormFields(this.formGroup);
}
backToDmp() {
this.router.navigate(['/plans', 'edit', this.formGroup.get('dmpId').value]);
}
//
//
// Misc
//
//
isDirty() {
return this.formGroup.dirty; //TODO: check if needed //&& this.hasChanges; // do we need this.formGroup.dirty
}
hasReversableStatus(): boolean {
if (this.item?.dmp) {
return (this.item.dmp.status == DmpStatus.Draft && this.formGroup.get('status').value == DescriptionStatus.Finalized);
} else {
return false;
}
}
descriptionInfoValid(): boolean {
return this.formGroup.get('label') && this.formGroup.get('label').valid && this.formGroup.get('descriptionTemplateId') && this.formGroup.get('descriptionTemplateId').valid;
}
//
//
// Table of Contents
//
//
public changeStep(selected: ToCEntry = null, execute: boolean = true) {
if (execute) {
if (selected) {
let fieldSet = this.getFirstFieldSet(selected);
let index = this.visibleFieldSets.findIndex(entry => entry.id === fieldSet.id);
this.step = index + (selected.type === ToCEntryType.FieldSet ? 1 : 0.5);
} else {
this.step = 0;
this.resetScroll();
}
}
}
getFirstFieldSet(entry: ToCEntry): ToCEntry {
if (entry.type === ToCEntryType.FieldSet && !this.table0fContents.internalTable.hiddenEntries.find(hiddenEntry => hiddenEntry === entry.id.toString())) {
return entry;
} else {
let subEntries = entry.subEntries.filter(subEntry => !this.table0fContents.internalTable.hiddenEntries.find(hiddenEntry => hiddenEntry === subEntry.id.toString()));
if (subEntries.length > 0) {
return this.getFirstFieldSet(subEntries[0]);
} else {
return null;
}
}
}
private resetScroll() {
document.getElementById('description-editor-form').scrollTop = 0;
}
get visibleFieldSets(): ToCEntry[] {
let fieldSets = [];
let arrays = this.table0fContents ? this.table0fContents.tocentries.
filter(entry => !this.table0fContents.internalTable.hiddenEntries.find(hiddenEntry => hiddenEntry === entry.id.toString())).map(entry => {
return this.getEntryVisibleFieldSets(entry);
})
: [];
arrays.forEach(array => {
fieldSets = fieldSets.concat(array);
});
return fieldSets;
}
getEntryVisibleFieldSets(entry: ToCEntry): ToCEntry[] {
let fieldSets = [];
if (entry.type === ToCEntryType.FieldSet && !this.table0fContents.internalTable.hiddenEntries.find(hiddenEntry => hiddenEntry === entry.id.toString())) {
fieldSets.push(entry);
} else if (entry.type !== ToCEntryType.FieldSet) {
entry.subEntries.forEach(subEntry => {
fieldSets = fieldSets.concat(this.getEntryVisibleFieldSets(subEntry));
});
}
return fieldSets;
}
registerFormListeners() {
// // const dmpSubscription =
// this.formGroup.get('dmp').valueChanges
// .pipe(takeUntil(this._destroyed))
// .subscribe(x => {
// this.dmpValueChanged(x);
// });
// // const profileSubscription =
this.formGroup.get('descriptionTemplateId').valueChanges
.pipe(takeUntil(this._destroyed))
.subscribe(descriptionTemplateId => {
if (descriptionTemplateId) {
// this.showtocentriesErrors = false;
this.descriptionTemplateValueChanged(descriptionTemplateId);
// this.formChanged();
}
});
// // const labelSubscription =
// this.formGroup.get('label').valueChanges
// .pipe(takeUntil(this._destroyed))
// .subscribe(x => {
// this.formChanged();
// });
// // const descriptionSubscription =
// this.formGroup.get('description').valueChanges
// .pipe(takeUntil(this._destroyed))
// .subscribe(x => {
// this.formChanged();
// });
// // const uriSubscription =
// this.formGroup.get('uri').valueChanges
// .pipe(takeUntil(this._destroyed))
// .subscribe(x => {
// this.formChanged();
// });
// // const tagsSubscription =
// this.formGroup.get('tags').valueChanges
// .pipe(takeUntil(this._destroyed))
// .subscribe(x => {
// this.formChanged();
// });
// if (this.formGroup.get('descriptionProfileDefinition')) {
// // const descriptionProfileDefinitionSubscription =
// this.formGroup.get('descriptionProfileDefinition').valueChanges
// .pipe(takeUntil(this._destroyed))
// .subscribe(x => {
// this.formChanged();
// });
// // this._listenersSubscription.add(descriptionProfileDefinitionSubscription);
}
descriptionTemplateValueChanged(descriptionTemplateId: Guid) {
if (descriptionTemplateId != null) {
this.descriptionTemplateService.getSingle(descriptionTemplateId, DescriptionEditorResolver.descriptionTemplateLookupFields()).pipe(takeUntil(this._destroyed)).subscribe(descriptionTemplate => {
this.editorModel.properties = new DescriptionPropertyDefinitionEditorModel(this.editorModel.validationErrorModel).fromModel(null, descriptionTemplate, null);
this.formGroup.setControl('properties', this.editorModel.buildProperties());
this.item.descriptionTemplate = descriptionTemplate;
const sectionId = this.item.dmpDescriptionTemplate.sectionId;
this.item.dmpDescriptionTemplate = this.item.dmp.dmpDescriptionTemplates.find(x => x.sectionId == sectionId && x.descriptionTemplateGroupId == descriptionTemplate.groupId);
this.formGroup.get('dmpDescriptionTemplateId').setValue(this.item.dmpDescriptionTemplate.id);
});
// this.formGroup.removeControl('descriptionProfileDefinition');
// this.getDefinition(profiledId);
}
}
// // this._listenersSubscription.add(dmpSubscription);
// // this._listenersSubscription.add(profileSubscription);
// // this._listenersSubscription.add(labelSubscription);
// // this._listenersSubscription.add(descriptionSubscription);
// // this._listenersSubscription.add(uriSubscription);
// // this._listenersSubscription.add(tagsSubscription);
// }
// //
// //
// // Sections
// //
// //
// addSection(): void {
// const section: DescriptionDefinitionSectionEditorModel = new DescriptionDefinitionSectionEditorModel();
// section.id = Guid.create();
// section.ordinal = (this.formGroup.get('definition').get('sections') as FormArray).controls.length + 1;
// section.hasTemplates = false;
// (this.formGroup.get('definition').get('sections') as FormArray).push(section.buildForm()); //TODO: dtziotzios validation path
// }
// removeSection(sectionIndex: number): void {
// (this.formGroup.get('definition').get('sections') as FormArray).removeAt(sectionIndex);
// (this.formGroup.get('definition').get('sections') as FormArray).controls.forEach((section, index) => {
// section.get('ordinal').setValue(index + 1);
// });
// }
// dropSections(event: CdkDragDrop<string[]>) {
// const sectionsFormArray = (this.formGroup.get('definition').get('sections') as FormArray);
// moveItemInArray(sectionsFormArray.controls, event.previousIndex, event.currentIndex);
// sectionsFormArray.updateValueAndValidity();
// sectionsFormArray.controls.forEach((section, index) => {
// section.get('ordinal').setValue(index + 1);
// });
// }
// //
// //
// // Fields
// //
// //
// systemFieldDisabled(systemField: DescriptionSystemFieldType) {
// return (this.formGroup.get('definition').get('sections') as FormArray)?.controls.some(x => (x.get('fields') as FormArray).controls.some(y => (y as UntypedFormGroup).get('systemFieldType')?.value === systemField));
// // for (let section in (this.formGroup.get('definition').get('sections')as FormArray)?.controls) {
// // if (i != sectionIndex) {
// // for (let f of this.fieldsArray(i).controls) {
// // if ((f.get('category').value == FieldCategory.System || f.get('category').value == DescriptionSectionFieldCategory.System) && f.get('type').value == systemField) {
// // return true;
// // }
// // }
// // }
// // i++;
// // }
// // return false;
// }
// selectedSystemFieldDisabled(): Array<DescriptionSystemFieldType> {
// return (this.formGroup.get('definition').get('sections') as FormArray)?.controls.flatMap(x => (x.get('fields') as FormArray).controls.map(y => (y as UntypedFormGroup).get('systemFieldType')?.value as DescriptionSystemFieldType));
// }
// addSystemField(sectionIndex: number, systemFieldType: DescriptionSystemFieldType): void {
// const field: FieldInSectionEditorModel = new FieldInSectionEditorModel();
// field.id = Guid.create();
// field.ordinal = ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray).length + 1;
// field.category = DescriptionSectionFieldCategory.System;
// field.systemFieldType = systemFieldType;
// field.required = (systemFieldType == DescriptionSystemFieldType.TEXT || systemFieldType == DescriptionSystemFieldType.Description) ? true : false;
// ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray).push(field.buildForm()); //TODO: dtziotzios validation path
// }
// removeSystemField(sectionIndex: number, fieldIndex: number): void {
// const formArray = ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray);
// formArray.removeAt(fieldIndex);
// formArray.controls.forEach((section, index) => {
// section.get('ordinal').setValue(index + 1);
// });
// }
// addExtraField(sectionIndex: number): void {
// const field: FieldInSectionEditorModel = new FieldInSectionEditorModel();
// field.id = Guid.create();
// field.ordinal = ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray).length + 1;
// field.category = DescriptionSectionFieldCategory.Extra;
// ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray).push(field.buildForm()); //TODO: dtziotzios validation path
// }
// removeExtraField(sectionIndex: number, fieldIndex: number): void {
// const formArray = ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray);
// formArray.removeAt(fieldIndex);
// formArray.controls.forEach((section, index) => {
// section.get('ordinal').setValue(index + 1);
// });
// }
// dropFields(event: CdkDragDrop<string[]>, sectionIndex: number) {
// const fieldsFormArray = ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('fields') as FormArray);
// moveItemInArray(fieldsFormArray.controls, event.previousIndex, event.currentIndex);
// fieldsFormArray.updateValueAndValidity();
// fieldsFormArray.controls.forEach((section, index) => {
// section.get('ordinal').setValue(index + 1);
// });
// }
// //
// //
// // Autocomplete configuration
// //
// //
// filterDescriptionTempaltes(value: string): Observable<DatasetProfileModel[]> {
// const request = new DataTableRequest<DatasetProfileCriteria>(null, null, { fields: ['+label'] });
// const criteria = new DatasetProfileCriteria();
// criteria.like = value;
// request.criteria = criteria;
// return this.dmpService.searchDescriptions(request);
// }
// onRemoveDescritionTemplate(event, sectionIndex: number) {
// const descriptionTemplateFormArray = (this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('descriptionTemplates') as FormArray;
// const foundIndex = descriptionTemplateFormArray.controls.findIndex(blueprint => blueprint.get('descriptionTemplateId').value === event.id);
// if (foundIndex !== -1) {
// descriptionTemplateFormArray.removeAt(foundIndex);
// }
// }
// onSelectDescritionTemplate(item, sectionIndex) {
// const descriptionTemplate: DescriptionTemplatesInSectionEditorModel = new DescriptionTemplatesInSectionEditorModel();
// descriptionTemplate.id = Guid.create();
// descriptionTemplate.descriptionTemplateId = item.id;
// descriptionTemplate.label = item.label;
// ((this.formGroup.get('definition').get('sections') as FormArray).at(sectionIndex).get('descriptionTemplates') as FormArray).push(descriptionTemplate.buildForm()); //TODO: dtziotzios validation path
// }
public cancel(): void {
this.router.navigate(['/descriptions']);
}
finalize() {
this.formService.removeAllBackEndErrors(this.formGroup);
this.formService.touchAllFormFields(this.formGroup);
if (!this.isFormValid()) {
this.dialog.open(FormValidationErrorsDialogComponent, {
data: {
errorMessages: [this.language.instant('DESCRIPTION-EDITOR.MESSAGES.MISSING-FIELDS')]
}
})
this.formService.touchAllFormFields(this.formGroup);
return;
}
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
restoreFocus: false,
data: {
message: this.language.instant('DESCRIPTION-OVERVIEW.FINALIZE-DIALOG.TITLE'),
confirmButton: this.language.instant('DESCRIPTION-OVERVIEW.FINALIZE-DIALOG.CONFIRM'),
cancelButton: this.language.instant('DESCRIPTION-OVERVIEW.FINALIZE-DIALOG.NEGATIVE'),
isDeleteConfirmation: false
}
});
dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
if (result) {
this.formGroup.get('status').setValue(DescriptionStatus.Finalized);
this.persistEntity();
}});
}
reverse() {
const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
restoreFocus: false,
data: {
message: this.language.instant('DESCRIPTION-EDITOR.ACTIONS.UNDO-FINALIZATION-QUESTION'),
confirmButton: this.language.instant('DESCRIPTION-EDITOR.ACTIONS.CONFIRM'),
cancelButton: this.language.instant('DESCRIPTION-EDITOR.ACTIONS.REJECT'),
isDeleteConfirmation: false
}
});
dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
if (result) {
const dmpUserRemovePersist: DescriptionStatusPersist = {
id: this.formGroup.get('id').value,
status: DescriptionStatus.Draft,
hash: this.formGroup.get('hash').value
};
this.descriptionService.persistStatus(dmpUserRemovePersist, DescriptionEditorResolver.lookupFields()).pipe(takeUntil(this._destroyed))
.subscribe(data => {
this.prepareForm(data);
this.onCallbackSuccess()
}, (error: any) => {
this.onCallbackError(error)
});
}});
}
}
// export class DescriptionEditorComponent extends CheckDeactivateBaseComponent implements OnInit {//IBreadCrumbComponent
// canDeactivate(): boolean {
// return !this.isDirty();
// }
// // breadCrumbs: Observable<BreadcrumbItem[]>;
// viewOnly = false;
// editMode = false;
// publicMode = false;
// hasChanges = false;
// isDiscarded = false;
// formGroupRawValue: any;
// saving = false;
// DescriptionStatus = DescriptionStatus;
// dmpAutoCompleteConfiguration: SingleAutoCompleteConfiguration;
// descriptionModel: DescriptionEditorModel;
// isNew = true;
// isCopy = false;
// formGroup: UntypedFormGroup = null;
// descriptionProfileDefinitionModel: DescriptionDescriptionFormEditorModel;
// availableProfiles: DescriptionProfileModel[] = [];
// finalize: boolean = false;
// itemId: string;
// dmpId: string;
// dmpSectionIndex: number;
// availableDescriptionTemplates: DescriptionProfileModel[] = [];
// newDmpId: string;
// publicId: string;
// profileUpdateId: string;
// downloadDocumentId: string;
// isLinear = false;
// lock: LockModel;
// lockStatus: Boolean;
// step: number = 0;
// stepOffset: number = 1;
// saveAnd = SaveType;
// descriptionSavedLinks: any = null;
// scrollTop: number;
// tocScrollTop: number;
// links: Link[] = [];
// //the table seraches for elements to scroll on page with id (TOCENTRY_ID_PREFIX+fieldsetId<Tocentry>)
// TOCENTRY_ID_PREFIX = "TocEntRy";
// showtocentriesErrors = false;
// @ViewChild('table0fContents') table0fContents: TableOfContents;
// hintErrors: boolean = false;
// descriptionIsOnceSaved = false;
// fieldsetIdWithFocus: string;
// visRulesService: VisibilityRulesService;
// constructor(
// private descriptionService: DescriptionService,
// private route: ActivatedRoute,
// public snackBar: MatSnackBar,
// public router: Router,
// public language: TranslateService,
// public externalSourcesService: ExternalSourcesService,
// public dialog: MatDialog,
// public externalSourcesConfigurationService: ExternalSourcesConfigurationService,
// private uiNotificationService: UiNotificationService,
// private formService: FormService,
// private lockService: LockService,
// private location: Location,
// private authService: AuthService,
// private configurationService: ConfigurationService,
// private httpClient: HttpClient,
// private matomoService: MatomoService,
// private fileUtils: FileUtils
// ) {
// super();
// }
// ngOnInit() {
// this.matomoService.trackPageView('Description Editor');
// this.route
// .data
// .pipe(takeUntil(this._destroyed))
// .subscribe(v => {
// this.viewOnly = v['public'];
// });
// const dmpRequestItem: RequestItem<DmpCriteria> = new RequestItem();
// dmpRequestItem.criteria = new DmpCriteria();
// this.dmpAutoCompleteConfiguration = {
// filterFn: this.searchDmp.bind(this),
// initialItems: (extraData) => this.searchDmp(''),
// displayFn: (item) => this.getDescriptionDisplay(item),
// titleFn: (item) => item['label'],
// subtitleFn: (item) => this.language.instant('DATASET-WIZARD.FIRST-STEP.SUB-TITLE') + new Date(item['creationTime']).toISOString()
// // iconFn: (item) => this.publicMode ? '' : (item['status'] ? 'lock' : 'lock_open'),
// // linkFn: (item) => this.publicMode ? '/explore-plans/overview/' + item['id'] : '/plans/overview/' + item['id']
// };
// const params = this.route.snapshot.params;
// const queryParams = this.route.snapshot.queryParams;
// const data: any = this.route.snapshot.data;
// this.itemId = params['id'];
// this.dmpId = params['dmpId'];
// this.dmpSectionIndex = parseInt(params['dmpSectionIndex']);
// this.newDmpId = queryParams['newDmpId'];
// this.publicId = params['publicId'];
// this.profileUpdateId = params['updateId'];
// this.finalize = data.finalize;
// this.itemId ? this.downloadDocumentId = this.itemId : this.downloadDocumentId = this.publicId
// this.init();
// // this.route.params
// // .pipe(takeUntil(this._destroyed))
// // .subscribe((params: Params) => {
// // const itemId = params['id'];
// // if (itemId != null) { setTimeout(() => this.stepper.selectedIndex = 2); }
// // });
// }
// init() {
// if (this.itemId != null && this.newDmpId == null) {
// this.isNew = false;
// this.descriptionService.getSingle(this.itemId)
// .pipe(takeUntil(this._destroyed))
// .subscribe(data => {
// this.lockService.checkLockStatus(data.id).pipe(takeUntil(this._destroyed)).subscribe(lockStatus => {
// this.lockStatus = lockStatus;
// this.descriptionModel = new DescriptionEditorModel().fromModel(data);
// this.dmpSectionIndex = this.descriptionModel.dmpSectionIndex;
// this.needsUpdate();
// // this.breadCrumbs = observableOf([
// // {
// // parentComponentName: null,
// // label: this.descriptionModel.label,
// // url: '/descriptions/edit/' + this.descriptionModel.id,
// // notFoundResolver: [
// // {
// // parentComponentName: null,
// // label: this.language.instant('NAV-BAR.MY-DATASET-DESCRIPTIONS').toUpperCase(),
// // url: '/descriptions'
// // },
// // ]
// // }]);
// this.formGroup = this.descriptionModel.buildForm();
// let profiles = this.descriptionModel.dmp.profiles.filter(profile => profile.data.dmpSectionIndex.includes(this.descriptionModel.dmpSectionIndex));
// for (var profile of profiles) {
// this.availableDescriptionTemplates.push({ id: profile.descriptionTemplateId, label: profile.label, description: "" })
// }
// this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
// this.editMode = this.descriptionModel.status === DescriptionStatus.Draft;
// if (this.descriptionModel.status === DescriptionStatus.Finalized || lockStatus) {
// this.formGroup.disable();
// this.viewOnly = true;
// }
// if (!lockStatus && !isNullOrUndefined(this.authService.currentAccountIsAuthenticated())) {
// const lockedBy: UserInfoListingModel = {
// email: this.authService.getUserProfileEmail(),
// id: this.authService.userId()?.toString(),
// name: this.authService.getPrincipalName(),
// role: 0 //TODO
// //role: this.authService.getRoles()?.at(0)
// }
// this.lock = new LockModel(data.id, lockedBy);
// this.lockService.createOrUpdate(this.lock).pipe(takeUntil(this._destroyed)).subscribe(async result => {
// this.lock.id = Guid.parse(result);
// interval(this.configurationService.lockInterval).pipe(takeUntil(this._destroyed)).subscribe(() => this.pumpLock());
// });
// }
// // if (this.viewOnly) { this.formGroup.disable(); } // For future use, to make Description edit like DMP.
// this.loadDescriptionProfiles();
// this.registerFormListeners();
// if (lockStatus) {
// this.dialog.open(PopupNotificationDialogComponent, {
// data: {
// title: this.language.instant('DATASET-WIZARD.LOCKED.TITLE'),
// message: this.language.instant('DATASET-WIZARD.LOCKED.MESSAGE')
// }, maxWidth: '30em'
// });
// }
// if (this.finalize && !this.lockStatus && !this.viewOnly) {
// setTimeout(() => {
// this.saveFinalize();
// }, 0);
// }
// // this.availableProfiles = this.descriptionModel.dmp.profiles;
// });
// },
// error => {
// switch (error.status) {
// case 403:
// this.uiNotificationService.snackBarNotification(this.language.instant('DATASET-WIZARD.MESSAGES.DATASET-NOT-ALLOWED'), SnackBarNotificationLevel.Error);
// break;
// case 404:
// this.uiNotificationService.snackBarNotification(this.language.instant('DATASET-WIZARD.MESSAGES.DATASET-NOT-FOUND'), SnackBarNotificationLevel.Error);
// break;
// default:
// this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.ERRORS.HTTP-REQUEST-ERROR'), SnackBarNotificationLevel.Error);
// }
// this.router.navigate(['/descriptions/']);
// return observableOf(null);
// });
// } else if (this.dmpId != null) {
// this.isNew = true;
// this.dmpService.getSingle(this.dmpId).pipe(map(data => data as DmpModel))
// .pipe(takeUntil(this._destroyed))
// .subscribe(data => {
// this.descriptionModel = new DescriptionEditorModel();
// setTimeout(() => {
// this.descriptionModel.dmp = data;
// this.descriptionModel.dmpSectionIndex = this.dmpSectionIndex;
// this.formGroup = this.descriptionModel.buildForm();
// let profiles = this.descriptionModel.dmp.profiles.filter(profile => profile.data.dmpSectionIndex.includes(this.dmpSectionIndex));
// for (var profile of profiles) {
// this.availableDescriptionTemplates.push({ id: profile.descriptionTemplateId, label: profile.label, description: "" })
// }
// this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
// this.editMode = this.descriptionModel.status === DescriptionStatus.Draft;
// this.formGroup.get('dmp').disable();
// const dialogRef = this.dialog.open(PrefillDescriptionComponent, {
// width: '590px',
// minHeight: '200px',
// restoreFocus: false,
// data: {
// availableProfiles: this.availableDescriptionTemplates,
// descriptionFormGroup: this.formGroup
// },
// panelClass: 'custom-modalbox'
// });
// dialogRef.afterClosed().subscribe(result => {
// if (result) {
// this.descriptionModel = this.descriptionModel.fromModel(result);
// this.descriptionModel.dmp = data;
// this.descriptionModel.dmpSectionIndex = this.dmpSectionIndex;
// this.formGroup = this.descriptionModel.buildForm();
// this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
// this.formGroup.get('dmp').disable();
// this.loadDescriptionProfiles();
// this.registerFormListeners();
// }
// })
// this.loadDescriptionProfiles();
// this.registerFormListeners();
// // this.availableProfiles = data.profiles;
// // this.breadCrumbs = observableOf([
// // {
// // parentComponentName: null,
// // label: this.language.instant('NAV-BAR.MY-DATASET-DESCRIPTIONS'),
// // url: '/descriptions',
// // notFoundResolver: [
// // // {
// // // parentComponentName: null,
// // // label: this.descriptionModel.dmp.grant.label,
// // // url: '/grants/edit/' + this.descriptionModel.dmp.grant.id
// // // },
// // {
// // parentComponentName: null,
// // label: this.descriptionModel.dmp.label,
// // url: '/plans/edit/' + this.descriptionModel.dmp.id,
// // }]
// // }]);
// });
// });
// } else if (this.newDmpId != null) {
// this.isNew = false;
// this.isCopy = true;
// this.descriptionService.getSingle(this.itemId)
// .pipe(takeUntil(this._destroyed))
// .subscribe(data => {
// this.lockService.checkLockStatus(data.id).pipe(takeUntil(this._destroyed)).subscribe(lockStatus => {
// this.lockStatus = lockStatus;
// this.descriptionModel = new DescriptionEditorModel().fromModel(data);
// this.dmpSectionIndex = this.descriptionModel.dmpSectionIndex;
// this.descriptionModel.status = 0;
// this.formGroup = this.descriptionModel.buildForm();
// this.formGroup.get('id').setValue(null);
// this.dmpService.getSingleNoDescriptions(this.newDmpId).pipe(map(data => data as DmpModel))
// .pipe(takeUntil(this._destroyed))
// .subscribe(data => {
// setTimeout(() => {
// this.descriptionModel.dmp = data;
// this.formGroup.get('dmp').setValue(this.descriptionModel.dmp);
// this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
// this.loadDescriptionProfiles();
// // this.breadCrumbs = observableOf([
// // {
// // parentComponentName: null,
// // label: this.language.instant('NAV-BAR.MY-DATASET-DESCRIPTIONS'),
// // url: '/descriptions',
// // notFoundResolver: [
// // // {
// // // parentComponentName: null,
// // // label: this.descriptionModel.dmp.grant.label,
// // // url: '/grants/edit/' + this.descriptionModel.dmp.grant.id
// // // },
// // {
// // parentComponentName: null,
// // label: this.descriptionModel.dmp.label,
// // url: '/plans/edit/' + this.descriptionModel.dmp.id,
// // }
// // ]
// // }]);
// });
// });
// this.editMode = this.descriptionModel.status === DescriptionStatus.Draft;
// if (this.descriptionModel.status === DescriptionStatus.Finalized || lockStatus) {
// this.formGroup.disable();
// this.viewOnly = true;
// }
// if (!lockStatus && !isNullOrUndefined(this.authService.currentAccountIsAuthenticated())) {
// const lockedBy: UserInfoListingModel = {
// email: this.authService.getUserProfileEmail(),
// id: this.authService.userId()?.toString(),
// name: this.authService.getPrincipalName(),
// role: 0 //TODO
// //role: this.authService.getRoles()?.at(0)
// }
// this.lock = new LockModel(data.id, lockedBy);
// this.lockService.createOrUpdate(this.lock).pipe(takeUntil(this._destroyed)).subscribe(async result => {
// this.lock.id = Guid.parse(result);
// interval(this.configurationService.lockInterval).pipe(takeUntil(this._destroyed)).subscribe(() => this.pumpLock());
// });
// }
// // if (this.viewOnly) { this.formGroup.disable(); } // For future use, to make Description edit like DMP.
// this.loadDescriptionProfiles();
// // this.availableProfiles = data.dmp.profiles;
// })
// });
// } else if (this.publicId != null) { // For Finalized -> Public Descriptions
// this.isNew = false;
// this.descriptionService.getSinglePublic(this.publicId)
// .pipe(takeUntil(this._destroyed)).pipe(
// catchError((error: any) => {
// this.uiNotificationService.snackBarNotification(error.error.message, SnackBarNotificationLevel.Error);
// this.router.navigate(['/descriptions/publicEdit/' + this.publicId]);
// return observableOf(null);
// }))
// .subscribe(data => {
// if (data) {
// this.descriptionModel = new DescriptionEditorModel().fromModel(data);
// this.formGroup = this.descriptionModel.buildForm();
// this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
// this.formGroup.disable();
// this.viewOnly = true;
// this.editMode = this.descriptionModel.status === DescriptionStatus.Draft;
// this.formGroup.get('dmp').setValue(this.descriptionModel.dmp);
// const breadcrumbs = [];
// breadcrumbs.push({
// parentComponentName: null,
// label: this.language.instant('NAV-BAR.PUBLIC DATASETS'),
// url: '/explore-descriptions'
// });
// breadcrumbs.push({
// parentComponentName: null,
// label: this.descriptionModel.label,
// url: '/descriptions/publicEdit/' + this.descriptionModel.id
// });
// // this.breadCrumbs = observableOf(breadcrumbs);
// }
// });
// this.publicMode = true;
// } else if (this.profileUpdateId != null) {
// this.descriptionService.updateDescriptionProfile(this.profileUpdateId)
// .pipe(takeUntil(this._destroyed))
// .subscribe(data => {
// this.descriptionModel = new DescriptionEditorModel().fromModel(data);
// this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
// this.needsUpdate();
// // this.breadCrumbs = observableOf([
// // {
// // parentComponentName: null,
// // label: this.language.instant('NAV-BAR.MY-DATASET-DESCRIPTIONS'),
// // url: '/descriptions',
// // notFoundResolver: [
// // // {
// // // parentComponentName: null,
// // // label: this.descriptionModel.dmp.grant.label,
// // // url: '/grants/edit/' + this.descriptionModel.dmp.grant.id
// // // },
// // {
// // parentComponentName: null,
// // label: this.descriptionModel.dmp.label,
// // url: '/plans/edit/' + this.descriptionModel.dmp.id,
// // },
// // ]
// // }]);
// this.formGroup = this.descriptionModel.buildForm();
// this.editMode = this.descriptionModel.status === DescriptionStatus.Draft;
// if (this.descriptionModel.status === DescriptionStatus.Finalized) {
// this.formGroup.disable();
// this.viewOnly = true;
// }
// // if (this.viewOnly) { this.formGroup.disable(); } // For future use, to make Description edit like DMP.
// this.loadDescriptionProfiles();
// });
// } else {
// this.descriptionModel = new DescriptionEditorModel();
// this.formGroup = this.descriptionModel.buildForm();
// this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
// this.editMode = this.descriptionModel.status === DescriptionStatus.Draft;
// if (this.descriptionModel.status === DescriptionStatus.Finalized) {
// this.formGroup.disable();
// this.viewOnly = true;
// }
// //if (this.viewOnly) { this.formGroup.disable(); } // For future use, to make Description edit like DMP.
// this.registerFormListeners();
// this.dmpValueChanged(null);
// // this.breadCrumbs = observableOf([
// // {
// // parentComponentName: null,
// // label: this.language.instant('DATASET-LISTING.ACTIONS.CREATE-NEW').toUpperCase(),
// // url: '/descriptions/new/'
// // }]);
// }
// }
// // private _listenersSubscription:Subscription = new Subscription();
// registerFormListeners() {
// // const dmpSubscription =
// this.formGroup.get('dmp').valueChanges
// .pipe(takeUntil(this._destroyed))
// .subscribe(x => {
// this.dmpValueChanged(x);
// });
// // const profileSubscription =
// this.formGroup.get('profile').valueChanges
// .pipe(takeUntil(this._destroyed))
// .subscribe(x => {
// if (x) {
// this.showtocentriesErrors = false;
// this.descriptionProfileValueChanged(x.id);
// this.formChanged();
// }
// });
// // const labelSubscription =
// this.formGroup.get('label').valueChanges
// .pipe(takeUntil(this._destroyed))
// .subscribe(x => {
// this.formChanged();
// });
// // const descriptionSubscription =
// this.formGroup.get('description').valueChanges
// .pipe(takeUntil(this._destroyed))
// .subscribe(x => {
// this.formChanged();
// });
// // const uriSubscription =
// this.formGroup.get('uri').valueChanges
// .pipe(takeUntil(this._destroyed))
// .subscribe(x => {
// this.formChanged();
// });
// // const tagsSubscription =
// this.formGroup.get('tags').valueChanges
// .pipe(takeUntil(this._destroyed))
// .subscribe(x => {
// this.formChanged();
// });
// if (this.formGroup.get('descriptionProfileDefinition')) {
// // const descriptionProfileDefinitionSubscription =
// this.formGroup.get('descriptionProfileDefinition').valueChanges
// .pipe(takeUntil(this._destroyed))
// .subscribe(x => {
// this.formChanged();
// });
// // this._listenersSubscription.add(descriptionProfileDefinitionSubscription);
// }
// // this._listenersSubscription.add(dmpSubscription);
// // this._listenersSubscription.add(profileSubscription);
// // this._listenersSubscription.add(labelSubscription);
// // this._listenersSubscription.add(descriptionSubscription);
// // this._listenersSubscription.add(uriSubscription);
// // this._listenersSubscription.add(tagsSubscription);
// }
// // private _unregisterFormListeners(){
// // this._listenersSubscription.unsubscribe();
// // this._listenersSubscription = new Subscription();
// // }
// dmpValueChanged(dmp: DmpListingModel) {
// if (dmp) {
// this.formGroup.get('profile').enable();
// this.loadDescriptionProfiles();
// } else {
// this.availableProfiles = [];
// this.formGroup.get('profile').reset();
// this.formGroup.get('profile').disable();
// this.formGroup.removeControl('descriptionProfileDefinition');
// }
// }
// descriptionProfileValueChanged(profiledId: string) {
// if (profiledId && profiledId.length > 0) {
// this.formGroup.removeControl('descriptionProfileDefinition');
// this.getDefinition(profiledId);
// }
// }
// searchDmp(query: string): Observable<DmpListingModel[]> {
// const fields: Array<string> = new Array<string>();
// fields.push('-created');
// const dmpDataTableRequest: DataTableRequest<DmpCriteria> = new DataTableRequest(0, null, { fields: fields });
// dmpDataTableRequest.criteria = new DmpCriteria();
// dmpDataTableRequest.criteria.like = query;
// dmpDataTableRequest.criteria.status = DmpStatus.Draft;
// return this.dmpService.getPaged(dmpDataTableRequest, "autocomplete").pipe(map(x => x.data));
// }
// loadDescriptionProfiles() {
// const descriptionProfileRequestItem: RequestItem<DescriptionProfileCriteria> = new RequestItem();
// descriptionProfileRequestItem.criteria = new DescriptionProfileCriteria();
// descriptionProfileRequestItem.criteria.id = this.formGroup.get('dmp').value.id;
// if (descriptionProfileRequestItem.criteria.id) {
// this.descriptionService.getAvailableProfiles(descriptionProfileRequestItem)
// .pipe(takeUntil(this._destroyed))
// .subscribe(items => {
// this.availableProfiles = items;
// });
// }
// }
// public formChanged() {
// if (!this.isDiscarded) {
// this.hasChanges = true;
// }
// }
// public cancel(): void {
// if (!isNullOrUndefined(this.lock)) {
// this.lockService.unlockTarget(this.descriptionModel.id).pipe(takeUntil(this._destroyed)).subscribe(
// complete => {
// this.publicMode ? this.router.navigate(['/explore']) : this.router.navigate(['/descriptions']);
// },
// error => {
// this.formGroup.get('status').setValue(DmpStatus.Draft);
// this.onCallbackError(error);
// }
// )
// } else {
// this.publicMode ? this.router.navigate(['/explore']) : this.router.navigate(['/descriptions']);
// }
// }
// getDescriptionDisplay(item: any): string {
// if (!this.publicMode) {
// return (item['status'] ? this.language.instant('TYPES.DATASET-STATUS.FINALISED').toUpperCase() : this.language.instant('TYPES.DATASET-STATUS.DRAFT').toUpperCase()) + ': ' + item['label'];
// } else {
// return item['label'];
// }
// }
// getDefinition(profileId: string) {
// // if (this.formGroup.invalid) { setTimeout(() => this.stepper.selectedIndex = 0); return; }
// this.descriptionService.getDefinition(profileId)
// .pipe(takeUntil(this._destroyed))
// .subscribe(item => {
// this.descriptionModel.descriptionProfileDefinition = new DescriptionDescriptionFormEditorModel().fromModel(item);
// this.descriptionProfileDefinitionModel = this.descriptionModel.descriptionProfileDefinition;
// this.formGroup.addControl('descriptionProfileDefinition', this.descriptionProfileDefinitionModel.buildForm());
// // const descriptionProfileDefinitionForm = this.descriptionProfileDefinitionModel.buildForm();
// // let profId = null;
// // try{
// // profId = this.formGroup.get('profile').value.id;
// // }catch{
// // }
// // if(this.formGroupRawValue && this.formGroupRawValue.descriptionProfileDefinition && (this.formGroupRawValue.profile.id === profId)){
// // // this.formGroup.get('descriptionProfileDefinition').patchValue( this.formGroupRawValue.descriptionProfileDefinition);
// // descriptionProfileDefinitionForm.patchValue(this.formGroupRawValue.descriptionProfileDefinition);
// // }
// // this.formGroup.addControl('descriptionProfileDefinition', descriptionProfileDefinitionForm);
// this.formGroup.get('descriptionProfileDefinition').valueChanges
// .pipe(debounceTime(600))
// .pipe(takeUntil(this._destroyed))
// .subscribe(x => {
// this.formChanged();
// });
// });
// }
// // formSubmit(): void {
// // if (!this.isFormValid()) { return; }
// // this.onSubmit();
// // }
// public isFormValid() {
// return this.formGroup.valid;
// }
// public isSemiFormValid(formGroup: UntypedFormGroup): boolean {
// var isValid: boolean = true;
// Object.keys(formGroup.controls).forEach(controlName => {
// if (controlName != 'descriptionProfileDefinition' && !formGroup.get(controlName).disabled && !(formGroup.get(controlName).valid)) {
// isValid = false;
// }
// });
// return isValid;
// }
// // onSubmit(): void {
// // this.descriptionService.createDescription(this.formGroup.value)
// // .pipe(takeUntil(this._destroyed))
// // .subscribe(
// // complete => {
// // this.descriptionService.getSingle(complete.id)
// // .pipe(takeUntil(this._destroyed))
// // .subscribe(
// // result => {
// // this.descriptionModel = new DescriptionEditorModel().fromModel(result);
// // }
// // );
// // this.onCallbackSuccess();
// // },
// // error => this.onCallbackError(error)
// // );
// // }
// submit(saveType?: SaveType, onSuccess: Function = null, onError: Function = null) {
// this.scrollTop = document.getElementById('description-editor-form').scrollTop;
// this.tocScrollTop = document.getElementById('stepper-options').scrollTop;
// this.descriptionService.createDescription(this.formGroup.getRawValue())
// .pipe(takeUntil(this._destroyed))
// .subscribe(
// data => {
// this.hasChanges = false;
// this.descriptionIsOnceSaved = true;
// this.onCallbackSuccess(data, saveType);
// if (onSuccess) {
// onSuccess();
// }
// },
// error => {
// if (onError) {
// onError();
// }
// this.onCallbackError(error)
// });
// }
// private _getErrorMessage(formControl: AbstractControl, name: string): string[] {
// const errors: string[] = [];
// Object.keys(formControl.errors).forEach(key => {
// if (key === 'required') {
// errors.push(this.language.instant(name + ": " + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.REQUIRED')));
// }
// // if (key === 'required') { errors.push(this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.THIS-FIELD') + ' "' + this.getPlaceHolder(formControl) + '" ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.HAS-ERROR') + ', ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.REQUIRED')); }
// else if (key === 'email') {
// errors.push(this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.THIS-FIELD') + ' "' + name + '" ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.HAS-ERROR') + ', ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.EMAIL'));
// } else if (key === 'min') {
// errors.push(this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.THIS-FIELD') + ' "' + name + '" ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.HAS-ERROR') + ', ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.MIN-VALUE', { 'min': formControl.getError('min').min }));
// } else if (key === 'max') {
// errors.push(this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.THIS-FIELD') + ' "' + name + '" ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.HAS-ERROR') + ', ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.MAX-VALUE', { 'max': formControl.getError('max').max }));
// } else {
// errors.push(this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.THIS-FIELD') + ' "' + name + '" ' + this.language.instant('GENERAL.FORM-VALIDATION-DISPLAY-DIALOG.HAS-ERROR') + ', ' + formControl.errors[key].message);
// }
// });
// return errors;
// }
// private _getPlaceHolder(formControl: any): string {
// if (formControl.nativeElement.localName === 'input' || formControl.nativeElement.localName === 'textarea'
// || formControl.nativeElement.localName === 'richTextarea') {
// return formControl.nativeElement.getAttribute('placeholder');
// } else if (formControl.nativeElement.localName === 'mat-select') {
// return formControl.nativeElement.getAttribute('placeholder');
// } else if (formControl.nativeElement.localName === 'app-single-auto-complete') {
// return (Array.from(formControl.nativeElement.firstChild.children).filter((x: any) => x.localName === 'input')[0] as any).getAttribute('placeholder');
// } else if (formControl.nativeElement.localName === 'app-multiple-auto-complete') {
// return (Array.from(formControl.nativeElement.firstChild.firstChild.firstChild.children).filter((x: any) => x.localName === 'input')[0] as any).getAttribute('placeholder');
// }
// }
// private _buildSemiFormErrorMessages(): string[] {//not including descriptionProfileDefinition
// const errmess: string[] = [];
// Object.keys(this.formGroup.controls).forEach(controlName => {
// if (controlName != 'descriptionProfileDefinition' && this.formGroup.get(controlName).invalid) {
// errmess.push(...this._buildErrorMessagesForAbstractControl(this.formGroup.get(controlName), controlName));
// }
// })
// return errmess;
// }
// // takes as an input an abstract control and gets its error messages[]
// private _buildErrorMessagesForAbstractControl(aControl: AbstractControl, controlName: string): string[] {
// const errmess: string[] = [];
// if (aControl.invalid) {
// if (aControl.errors) {
// //check if has placeholder
// if ((<any>aControl).nativeElement !== undefined && (<any>aControl).nativeElement !== null) {
// const placeholder = this._getPlaceHolder(aControl);
// if (placeholder) {
// controlName = placeholder;
// }
// }
// const errorMessage = this._getErrorMessage(aControl, controlName);
// errmess.push(...errorMessage);
// }
// /*in case the aControl is FormControl then the it should have provided its error messages above.
// No need to check case of FormControl below*/
// if (aControl instanceof UntypedFormGroup) {
// const fg = aControl as UntypedFormGroup;
// //check children
// Object.keys(fg.controls).forEach(controlName => {
// errmess.push(...this._buildErrorMessagesForAbstractControl(fg.get(controlName), controlName));
// });
// } else if (aControl instanceof UntypedFormArray) {
// const fa = aControl as UntypedFormArray;
// fa.controls.forEach((control, index) => {
// errmess.push(...this._buildErrorMessagesForAbstractControl(control, `${controlName} --> ${index + 1}`));
// });
// }
// }
// return errmess;
// }
// save(saveType?: SaveType) {
// this.saving = true;
// Object.keys(this.formGroup.controls).forEach(controlName => {
// if (controlName == 'descriptionProfileDefinition') {
// return;
// }
// this.formService.touchAllFormFields(this.formGroup.get(controlName));
// })
// // this.formService.touchAllFormFields(this.formGroup);
// if (!this.isSemiFormValid(this.formGroup)) {
// //build messages
// const errorMessages = this._buildSemiFormErrorMessages();
// this.showValidationErrorsDialog(undefined, errorMessages);
// this.hintErrors = true;
// this.saving = false;
// return;
// }
// this.submit(saveType);
// }
// private showValidationErrorsDialog(projectOnly?: boolean, errmess?: string[]) {
// if (errmess) {
// const dialogRef = this.dialog.open(FormValidationErrorsDialogComponent, {
// disableClose: true,
// autoFocus: false,
// restoreFocus: false,
// data: {
// errorMessages: errmess,
// projectOnly: projectOnly
// },
// });
// } else {
// const dialogRef = this.dialog.open(FormValidationErrorsDialogComponent, {
// disableClose: true,
// autoFocus: false,
// restoreFocus: false,
// data: {
// formGroup: this.formGroup,
// projectOnly: projectOnly
// },
// });
// }
// }
// hasNotReversableStatus(): boolean {
// if (this.formGroup.get('dmp').value && !this.publicMode) {
// return (this.formGroup.get('dmp').value.status == DmpStatus.Finalized && this.formGroup.get('status').value == DescriptionStatus.Finalized);
// } else {
// return false;
// }
// }
// reverse() {
// this.dialog.open(ConfirmationDialogComponent, {
// data: {
// message: this.language.instant('DATASET-WIZARD.ACTIONS.UNDO-FINALIZATION-QUESTION'),
// confirmButton: this.language.instant('DATASET-WIZARD.ACTIONS.CONFIRM'),
// cancelButton: this.language.instant('DATASET-WIZARD.ACTIONS.REJECT'),
// },
// maxWidth: '30em'
// })
// .afterClosed()
// .pipe(
// filter(x => x),
// takeUntil(this._destroyed)
// ).subscribe(result => {
// if (result) {
// // if (!this.isFormValid()) { return; }
// this.formGroup.get('status').setValue(DescriptionStatus.Draft);
// this.submit(SaveType.finalize, () => {
// this.viewOnly = false;
// this.descriptionModel.status = DescriptionStatus.Draft;
// setTimeout(x => {
// this.formGroup = null;
// });
// setTimeout(x => {
// this.formGroup = this.descriptionModel.buildForm();
// this.registerFormListeners();
// });
// }, () => {
// this.formGroup.get('status').setValue(DescriptionStatus.Finalized);
// this.viewOnly = true;
// });
// } else {
// this.saving = false;
// }
// });
// }
// saveFinalize() {
// // this.formService.touchAllFormFields(this.formGroup);
// this.saving = true;
// if (!this.isSemiFormValid(this.formGroup) || (this.table0fContents && this.table0fContents.hasVisibleInvalidFields())) {
// // this.showValidationErrorsDialog();
// this.dialog.open(FormValidationErrorsDialogComponent, {
// data: {
// errorMessages: [this.language.instant('DATASET-WIZARD.MESSAGES.MISSING-FIELDS')]
// }
// })
// this.touchForm();
// this.hintErrors = true;
// this.saving = false;
// return;
// }
// const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
// restoreFocus: false,
// data: {
// message: this.language.instant('GENERAL.CONFIRMATION-DIALOG.FINALIZE-ITEM'),
// confirmButton: this.language.instant('QUICKWIZARD.SAVE-DIALOG.ACTIONS.AFFIRMATIVE'),
// cancelButton: this.language.instant('QUICKWIZARD.SAVE-DIALOG.ACTIONS.NEGATIVE'),
// isDeleteConfirmation: false
// }
// });
// dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
// if (result) {
// // if (!this.isFormValid()) { return; }
// this.formGroup.get('status').setValue(DescriptionStatus.Finalized);
// this.submit(SaveType.finalize, null, () => {
// this.formGroup.get('status').setValue(DescriptionStatus.Draft);
// });
// } else {
// this.saving = false;
// }
// });
// }
// onCallbackSuccess(data?: DescriptionModel, saveType?: SaveType): void {
// this.uiNotificationService.snackBarNotification(this.isNew ? this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-CREATION') : this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success);
// if (data) {
// if (saveType === this.saveAnd.addNew) {
// this.router.navigate(['/reload']).then(() => {
// this.router.navigate(['/descriptions', 'new', this.formGroup.get('dmp').value.id, this.dmpSectionIndex]);
// })
// } else if (saveType === this.saveAnd.close) {
// this.router.navigate(['/reload']).then(() => {
// this.router.navigate(['/plans', 'edit', this.formGroup.get('dmp').value.id]);
// });
// } else if (saveType === SaveType.finalize) {
// this.router.navigate(['/reload']).then(() => {
// this.router.navigate(['/descriptions', 'edit', data.id]);
// });
// } else {
// this.descriptionModel = new DescriptionEditorModel().fromModel(data);
// this.editMode = this.descriptionModel.status === DescriptionStatus.Draft;
// // setTimeout(() => { this.formGroup = null; });
// setTimeout(() => {
// this.formGroup.get('id').patchValue(data.id);
// this.formGroup.get('modified').patchValue(data.modified);
// this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue()));
// this.hasChanges = false;
// // this.formGroup = this.descriptionModel.buildForm();
// // if (this.formGroup.get('descriptionProfileDefinition')) {
// // this.formGroup.removeControl('descriptionProfileDefinition');
// // this.getDefinition(data.profile.id);
// // this.maxStep = 1;
// // } else {
// // this.getDefinition(data.profile.id);
// // this.maxStep = 1;
// // }
// });
// setTimeout(() => {
// document.getElementById('description-editor-form').scrollTop = this.scrollTop;
// document.getElementById('stepper-options').scrollTop = this.tocScrollTop;
// }, 500);
// this.saving = false;
// if (this.isNew) {
// this.reloadDateset(this.descriptionModel.id);
// }
// // this.router.navigate(['/reload']).then(() => { this.router.navigate(['/descriptions', 'edit', data.id]); });
// }
// } else {
// this.router.navigate(['/descriptions']);
// }
// }
// onCallbackError(error: any) {
// const errmes = error && error.message ? error.message as string : null;
// let feedbackMessage = this.language.instant('DATASET-EDITOR.ERRORS.ERROR-OCCURED');
// if (errmes) {
// feedbackMessage += errmes;
// }
// this.uiNotificationService.snackBarNotification(feedbackMessage, SnackBarNotificationLevel.Warning);
// this.setErrorModel(error.error);
// this.saving = false;
// }
// public setErrorModel(validationErrorModel: ValidationErrorModel) {
// Object.keys(validationErrorModel).forEach(item => {
// (<any>this.descriptionModel.validationErrorModel)[item] = (<any>validationErrorModel)[item];
// });
// }
// downloadPDF(id: string): void {
// this.descriptionService.downloadPDF(id)
// .pipe(takeUntil(this._destroyed))
// .subscribe(response => {
// const blob = new Blob([response.body], { type: 'application/pdf' });
// const filename = this.fileUtils.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition'));
// FileSaver.saveAs(blob, filename);
// this.matomoService.trackDownload('descriptions', "pdf", id);
// });
// }
// downloadDOCX(id: string): void {
// this.descriptionService.downloadDOCX(id)
// .pipe(takeUntil(this._destroyed))
// .subscribe(response => {
// const blob = new Blob([response.body], { type: 'application/msword' });
// const filename = this.fileUtils.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition'));
// FileSaver.saveAs(blob, filename);
// this.matomoService.trackDownload('descriptions', "docx", id);
// });
// }
// downloadXML(id: string): void {
// this.descriptionService.downloadXML(id)
// .pipe(takeUntil(this._destroyed))
// .subscribe(response => {
// const blob = new Blob([response.body], { type: 'application/xml' });
// const filename = this.fileUtils.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition'));
// FileSaver.saveAs(blob, filename);
// this.matomoService.trackDownload('descriptions', "xml", id);
// });
// }
// // advancedClicked() {
// // const dialogRef = this.dialog.open(ExportMethodDialogComponent, {
// // maxWidth: '500px',
// // data: {
// // message: "Download as:",
// // XMLButton: "XML",
// // documentButton: "Document",
// // pdfButton: "PDF"
// // }
// // });
// // dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
// // if (result == "pdf") {
// // this.downloadPDF();
// // } else if (result == "xml") {
// // this.downloadXML();
// // } else if (result == "doc") {
// // this.downloadDOCX();
// // }
// // });
// // }
// public redirectToGrant() {
// this.router.navigate(['grants/edit/' + this.descriptionModel.dmp.grant.id]);
// }
// public redirectToDmp() {
// this.router.navigate(['plans/edit/' + this.descriptionModel.dmp.id]);
// }
// public enableForm() {
// if (this.formGroup.get('status').value !== DescriptionStatus.Finalized) {
// this.editMode = true;
// this.viewOnly = false;
// this.formGroup.enable();
// } else {
// this.descriptionService.unlock(this.formGroup.get('id').value)
// .pipe(takeUntil(this._destroyed))
// .subscribe(x => {
// this.editMode = true;
// this.viewOnly = false;
// this.descriptionModel.status = DescriptionStatus.Draft;
// this.formGroup.get('status').patchValue(DescriptionStatus.Draft);
// this.formGroup.enable();
// });
// }
// }
// public disableForm() {
// this.editMode = false;
// //this.viewOnly = true;
// this.formGroup.disable();
// }
// openConfirm(dmpLabel, id): 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.descriptionService.delete(id)
// .pipe(takeUntil(this._destroyed))
// .subscribe(
// complete => this.onCallbackSuccess(),
// error => this.onCallbackError(error)
// );
// }
// });
// }
// openDmpSearchDialogue() {
// const formControl = new UntypedFormControl();
// const dialogRef = this.dialog.open(DescriptionCopyDialogueComponent, {
// width: '500px',
// restoreFocus: false,
// data: {
// formControl: formControl,
// descriptionId: this.formGroup.value.id,
// descriptionProfileId: this.formGroup.value.profile,
// descriptionProfileExist: 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.descriptionProfileExist) {
// const newDmpId = result.formControl.value.id
// this.router.navigate(['/descriptions/copy/' + result.descriptionId], { queryParams: { newDmpId: newDmpId } });
// }
// });
// }
// needsUpdate() {
// if (this.descriptionModel.isProfileLatestVersion || (this.descriptionModel.status === DescriptionStatus.Finalized)
// || (this.descriptionModel.isProfileLatestVersion == undefined && this.descriptionModel.status == undefined)) {
// return false;
// } else {
// return true;
// }
// }
// linkToScroll: LinkToScroll;
// onStepFound(linkToScroll: LinkToScroll) {
// this.linkToScroll = linkToScroll;
// }
// private pumpLock() {
// this.lock.touchedAt = new Date();
// this.lockService.createOrUpdate(this.lock).pipe(takeUntil(this._destroyed)).subscribe(async result => {
// if (!isNullOrUndefined(result)) {
// this.lock.id = Guid.parse(result);
// } else {
// this.location.back();
// }
// });
// }
// getEntryVisibleFieldSets(entry: ToCEntry): ToCEntry[] {
// let fieldSets = [];
// if (entry.type === ToCEntryType.FieldSet && !this.table0fContents.internalTable.hiddenEntries.find(hiddenEntry => hiddenEntry === entry.id)) {
// fieldSets.push(entry);
// } else if (entry.type !== ToCEntryType.FieldSet) {
// entry.subEntries.forEach(subEntry => {
// fieldSets = fieldSets.concat(this.getEntryVisibleFieldSets(subEntry));
// });
// }
// return fieldSets;
// }
// get visibleFieldSets(): ToCEntry[] {
// let fieldSets = [];
// let arrays = this.table0fContents ? this.table0fContents.tocentries.
// filter(entry => !this.table0fContents.internalTable.hiddenEntries.find(hiddenEntry => hiddenEntry === entry.id)).map(entry => {
// return this.getEntryVisibleFieldSets(entry);
// })
// : [];
// arrays.forEach(array => {
// fieldSets = fieldSets.concat(array);
// });
// return fieldSets;
// }
// getFirstFieldSet(entry: ToCEntry): ToCEntry {
// if (entry.type === ToCEntryType.FieldSet && !this.table0fContents.internalTable.hiddenEntries.find(hiddenEntry => hiddenEntry === entry.id)) {
// return entry;
// } else {
// let subEntries = entry.subEntries.filter(subEntry => !this.table0fContents.internalTable.hiddenEntries.find(hiddenEntry => hiddenEntry === subEntry.id));
// if (subEntries.length > 0) {
// return this.getFirstFieldSet(subEntries[0]);
// } else {
// return null;
// }
// }
// }
// public changeStep(selected: ToCEntry = null, execute: boolean = true) {
// if (execute) {
// if (selected) {
// let fieldSet = this.getFirstFieldSet(selected);
// let index = this.visibleFieldSets.findIndex(entry => entry.id === fieldSet.id);
// this.step = index + (selected.type === ToCEntryType.FieldSet ? 1 : 0.5);
// } else {
// this.step = 0;
// this.resetScroll();
// }
// }
// }
// get maxStep() {
// return this.visibleFieldSets.length;
// }
// public nextStep() {
// if (this.step < this.maxStep) {//view is changing
// this.step = Math.floor(this.step + 1);
// let entry = this.visibleFieldSets[this.step - 1];
// this.table0fContents.onToCentrySelected(entry, false);
// this.scroll(entry);
// }
// }
// public previousStep() {
// if (this.step > 0) {
// this.step = Math.ceil(this.step - 1);
// if (this.step >= 1) {
// let entry = this.visibleFieldSets[this.step - 1];
// this.table0fContents.onToCentrySelected(entry, false);
// this.scroll(entry);
// } else {
// this.table0fContents.onToCentrySelected(null, false);
// this.resetScroll();
// }
// }
// }
// private resetScroll() {
// document.getElementById('description-editor-form').scrollTop = 0;
// }
// private scroll(entry: ToCEntry) {
// document.getElementById(entry.id).scrollIntoView();
// }
// isDirty() {
// return this.formGroup.dirty && this.hasChanges; // do we need this.formGroup.dirty
// }
// discardChanges() {
// // this.isDiscarded = true;
// // this.hasChanges = false;
// // this.hintErrors = false;
// let messageText = "";
// let confirmButtonText = "";
// let cancelButtonText = "";
// let isDeleteConfirmation = false;
// if (this.isNew && !this.descriptionIsOnceSaved) {
// messageText = this.language.instant('DATASET-EDITOR.ACTIONS.DISCARD.DISCARD-NEW-MESSAGE');
// confirmButtonText = this.language.instant('DATASET-EDITOR.ACTIONS.DISCARD.DISCARD-NEW-CONFIRM');
// cancelButtonText = this.language.instant('DATASET-EDITOR.ACTIONS.DISCARD.DISCARD-NEW-DENY');
// isDeleteConfirmation = true;
// // Object.keys(this.formGroup['controls']).forEach((key: string) => {
// // if (key !== 'dmp' && (key!== 'profile')) {
// // if(key === 'descriptionProfileDefinition'){
// // this.formGroup.get(key).patchValue(this.descriptionProfileDefinitionModel.buildForm().getRawValue);
// // }else{
// // this.formGroup.get(key).reset();
// // }
// // }
// // });
// } else {
// messageText = this.language.instant('DATASET-EDITOR.ACTIONS.DISCARD.DISCARD-EDITED-MESSAGE');
// confirmButtonText = this.language.instant('DATASET-EDITOR.ACTIONS.DISCARD.DISCARD-EDITED-CONFIRM');
// cancelButtonText = this.language.instant('DATASET-EDITOR.ACTIONS.DISCARD.DISCARD-EDITED-DENY');
// isDeleteConfirmation = false;
// // this.isDiscarded = true;
// // this.hasChanges = false;
// // this.hintErrors = false;
// // // this._unregisterFormListeners();
// // this.formGroup.patchValue(JSON.parse(JSON.stringify(this.formGroupRawValue)));
// // // this.registerFormListeners();
// // this.isDiscarded = false;
// }
// const dialogRef = this.dialog.open(ConfirmationDialogComponent, {
// restoreFocus: false,
// data: {
// message: messageText,
// confirmButton: confirmButtonText,
// cancelButton: cancelButtonText,
// isDeleteConfirmation: true
// },
// maxWidth: '40em'
// });
// dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => {
// if (result) {
// // this.backToDmp(this.formGroup.get('dmp').value.id)
// setTimeout(x => {
// this.init();
// });
// }
// });
// // this.isDiscarded = false;
// }
// addDescription(dmpId: string) {
// this.router.navigate(['/descriptions', 'new', dmpId]);
// }
// reloadDateset(descriptionId: string) {
// let url = this.router.createUrlTree(['/descriptions', 'edit', descriptionId]).toString();
// this.location.go(url);
// }
// backToDmp(id: string) {
// this.router.navigate(['/plans', 'edit', id]);
// }
// getLinks(currentLinks: Link[]) {
// this.links = currentLinks;
// }
// printForm() {
// console.log(this.formGroup);
// }
// printFormValue() {
// console.log(this.formGroup.value);
// }
// touchForm() {
// this.formGroup.markAllAsTouched();
// this.showtocentriesErrors = true;
// }
// }