import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop'; import { DatePipe } from '@angular/common'; import { Component, OnInit } from '@angular/core'; import { FormArray, UntypedFormArray, UntypedFormGroup } from '@angular/forms'; import { MatDialog } from '@angular/material/dialog'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { DescriptionStatus } from '@app/core/common/enum/description-status'; import { DmpAccessType } from '@app/core/common/enum/dmp-access-type'; import { DmpBlueprintFieldCategory } from '@app/core/common/enum/dmp-blueprint-field-category'; import { DmpBlueprintExtraFieldDataType } from '@app/core/common/enum/dmp-blueprint-field-type'; import { DmpBlueprintStatus } from '@app/core/common/enum/dmp-blueprint-status'; import { DmpBlueprintSystemFieldType } from '@app/core/common/enum/dmp-blueprint-system-field-type'; import { DmpContactType } from '@app/core/common/enum/dmp-contact-type'; 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 { DmpBlueprint } from '@app/core/model/dmp-blueprint/dmp-blueprint'; import { Dmp, DmpPersist } from '@app/core/model/dmp/dmp'; import { LanguageInfo } from '@app/core/model/language-info'; import { AuthService } from '@app/core/services/auth/auth.service'; import { ConfigurationService } from '@app/core/services/configuration/configuration.service'; import { LanguageInfoService } from '@app/core/services/culture/language-info-service'; import { DescriptionTemplateService } from '@app/core/services/description-template/description-template.service'; import { DmpBlueprintService } from '@app/core/services/dmp/dmp-blueprint.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 { UserService } from '@app/core/services/user/user.service'; import { EnumUtils } from '@app/core/services/utilities/enum-utils.service'; import { QueryParamsService } from '@app/core/services/utilities/query-params.service'; import { SingleAutoCompleteConfiguration } from '@app/library/auto-complete/single/single-auto-complete-configuration'; import { PopupNotificationDialogComponent } from '@app/library/notification/popup/popup-notification.component'; 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 { DmpEditorModel } from './dmp-editor.model'; import { DmpEditorResolver } from './dmp-editor.resolver'; import { DmpEditorService } from './dmp-editor.service'; import { DmpUserRole } from '@app/core/common/enum/dmp-user-role'; import { DmpUserType } from '@app/core/common/enum/dmp-user-type'; @Component({ selector: 'app-dmp-editor', templateUrl: './dmp-editor.component.html', styleUrls: ['./dmp-editor.component.scss'], providers: [DmpEditorService] }) export class DmpEditorComponent extends BaseEditor implements OnInit { isNew = true; isDeleted = false; item: Dmp; selectedBlueprint: DmpBlueprint; lockStatus: Boolean = false; step: number = 0; descriptionStatusEnum = DescriptionStatus; dmpBlueprintSectionFieldCategoryEnum = DmpBlueprintFieldCategory; dmpBlueprintSystemFieldTypeEnum = DmpBlueprintSystemFieldType; dmpBlueprintExtraFieldDataTypeEnum = DmpBlueprintExtraFieldDataType; dmpAccessTypeEnum = DmpAccessType; dmpAccessTypeEnumValues = this.enumUtils.getEnumValues(DmpAccessType); dmpContactTypeEnum = DmpContactType; dmpContactTypeEnumValues = this.enumUtils.getEnumValues(DmpContactType); dmpUserTypeEnum = DmpUserType; dmpUserTypeEnumValues = this.enumUtils.getEnumValues(DmpUserType); dmpUserRoleEnumValues = this.enumUtils.getEnumValues(DmpUserRole); singleAutocompleteBlueprintConfiguration: SingleAutoCompleteConfiguration = { initialItems: (data?: any) => this.dmpBlueprintService.query(this.dmpBlueprintService.buildAutocompleteLookup(null, null, null, [DmpBlueprintStatus.Finalized])).pipe(map(x => x.items)), filterFn: (searchQuery: string, data?: any) => this.dmpBlueprintService.query(this.dmpBlueprintService.buildAutocompleteLookup(searchQuery, null, null, [DmpBlueprintStatus.Finalized])).pipe(map(x => x.items)), getSelectedItem: (selectedItem: any) => this.dmpBlueprintService.query(this.dmpBlueprintService.buildAutocompleteLookup(null, null, [selectedItem])).pipe(map(x => x.items[0])), displayFn: (item: DmpBlueprint) => item.label, titleFn: (item: DmpBlueprint) => item.label, valueAssign: (item: DmpBlueprint) => item.id, }; protected get canDelete(): boolean { return !this.isDeleted && !this.isNew && this.hasPermission(this.authService.permissionEnum.DeleteDmp); } protected get canSave(): boolean { return !this.isDeleted && this.hasPermission(this.authService.permissionEnum.EditDmp); } protected get canFinalize(): boolean { return !this.isDeleted && this.hasPermission(this.authService.permissionEnum.EditDmp); } private hasPermission(permission: AppPermission): boolean { return this.authService.hasPermission(permission) || this.editorModel?.permissions?.includes(permission); } 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, // Rest dependencies. Inject any other needed deps here: public authService: AuthService, private dmpService: DmpService, private logger: LoggingService, // private descriptionEditorService: DescriptionEditorService, public dmpBlueprintService: DmpBlueprintService, private matomoService: MatomoService, private lockService: LockService, private configurationService: ConfigurationService, // public visibilityRulesService: VisibilityRulesService, private languageInfoService: LanguageInfoService, public enumUtils: EnumUtils, public descriptionTemplateService: DescriptionTemplateService, public userService: UserService ) { super(dialog, language, formService, router, uiNotificationService, httpErrorHandlingService, filterService, datePipe, route, queryParamsService); } ngOnInit(): void { this.matomoService.trackPageView('DMP Editor'); super.ngOnInit(); this.route.params .pipe(takeUntil(this._destroyed)) .subscribe((params: Params) => { const itemId = params['itemId']; if (itemId != null) { this.isNew = false; this.lockService.checkLockStatus(itemId).pipe(takeUntil(this._destroyed)).subscribe(lockStatus => { this.lockStatus = lockStatus; if (this.item.status === DmpStatus.Finalized || lockStatus) { this.formGroup.disable(); } 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 (!lockStatus && !isNullOrUndefined(this.authService.currentAccountIsAuthenticated())) { // TODO: lock it. // const lockPersist: LockPersist = { // target: itemId, // targetType: LockTargetType.Dmp, // lockedBy: this.authService.userId() // } // this.lockService.persist(lockPersist).pipe(takeUntil(this._destroyed)).subscribe(async result => { // this.lock.id = Guid.parse(result); // interval(this.configurationService.lockInterval).pipe(takeUntil(this._destroyed)).subscribe(() => this.pumpLock()); // }); } }); } }); } getItem(itemId: Guid, successFunction: (item: Dmp) => void) { this.dmpService.getSingle(itemId, DmpEditorResolver.lookupFields()) .pipe(map(data => data as Dmp), takeUntil(this._destroyed)) .subscribe( data => successFunction(data), error => this.onCallbackError(error) ); } prepareForm(data: Dmp) { try { this.editorModel = data ? new DmpEditorModel().fromModel(data) : new DmpEditorModel(); this.item = data; this.selectedBlueprint = data?.blueprint; this.isDeleted = data ? data.isActive === IsActive.Inactive : false; this.buildForm(); } catch (error) { this.logger.error('Could not parse Dmp item: ' + data + error); this.uiNotificationService.snackBarNotification(this.language.instant('COMMONS.ERRORS.DEFAULT'), SnackBarNotificationLevel.Error); } } buildForm() { this.formGroup = this.editorModel.buildForm(null, this.isDeleted || !this.authService.hasPermission(AppPermission.EditDmp)); if (this.editorModel.status == DmpStatus.Finalized || this.isDeleted) { this.formGroup.disable(); } if (this.item != null) { this.nextStep(); } } refreshData(): void { this.getItem(this.editorModel.id, (data: Dmp) => this.prepareForm(data)); } refreshOnNavigateToData(id?: Guid): void { this.formGroup.markAsPristine(); if (this.isNew) { let route = []; route.push('/plans/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 DmpPersist; //Transform to persist //Transform descriptionTemplates formData.descriptionTemplates = []; for (const sectionId in (this.formGroup.get('descriptionTemplates') as UntypedFormGroup).controls) { formData.descriptionTemplates.push( ...(this.formGroup.get('descriptionTemplates').get(sectionId).value as Guid[]).map(x => { return { sectionId: Guid.parse(sectionId), descriptionTemplateGroupId: x } }) ); } this.dmpService.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.dmpService.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); } // // // Steps // // changeStep(index: number) { this.step = index; this.resetScroll(); } nextStep() { this.step = this.step < this.selectedBlueprint.definition.sections.length ? this.step + 1 : this.step; this.resetScroll(); } previousStep() { this.step = this.step !== 1 ? this.step - 1 : this.step; this.resetScroll(); } private resetScroll() { // document.getElementById('editor-form').scrollTop = 0; } // // // Blueprint // // selectBlueprint() { this.dmpBlueprintService.getSingle(this.formGroup.get('blueprint').value, DmpEditorResolver.blueprintLookupFields()).pipe(takeUntil(this._destroyed)).subscribe(data => { this.selectedBlueprint = data; this.buildFormAfterBlueprintSelection(); this.nextStep(); }); } selectDefaultBlueprint() { this.dmpBlueprintService.getSingle(this.configurationService.defaultBlueprintId, DmpEditorResolver.blueprintLookupFields()).pipe(takeUntil(this._destroyed)).subscribe(data => { this.selectedBlueprint = data; this.formGroup.get('blueprint').setValue(this.selectedBlueprint.id); this.buildFormAfterBlueprintSelection(); this.nextStep(); }); } private buildFormAfterBlueprintSelection() { const dmp: Dmp = { label: this.formGroup.get('label').value, description: this.formGroup.get('description').value, blueprint: this.selectedBlueprint, status: DmpStatus.Draft } this.prepareForm(dmp); } // // // Contacts // // addContact(): void { const contactArray = this.formGroup.get('properties').get('contacts') as FormArray; (this.formGroup.get('properties').get('contacts') as FormArray).push(this.editorModel.createChildContact(contactArray.length)); } removeContact(contactIndex: number): void { (this.formGroup.get('properties').get('contacts') as FormArray).removeAt(contactIndex); DmpEditorModel.reApplyPropertiesValidators( { formGroup: this.formGroup, validationErrorModel: this.editorModel.validationErrorModel } ); this.formGroup.get('properties').get('contacts').markAsDirty(); } dropContacts(event: CdkDragDrop) { const contactsFormArray = (this.formGroup.get('properties').get('contacts') as FormArray); moveItemInArray(contactsFormArray.controls, event.previousIndex, event.currentIndex); contactsFormArray.updateValueAndValidity(); DmpEditorModel.reApplyPropertiesValidators( { formGroup: this.formGroup, validationErrorModel: this.editorModel.validationErrorModel } ); this.formGroup.get('properties').get('contacts').markAsDirty(); } // // // Descriptions // // public descriptionsInSection(sectionId: Guid) { this.item?.descriptions?.filter(x => x?.dmpDescriptionTemplate?.sectionId === sectionId) || []; } editDescription(id: string, isNew: boolean, showModal: boolean = false) { if (showModal) { // const dialogRef = this.dialog.open(DmpToDatasetDialogComponent, { // width: '500px', // autoFocus: false, // restoreFocus: false, // }); // dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => { // if (result) { // if (isNew) { // this.router.navigate(['/datasets', 'new', id, this.dmpSectionIndex]); // } else { // this.router.navigate(['/datasets', 'edit', id]); // } // } // }); } else { if (isNew) { // this.router.navigate(['/descriptions', 'new', id, this.dmpSectionIndex]); } else { this.router.navigate(['/descriptions', 'edit', id]); } } } addDescription(sectionId: Guid) { // this.saving = true; // if (!this._isDMPDescriptionValid()) { // const errmess = this._buildDMPDescriptionErrorMessages(); // this.showValidationErrorsDialog(undefined, errmess); // this.hintErrors = true; // this.saving = false; // return; // } // this.dmpSectionIndex = dmpSectionIndex; // this.onSubmit(true, false); } // // // Description Template // // onRemoveDescriptionTemplate(event, sectionIndex: number) { let found = false; const section = this.selectedBlueprint.definition.sections[sectionIndex]; let sectionDescriptionTemplates = (this.formGroup.get('descriptionTemplates') as UntypedFormArray).controls.find(x => x.get('sectionId').value === event.id); } onPreviewDescriptionTemplate(event, sectionIndex: number) { // const dialogRef = this.dialog.open(DatasetPreviewDialogComponent, { // width: '590px', // minHeight: '200px', // restoreFocus: false, // data: { // template: event // }, // panelClass: 'custom-modalbox' // }); // dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => { // if (result) { // this.addProfile(event, sectionIndex); // this.profilesAutoCompleteConfiguration = { // filterFn: this.filterProfiles.bind(this), // initialItems: (excludedItems: any[]) => this.filterProfiles('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))), // displayFn: (item) => item['label'], // titleFn: (item) => item['label'], // subtitleFn: (item) => item['description'], // popupItemActionIcon: 'visibility' // }; // } // }); } onDescriptionTemplateSelected(event, sectionIndex: number) { try { this.addProfile(event, sectionIndex); // const profileCounts: Map = new Map(); // profiles.forEach((value) => profileCounts.set(value.id, (profileCounts.get(value.id) !== undefined ? profileCounts.get(value.id): 0 ) + 1)); // const duplicateProfiles = profiles.filter((value) => { // let isOk = profileCounts.get(value.id) > 1; // if (isOk) { // profileCounts.set(value.id, 0); // } // return isOk; // }); // duplicateProfiles.forEach((value) => profiles.splice(profiles.lastIndexOf(value), 1)); // profiles.sort((a,b)=> a.label.localeCompare(b.label)); } catch { console.info('Could not sort Dataset Templates') } } addProfile(event, sectionIndex: number) { // const profiles = this.formGroup.get('profiles').value as DmpDatasetProfile[]; // let found = profiles.find((value) => value.id === event.id); // if (found !== undefined) { // if (found.data.dmpSectionIndex.indexOf(sectionIndex) === -1) { // found.data.dmpSectionIndex.push(sectionIndex); // } // else { // this.sectionTemplates[sectionIndex].pop(); // } // } // else { // let dmpDatasetProfileSection: DmpDatasetProfileSectionsFormModel = new DmpDatasetProfileSectionsFormModel(); // dmpDatasetProfileSection.dmpSectionIndex = [sectionIndex]; // profiles.push({ id: null, descriptionTemplateId: event.id, label: event.label, data: dmpDatasetProfileSection }); // } // this.formGroup.get('profiles').setValue(profiles); } // // // Misc // // public isDirty(): boolean { return this.formGroup && this.formGroup.dirty; //&& this.hasChanges; } getLanguageInfos(): LanguageInfo[] { return this.languageInfoService.getLanguageInfoValues(); } // canDeactivate(): boolean { // return !this.isDirty(); // } // saving = false; // isNew = true; // isUserOwner: boolean = true; // isNewVersion = false; // isFinalized = false; // isClone = false; // hasChanges = false; // isDiscarded = false; // isCreateNew = false; // isCreateNewProject = false; // isCreateNewFunder = false; // dmp: DmpEditorModel; // dmpSectionIndex: number = 0; // formGroup: UntypedFormGroup = null; // formGroupRawValue: any; // datasets = new UntypedFormArray([]); // associatedUsers: Array; // people: Array; // lock: Lock; // lockPersist: LockPersist; // lockStatus: Boolean = false; // step: number = 0; // stepsBeforeDatasets: number = 4; // maxStep: number = 4; // scrollTop: number; // hintErrors: boolean = false; // selectedDmpBlueprintDefinition: DmpBlueprintDefinition = null; // sectionTemplates: Array> = new Array>(); // private associates: UserModel[] = []; // visibles: Visible[] = [ // { value: true, name: 'DMP-EDITOR.VISIBILITY.PUBLIC' }, // { value: false, name: 'DMP-EDITOR.VISIBILITY.RESTRICTED' } // ] // licenseAutoCompleteConfiguration = this.referenceService.getSingleAutocompleteConfiguration([ReferenceType.Licenses]); // organisationsAutoCompleteConfiguration: MultipleAutoCompleteConfiguration = { // filterFn: this.filterOrganisations.bind(this), // initialItems: (excludedItems: any[]) => this.filterOrganisations('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))), // displayFn: (item) => item['name'], // titleFn: (item) => item['name'], // subtitleFn: (item) => item['tag'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['tag'] : (item['key'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['key'] : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE')) // }; // researchersAutoCompleteConfiguration: MultipleAutoCompleteConfiguration = { // filterFn: this.filterResearchers.bind(this), // initialItems: (excludedItems: any[]) => this.filterResearchers('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))), // displayFn: (item) => item['name'], // titleFn: (item) => item['name'], // subtitleFn: (item) => item['tag'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['tag'] : (item['key'] ? this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.SOURCE:') + item['key'] : this.language.instant('TYPES.EXTERNAL-DATASET-TYPE.NO-SOURCE')) // }; // profilesAutoCompleteConfiguration: MultipleAutoCompleteConfiguration; // dmpBlueprintSectionFieldCategory = DmpBlueprintFieldCategory; // dmpBlueprintSystemFieldType = DmpBlueprintSystemFieldType; // //public dmpBlueprintSystemFieldTypeEnum = this.enumUtils.getEnumValues(DmpBlueprintSystemFieldType); // dmpBlueprintExtraFieldDataType = DmpBlueprintExtraFieldDataType; // //public dmpBlueprintExtraFieldDataTypeEnum = this.enumUtils.getEnumValues(DmpBlueprintExtraFieldDataType); // constructor( // private dmpBlueprintService: DmpBlueprintService, // private datasetService: DatasetService, // private authService: AuthService, // private route: ActivatedRoute, // private router: Router, // private configurationService: ConfigurationService, // private languageInfoService: LanguageInfoService, // private language: TranslateService, // private externalSourcesService: ExternalSourcesService, // private organizationService: OrganisationService, // private uiNotificationService: UiNotificationService, // private formService: FormService, // private dialog: MatDialog, // private lockService: LockService, // private matomoService: MatomoService, // private referenceService: ReferenceService // ) { // super(); // } // ngOnInit(): void { // this.matomoService.trackPageView('DMP Editor'); // this.route.params // .pipe(takeUntil(this._destroyed)) // .subscribe((params: Params) => { // const itemId = params['id']; // if (itemId != null) { // this.isNew = false; // this.dmpService.getSingle(itemId).pipe(map(data => data as DmpModel)) // .pipe(takeUntil(this._destroyed)) // .subscribe(async data => { // this.lockService.checkLockStatus(Guid.parse(data.id)).pipe(takeUntil(this._destroyed)).subscribe(lockStatus => { // this.lockStatus = lockStatus; // this.dmp = new DmpEditorModel(); // this.dmp.grant = new GrantTabModel(); // this.dmp.project = new ProjectFormModel(); // this.dmp.funder = new FunderFormModel(); // this.dmp.extraProperties = new ExtraPropertiesFormModel(); // this.dmp.fromModel(data); // this.formGroup = this.dmp.buildForm(); // this.datasets = this.formGroup.get('datasets') as UntypedFormArray; // this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue())); // if (!isNullOrUndefined(this.formGroup.get('profile').value)) { // this.getSingle(Guid.parse(this.formGroup.get('profile').value), data => { // this.selectedDmpBlueprintDefinition = data.definition; // this.checkForGrant(); // this.checkForFunder(); // this.checkForProject(); // this.buildExtraFields(); // this.formGroup.get('profile').setValue(data); // this.maxStep = this.selectedDmpBlueprintDefinition.sections.length; // this.step = 1; // this.addProfiles(this.dmp.profiles); // }); // } // this.maxStep = this.formGroup.get('datasets') ? this.maxStep + this.formGroup.get('datasets').value.length - 1 : this.maxStep; // this.setIsUserOwner(); // if (!this.isUserOwner) { // if (this.isUserMember()) { // this.router.navigate(['plans', 'overview', itemId]); // return; // } // this.isFinalized = true; // this.formGroup.disable(); // } // if (this.dmp.status === DmpStatus.Finalized || lockStatus) { // this.isFinalized = true; // this.formGroup.disable(); // } // if (this.authService.currentAccountIsAuthenticated()) { // if (!lockStatus) { // const persist : LockPersist = null; // persist.target = Guid.parse(data.id); // persist.targetType = LockTargetType.Dmp; // persist.lockedBy = this.getUserFromDMP(); // // this.lock = new LockModel(data.id, this.getUserFromDMP()); // this.lockService.persist(persist).pipe(takeUntil(this._destroyed)).subscribe(async result => { // this.lock = result; // interval(this.configurationService.lockInterval).pipe(takeUntil(this._destroyed)).subscribe(() => this.pumpLock()); // }); // } // } // this.associatedUsers = data.associatedUsers; // this.people = data.users; // this.formGroup.valueChanges.pipe(takeUntil(this._destroyed)) // .subscribe(x => { // this.formChanged(); // }); // if (this.lockStatus) { // this.dialog.open(PopupNotificationDialogComponent, { // data: { // title: this.language.instant('DMP-EDITOR.LOCKED.TITLE'), // message: this.language.instant('DMP-EDITOR.LOCKED.MESSAGE') // }, maxWidth: '30em' // }); // } // }); // }); // } // else { // this.dmp = new DmpEditorModel(); // this.dmp.grant = new GrantTabModel(); // this.dmp.project = new ProjectFormModel(); // this.dmp.funder = new FunderFormModel(); // this.dmp.extraProperties = new ExtraPropertiesFormModel(); // this.dmp.extraProperties.visible = false; // this.dmp.extraProperties.contact = this.authService.userId()?.toString(); // this.formGroup = this.dmp.buildForm(); // this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue())); // if (!isNullOrUndefined(this.formGroup.get('profile').value)) { // this.getSingle(Guid.parse(this.formGroup.get('profile').value), data => { // this.selectedDmpBlueprintDefinition = data.definition; // this.checkForGrant(); // this.checkForFunder(); // this.checkForProject(); // this.buildExtraFields(); // this.formGroup.get('profile').setValue(data); // this.maxStep = this.selectedDmpBlueprintDefinition.sections.length; // this.step = 1; // this.addProfiles(); // }); // } // this.registerFormEventsForDmpBlueprint(); // if (!this.isUserOwner) { // this.formGroup.disable(); // } // if (isNullOrUndefined(this.formGroup.get('extraProperties').get('publicDate').value)) { // this.formGroup.get('extraProperties').get('publicDate').patchValue(new Date()); // } // let associate: UserModel = { // id: this.authService.userId()?.toString(), // name: this.authService.getPrincipalName(), // appRoles: this.authService.getRoles(), // email: this.authService.getUserProfileEmail() // }; // this.associates.push(associate); // if (isNullOrUndefined(this.formGroup.get('extraProperties').get('contact').value)) { // this.formGroup.get('extraProperties').get('contact').patchValue(associate.id); // } // if (isNullOrUndefined(this.formGroup.get('extraProperties').get('language').value)) { // this.formGroup.get('extraProperties').get('language').patchValue('en'); // } // try { // const profiles = this.formGroup.get('profiles').value as DmpDatasetProfile[]; // profiles.sort((a, b) => a.label.localeCompare(b.label)); // } catch { // console.info('Could not sort profiles'); // } // } // }); // this.profilesAutoCompleteConfiguration = { // filterFn: this.filterProfiles.bind(this), // initialItems: (excludedItems: any[]) => this.filterProfiles('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))), // displayFn: (item) => item['label'], // titleFn: (item) => item['label'], // subtitleFn: (item) => item['description'], // popupItemActionIcon: 'visibility' // }; // } // extraFieldsArray(): UntypedFormArray { // return this.formGroup.get('extraFields') as UntypedFormArray; // } // setIsUserOwner() { // if (this.dmp) { // const principalId: string = this.authService.userId()?.toString(); // this.isUserOwner = !!this.dmp.users.find(x => (x.role === Role.Owner) && (x.id === principalId)); // } // } // isUserMember(): boolean { // try { // const principalId: string = this.authService.userId()?.toString(); // return !!this.dmp.users.find(x => (x.role === Role.Member) && (x.id === principalId)); // } catch { // return false; // } // } // getUserFromDMP(): any { // if (this.dmp) { // const principalId: string = this.authService.userId()?.toString(); // return this.dmp.users.find(x => x.id === principalId); // } // } // private pumpLock() { // this.lock.touchedAt = new Date(); // //his.lockService.createOrUpdate(this.lock).pipe(takeUntil(this._destroyed)).subscribe(async result => this.lock.id = Guid.parse(result)); // } // public isDirty(): boolean { // return this.formGroup && this.formGroup.dirty && this.hasChanges; // } // public discard() { // let messageText = ""; // let confirmButtonText = ""; // let cancelButtonText = ""; // if (this.isNew) { // 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'); // } 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'); // } // 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.discardChanges(); // }); // } // }); // } // public discardChanges() { // this.isDiscarded = true; // this.hasChanges = false; // if (!this.isNew) { // let grantControl; // if (this.formGroup.get('grant').get('existGrant')) { // grantControl = new GrantTabModel(); // grantControl.fromModel(this.formGroup.get('grant').get('existGrant').value); // } else { // // TODO: Commented in refactor // //grantControl = new GrantEditorModel(); // //grantControl.fromModel(this.formGroup.get('grant').value); // } // grantControl.buildForm() // this.formGroup.patchValue(JSON.parse(JSON.stringify(this.formGroupRawValue))); // if (this.formGroup.get('grant').get('existGrant')) { // this.formGroup.get('grant').get('existGrant').setValue(grantControl.existGrant); // } else { // this.formGroup.get('grant').setValue(grantControl); // } // } else { // this.formGroup.reset(); // this.formGroup.get("status").setValue(DmpStatus.Draft); // this.formGroup.get('extraProperties').get('visible').setValue(false); // this.formGroup.get('extraProperties').get('contact').setValue(this.authService.userId()?.toJSON()); // this.formGroup.get('associatedUsers').setValue([]); // } // this.isDiscarded = false; // } // save() { // this.formSubmit(false); // } // formSubmit(addNew?: boolean, showAddDatasetDialog?: boolean): void { // this.saving = true; // this.formService.touchAllFormFields(this.formGroup); // if (!this._isDMPDescriptionValid()) { // const errmess = this._buildDMPDescriptionErrorMessages(); // this.showValidationErrorsDialog(undefined, errmess); // this.hintErrors = true; // this.saving = false; // return; // } // this.onSubmit(addNew, showAddDatasetDialog); // } // public formChanged() { // if (!this.isDiscarded) { // this.hasChanges = true; // } // } // selectDefaultBlueprint() { // this.getSingle(this.configurationService.defaultBlueprintId, data => { // this.selectedDmpBlueprintDefinition = data.definition; // this.formGroup.get('profile').setValue(data.id); // this.maxStep = this.selectedDmpBlueprintDefinition.sections.length; // this.nextStep(); // }); // } // selectBlueprint() { // this.maxStep = this.selectedDmpBlueprintDefinition.sections.length; // this.nextStep(); // } // nextStep() { // this.step = this.step < this.maxStep ? this.step + 1 : this.step; // this.resetScroll(); // // if (this.step >= this.stepsBeforeDatasets) { // // this.datasetId = this.datasets.at(this.step - this.stepsBeforeDatasets).get('id').value; // // } // } // previousStep() { // this.step = this.step !== 1 ? this.step - 1 : this.step; // this.resetScroll(); // // if (this.step >= this.stepsBeforeDatasets) { // // this.datasetId = this.datasets.at(this.step - this.stepsBeforeDatasets).get('id').value; // // } // } // changeStep(index: number, dataset?: UntypedFormControl) { // this.step = index; // this.resetScroll(); // // if (dataset) { this.datasetId = dataset.get('id').value }; // } // private resetScroll() { // document.getElementById('editor-form').scrollTop = 0; // } // hasProfile(sectionIndex: number): boolean { // return this.formGroup.get('profiles') && this.formGroup.get('profiles').value && this.formGroup.get('profiles').value.some(x => x.data.dmpSectionIndex.includes(sectionIndex)); // } // addDataset(dmpSectionIndex: number) { // this.saving = true; // if (!this._isDMPDescriptionValid()) { // const errmess = this._buildDMPDescriptionErrorMessages(); // this.showValidationErrorsDialog(undefined, errmess); // this.hintErrors = true; // this.saving = false; // return; // } // // const showDialog = this.hasProfile() && this.isNew; // this.dmpSectionIndex = dmpSectionIndex; // this.onSubmit(true, false); // // this.formSubmit(true, false); // // Add dataset to list // // if (!this.formGroup.get('datasets')) { // // this.formGroup.addControl('datasets', new FormBuilder().array(new Array())); // // } // // this.formGroup.get('datasets')['controls'].push(new DatasetWizardEditorModel().buildForm()); // // this.datasets = this.formGroup.get('datasets') as FormArray; // // this.step = this.stepsBeforeDatasets + this.formGroup.get('datasets')['controls'].length - 1; // // this.maxStep = this.maxStep + this.formGroup.get('datasets')['controls'].length - 1; // } // onSubmit(addNew?: boolean, showAddDatasetDialog?: boolean): void { // this.scrollTop = document.getElementById('editor-form').scrollTop; // // return; // this.dmpService.createDmp(this.formGroup.getRawValue()) // .pipe(takeUntil(this._destroyed)) // .subscribe( // complete => { // this.formGroup.get('id').setValue(complete.id); // this.formGroup.get('modified').setValue(complete.modified); // this.hasChanges = false; // if (showAddDatasetDialog) { // this.addDatasetOpenDialog(complete); // } // if (addNew) { // this.onCallbackSuccessAddNew(complete); // } // else { this.onCallbackSuccess(complete) } // }, // error => { // this.formGroup.get('status').setValue(DmpStatus.Draft); // this.onCallbackError(error); // } // ); // // this.dmpService.createDmpWithDatasets(this.formGroup.getRawValue()) // // .pipe(takeUntil(this._destroyed)) // // .subscribe( // // complete => { // // if (showAddDatasetDialog) { // // this.addDatasetOpenDialog(complete); // // } // // else if (this.step < this.stepsBeforeDatasets) { this.onCallbackSuccess(complete) } // // else { this.onCallbackSuccess(complete, this.datasetId) } // // }, // // error => { // // this.formGroup.get('status').setValue(DmpStatus.Draft); // // this.onCallbackError(error); // // } // // ) // } // addDatasetOpenDialog(dmp: DmpModel) { // const dialogRef = this.dialog.open(ConfirmationDialogComponent, { // maxWidth: '500px', // restoreFocus: false, // data: { // message: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ADD-DATASET'), // confirmButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CONFIRM'), // cancelButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.NO'), // isDeleteConfirmation: false // } // }); // dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => { // if (result) { // // this.router.navigate(['datasets/new/' + id]); // this.addDataset(this.dmpSectionIndex); // } else { // dmp.id != null ? this.router.navigate(['/plans', 'edit', dmp.id]) : this.router.navigate(['/plans']); // } // }); // } // onCallbackSuccess(dmp?: DmpModel, datasetId?: string): void { // // On save keep editor position // this.uiNotificationService.snackBarNotification(this.isNew ? this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-CREATION') : this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success); // if (dmp) { // if (this.isNew) { // this.router.navigate(['/plans', 'edit', dmp.id]); // } // let dmpEditorModel: DmpEditorModel; // dmpEditorModel = new DmpEditorModel(); // dmpEditorModel.grant = new GrantTabModel(); // dmpEditorModel.project = new ProjectFormModel(); // dmpEditorModel.funder = new FunderFormModel(); // dmpEditorModel.extraProperties = new ExtraPropertiesFormModel(); // dmpEditorModel.fromModel(dmp); // this.formGroupRawValue = JSON.parse(JSON.stringify(this.formGroup.getRawValue())); // this.associatedUsers = dmp.associatedUsers; // this.people = dmp.users; // setTimeout(() => { this.formGroup = null; }); // setTimeout(() => { // this.formGroup = dmpEditorModel.buildForm(); // this.formGroup.valueChanges.pipe(takeUntil(this._destroyed)) // .subscribe(x => { // this.formChanged(); // }); // }); // setTimeout(() => { document.getElementById('editor-form').scrollTop = this.scrollTop; }); // this.saving = false; // this.isNew = false; // } else { // this.router.navigate(['/reload']).then(() => { this.router.navigate(['/plans']); }); // } // // Uncomment to not keep editor position on save // // if (dmp.id != null) { // // datasetId ? this.router.navigate(['/reload']).then(() => { this.router.navigate(['/plans', 'edit', dmp.id], { queryParams: { dataset: datasetId } }); }) : this.router.navigate(['/reload']).then(() => { this.router.navigate(['/plans', 'edit', dmp.id]); }) // // } else { // // this.router.navigate(['/reload']).then(() => { this.router.navigate(['/plans']); }); // // } // } // onCallbackError(error: any) { // this.uiNotificationService.snackBarNotification(error.error.message, SnackBarNotificationLevel.Error); // this.setErrorModel(error.error); // this.saving = false; // //this.validateAllFormFields(this.formGroup); // } // public setErrorModel(validationErrorModel: ValidationErrorModel) { // Object.keys(validationErrorModel).forEach(item => { // (this.dmp.validationErrorModel)[item] = (validationErrorModel)[item]; // }); // } // onCallbackSuccessAddNew(dmp?: DmpModel) { // // this.editDataset(dmp.id, true, this.isNew && !this.formGroup.get('datasets').value.length); // this.editDataset(dmp.id, true, false); // this.saving = false; // } // editDataset(id: string, isNew: boolean, showModal: boolean = false) { // if (showModal) { // const dialogRef = this.dialog.open(DmpToDatasetDialogComponent, { // width: '500px', // autoFocus: false, // restoreFocus: false, // }); // dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => { // if (result) { // if (isNew) { // this.router.navigate(['/datasets', 'new', id, this.dmpSectionIndex]); // } else { // this.router.navigate(['/datasets', 'edit', id]); // } // } // }); // } else { // if (isNew) { // this.router.navigate(['/datasets', 'new', id, this.dmpSectionIndex]); // } else { // this.router.navigate(['/datasets', 'edit', id]); // } // } // } // public removeDataset(datasetId: string, index: number) { // 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) { // if (datasetId) { // this.datasetService.delete(datasetId) // .pipe(takeUntil(this._destroyed)) // .subscribe( // complete => { // this.onDeleteCallbackSuccess(); // }, // error => this.onDeleteCallbackError(error) // ); // } // this.formGroup.get('datasets')['controls'].splice(index, 1); // this.step = 0; // } // }); // } // onDeleteCallbackSuccess(): void { // this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-DELETE'), SnackBarNotificationLevel.Success); // this.dmp.id != null ? this.router.navigate(['/reload']).then(() => this.router.navigate(['/plans', 'edit', this.dmp.id])) : this.router.navigate(['/plans']); // } // onDeleteCallbackError(error) { // this.uiNotificationService.snackBarNotification(error.error.message ? error.error.message : this.language.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-DELETE'), SnackBarNotificationLevel.Error); // } // //checks if the dpm is valid not taking into account the datasets validity // private _isDMPDescriptionValid(): boolean { // const form: UntypedFormGroup = this.formGroup; // if (form.controls) { // return Object.keys(form.controls) // .map(controlName => {//get validity of each control // if (controlName === 'datasets') {//we dont care if datasets are valid // return true; // } // return !form.get(controlName).invalid;//!! in case the control is disabled, we consider it valid // }) // .reduce((isFormValid, isControlValid) => {//aggregate validities // return isControlValid && isFormValid; // }, true); // } // return true; // } // 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 // }, // }); // } // } // private _buildDMPDescriptionErrorMessages(): string[] {//not including datasets // const errmess: string[] = []; // Object.keys(this.formGroup.controls).forEach(controlName => { // if (controlName != 'datasets' && 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 ((aControl).nativeElement !== undefined && (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; // } // 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'); // } // } // filterProfiles(value: string): Observable { // const request = new DataTableRequest(null, null, { fields: ['+label'] }); // const criteria = new DatasetProfileCriteria(); // criteria.like = value; // request.criteria = criteria; // return this.dmpService.searchDmpBlueprints(request); // } // private getSingle(blueprintId: Guid, successFunction) { // this.dmpBlueprintService.getSingle(blueprintId, [ // nameof(x => x.id), // nameof(x => x.label), // nameof(x => x.status), // nameof(x => x.description), // nameof(x => x.status), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.id)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.label)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.description)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.ordinal)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.hasTemplates)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.id)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.category)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.dataType)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.systemFieldType)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.label)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.placeholder)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.description)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.required)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.fields), nameof(x => x.ordinal)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.descriptionTemplates), nameof(x => x.id)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.descriptionTemplates), nameof(x => x.descriptionTemplateId)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.descriptionTemplates), nameof(x => x.label)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.descriptionTemplates), nameof(x => x.minMultiplicity)].join('.'), // [nameof(x => x.definition), nameof(x => x.sections), nameof(x => x.descriptionTemplates), nameof(x => x.maxMultiplicity)].join('.'), // nameof(x => x.createdAt), // nameof(x => x.hash), // nameof(x => x.isActive) // ] // ) // .pipe(map(data => data as DmpBlueprint), takeUntil(this._destroyed)) // .subscribe( // data => successFunction(data), // error => this.onCallbackError(error) // ); // } // registerFormEventsForDmpBlueprint(): void { // this.formGroup.get('profile').valueChanges // .pipe( // takeUntil(this._destroyed)) // .subscribe(blueprintIdString => { // const blueprintId = Guid.parse(blueprintIdString); // if (blueprintId) { // this.getSingle(blueprintId, data => { // this.selectedDmpBlueprintDefinition = data.definition; // this.checkForGrant(); // this.checkForFunder(); // this.checkForProject(); // this.buildExtraFields(); // this.addProfiles(); // }); // } // else { // this.selectedDmpBlueprintDefinition = null; // } // }) // } // private buildExtraFields(): void { // const extraFields = new Array(); // this.selectedDmpBlueprintDefinition.sections.forEach(section => section.fields.forEach(field => { // if (field.category as unknown == DmpBlueprintFieldCategory.Extra) { // let extraField = new DmpExtraFieldEditorModel(); // extraField.id = field.id.toString(); // if (!isNullOrUndefined(this.dmp.extraFields)) { // let found = this.dmp.extraFields.find(f => Guid.parse(f.id) === field.id); // if (found !== undefined) { // extraField.value = found.value; // } // } // extraFields.push(extraField.buildForm()); // } // })); // this.formGroup.setControl('extraFields', new UntypedFormBuilder().array(extraFields)); // } // getExtraFieldIndex(id: string): string { // let foundFieldIndex: number; // (this.formGroup.get('extraFields') as UntypedFormArray).controls.forEach((element, index) => { // if (element.value.id === id) { // foundFieldIndex = index; // } // }); // return foundFieldIndex.toString(); // } // private checkForGrant() { // let hasGrant = false; // this.selectedDmpBlueprintDefinition.sections.forEach(section => section.fields.forEach( // field => { // if (field.category as unknown === DmpBlueprintFieldCategory.System && field.systemFieldType === DmpBlueprintSystemFieldType.GRANT) { // hasGrant = true; // } // } // )); // if (!hasGrant) { // this.formGroup.removeControl('grant'); // } // } // private checkForFunder() { // let hasFunder = false; // this.selectedDmpBlueprintDefinition.sections.forEach(section => section.fields.forEach( // field => { // if (field.category as unknown === DmpBlueprintFieldCategory.System && field.systemFieldType === DmpBlueprintSystemFieldType.FUNDER) { // hasFunder = true; // } // } // )); // if (!hasFunder) { // this.formGroup.removeControl('funder'); // } // } // private checkForProject() { // let hasProject = false; // this.selectedDmpBlueprintDefinition.sections.forEach(section => section.fields.forEach( // field => { // if (field.category as unknown === DmpBlueprintFieldCategory.System && field.systemFieldType === DmpBlueprintSystemFieldType.PROJECT) { // hasProject = true; // } // } // )); // if (!hasProject) { // this.formGroup.removeControl('project'); // } // } // private addProfiles(profiles?: DmpDatasetProfile[]) { // for (let i = 0; i < this.selectedDmpBlueprintDefinition.sections.length; i++) { // this.sectionTemplates.push(new Array()); // } // const templates: Array = new Array(); // this.selectedDmpBlueprintDefinition.sections.forEach(section => { // if (profiles !== undefined) { // profiles.filter(profile => profile.data.dmpSectionIndex.includes(section.ordinal - 1)).forEach(profile => this.sectionTemplates[section.ordinal - 1].push({ id: profile.descriptionTemplateId, label: profile.label, description: "" })); // } // else { // section.descriptionTemplates.forEach(template => { // this.sectionTemplates[section.ordinal - 1].push({ id: template.descriptionTemplateId.toString(), label: template.label, description: "" }) // let found: DmpDatasetProfile = templates.find(dmpDatasetProfile => Guid.parse(dmpDatasetProfile.descriptionTemplateId) == template.descriptionTemplateId); // if (found === undefined) { // let data: DmpDatasetProfileSectionsFormModel = new DmpDatasetProfileSectionsFormModel(); // data.dmpSectionIndex.push(section.ordinal - 1); // let id = null; // if (profiles !== undefined) { // let existedProfile = profiles.find(profile => Guid.parse(profile.descriptionTemplateId) == template.descriptionTemplateId); // if (existedProfile !== undefined) { // id = existedProfile.id; // } // } // let profile: DmpDatasetProfile = { // id: id, // descriptionTemplateId: template.descriptionTemplateId.toString(), // label: template.label, // data: data // }; // templates.push(profile); // } // else { // found.data.dmpSectionIndex.push(section.ordinal - 1); // } // }); // } // }); // (profiles !== undefined) ? this.formGroup.get('profiles').setValue(profiles) : this.formGroup.get('profiles').setValue(templates); // } // getLanguageInfos(): LanguageInfo[] { // return this.languageInfoService.getLanguageInfoValues(); // } // getAssociates(): UserModel[] { // let associates: UserModel[]; // if (this.formGroup.get('associatedUsers').value && this.formGroup.get('associatedUsers').value.length > 0) { // associates = []; // } else { // associates = this.associates; // } // //associates = (this.formGroup.get('researchers').value as any[]); // associates = associates.concat(this.formGroup.get('associatedUsers').value); // return associates; // } // // Researchers // filterResearchers(value: string): Observable { // //return this.externalSourcesService.searchDMPResearchers({ criteria: { name: value, like: null } }); // // const lookup = new ReferenceSearchLookup(); // // lookup.like = value; // // lookup.key = ''; // // lookup.type = ReferenceType.Researcher; // // return this.referenceService.search(lookup); // const lookup = new ReferenceSearchDefinitionLookup(); // //lookup.like=''; // //lookup.page.size = 1; // lookup.key = ''; // //from reference type db hardcoded // lookup.referenceTypeId = Guid.parse('51225b6a-86a6-48ac-9192-f15096dbcb8a'); // const fields = [ // ...ReferenceTypeEditorResolver.lookupFields() // ]; // lookup.project.fields = fields; // return this.referenceService.searchWithDefinition(lookup); // } // addResearcher(event: MouseEvent) { // event.stopPropagation(); // const dialogRef = this.dialog.open(AddResearcherComponent, { // data: this.formGroup.get('researchers') // }); // dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => { // if (result) { // const fullName = result.firstName + " " + result.lastName; // const newItem = { // label: null, // name: fullName, // id: null, // status: 0, // key: "Internal", // reference: result.reference // }; // const researchersArray = this.formGroup.get('researchers').value || []; // researchersArray.push(newItem); // this.formGroup.get('researchers').setValue(researchersArray); // } // }); // } // // Organizations // showOrganizationCreator(): boolean { // return this.configurationService.allowOrganizationCreator; // } // filterOrganisations(value: string): Observable { // return this.organizationService.searchGeneralOrganisations({ criteria: { labelLike: value } }); // } // cantAddOrganizations(): boolean { // if (!isNullOrUndefined(this.formGroup.get('organizations'))) { // return this.formGroup.get('organiztions').disabled; // } else { // return false; // } // } // addOrganization(event: MouseEvent) { // event.stopPropagation(); // const dialogRef = this.dialog.open(AddOrganizationComponent, { // data: this.formGroup.get('organisations') // }); // dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => { // if (result) { // const fullName = result.name; // const newItem = { // label: null, // name: fullName, // id: null, // status: 0, // key: "Internal", // reference: result.reference // }; // const organizationsArray = this.formGroup.get('organisations').value || []; // organizationsArray.push(newItem); // this.formGroup.get('organisations').setValue(organizationsArray); // } // }); // } // showToggleButton() { // return (!this.isFinalized && this.isUserOwner) || this.isClone; // } // allAvailableProfiles(event: MouseEvent) { // event.stopPropagation(); // const dialogRef = this.dialog.open(AvailableProfilesComponent, { // data: { // profiles: this.formGroup.get('profiles') // } // }); // return false; // } // onRemoveTemplate(event, sectionIndex: number) { // let found = false; // let profiles = this.formGroup.get('profiles').value as DmpDatasetProfile[]; // this.formGroup.get('datasets')['controls'].forEach(element => { // if ((element.get('profile').value.id === event.id) && (element.get('dmpSectionIndex').value === sectionIndex)) { // found = true; // this.uiNotificationService.snackBarNotification(this.language.instant('GENERAL.SNACK-BAR.UNSUCCESSFUL-REMOVE-TEMPLATE'), SnackBarNotificationLevel.Success); // } // }); // if (found) { // this.formGroup.get('profiles').setValue(profiles); // this.profilesAutoCompleteConfiguration = { // filterFn: this.filterProfiles.bind(this), // initialItems: (excludedItems: any[]) => this.filterProfiles('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))), // displayFn: (item) => item['label'], // titleFn: (item) => item['label'], // subtitleFn: (item) => item['description'], // popupItemActionIcon: 'visibility' // }; // } // else { // this.sectionTemplates[sectionIndex] = this.sectionTemplates[sectionIndex].filter(sectionProfile => sectionProfile.id !== event.id); // profiles = profiles.filter(sectionProfile => sectionProfile.descriptionTemplateId !== event.id); // this.formGroup.get('profiles').setValue(profiles); // } // } // addProfile(event, sectionIndex: number) { // const profiles = this.formGroup.get('profiles').value as DmpDatasetProfile[]; // let found = profiles.find((value) => value.id === event.id); // if (found !== undefined) { // if (found.data.dmpSectionIndex.indexOf(sectionIndex) === -1) { // found.data.dmpSectionIndex.push(sectionIndex); // } // else { // this.sectionTemplates[sectionIndex].pop(); // } // } // else { // let dmpDatasetProfileSection: DmpDatasetProfileSectionsFormModel = new DmpDatasetProfileSectionsFormModel(); // dmpDatasetProfileSection.dmpSectionIndex = [sectionIndex]; // profiles.push({ id: null, descriptionTemplateId: event.id, label: event.label, data: dmpDatasetProfileSection }); // } // this.formGroup.get('profiles').setValue(profiles); // } // onPreviewDescriptionTemplate(event, sectionIndex: number) { // const dialogRef = this.dialog.open(DatasetPreviewDialogComponent, { // width: '590px', // minHeight: '200px', // restoreFocus: false, // data: { // template: event // }, // panelClass: 'custom-modalbox' // }); // dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => { // if (result) { // this.addProfile(event, sectionIndex); // this.profilesAutoCompleteConfiguration = { // filterFn: this.filterProfiles.bind(this), // initialItems: (excludedItems: any[]) => this.filterProfiles('').pipe(map(result => result.filter(resultItem => (excludedItems || []).map(x => x.id).indexOf(resultItem.id) === -1))), // displayFn: (item) => item['label'], // titleFn: (item) => item['label'], // subtitleFn: (item) => item['description'], // popupItemActionIcon: 'visibility' // }; // } // }); // } // onOptionSelected(event, sectionIndex: number) { // try { // this.addProfile(event, sectionIndex); // // const profileCounts: Map = new Map(); // // profiles.forEach((value) => profileCounts.set(value.id, (profileCounts.get(value.id) !== undefined ? profileCounts.get(value.id): 0 ) + 1)); // // const duplicateProfiles = profiles.filter((value) => { // // let isOk = profileCounts.get(value.id) > 1; // // if (isOk) { // // profileCounts.set(value.id, 0); // // } // // return isOk; // // }); // // duplicateProfiles.forEach((value) => profiles.splice(profiles.lastIndexOf(value), 1)); // // profiles.sort((a,b)=> a.label.localeCompare(b.label)); // } catch { // console.info('Could not sort Dataset Templates') // } // } }