argos/dmp-frontend/src/app/ui/dmp/editor/add-organization/add-organization.component.ts

82 lines
2.9 KiB
TypeScript

import { Component, Inject, OnInit } from '@angular/core';
import { AbstractControl, AsyncValidatorFn, FormControl, FormGroup, ValidationErrors } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { ExternalSourcesService } from '@app/core/services/external-sources/external-sources.service';
import { ExternalResearcherService } from '@app/core/services/external-sources/researcher/external-researcher.service';
import { OrganisationService } from '@app/core/services/organisation/organisation.service';
import { BaseComponent } from '@common/base/base.component';
import { Observable } from 'rxjs';
import { debounceTime, distinctUntilChanged, first, map, mergeMap, takeUntil } from 'rxjs/operators';
import { OrganizationEditorModel } from './add-organization.model';
@Component({
selector: 'app-add-organization-component',
templateUrl: 'add-organization.component.html',
})
export class AddOrganizationComponent extends BaseComponent implements OnInit {
public formGroup: FormGroup;
private existingReferences: string[] = [];
get referenceExists(){
const reference = this.formGroup.get('reference').value;
return this.existingReferences.find((r)=>r === reference)
}
constructor(
private externalSourcesService: ExternalSourcesService,
private externalResearcherService: ExternalResearcherService,
public dialogRef: MatDialogRef<AddOrganizationComponent>,
@Inject(MAT_DIALOG_DATA) public data: any
) {
super();
if(data){
const researchers = (data as FormControl).value ;
if(researchers){
this.existingReferences = (researchers as Array<any>).map(researcher => researcher.reference);
}
}}
ngOnInit(): void {
const researcher = new OrganizationEditorModel();
this.formGroup = researcher.buildForm();
this.formGroup.get('reference').setAsyncValidators(this.organizationUniqueIdentifier());
}
send(value: any) {
this.externalResearcherService.createResearcher(this.formGroup.value)
.pipe(takeUntil(this._destroyed))
.subscribe(
null, null, () => this.dialogRef.close()
);
}
addOrganization() {
this.dialogRef.close(this.formGroup.value);
}
isFormValid() {
return this.formGroup.valid && !this.referenceExists;
}
private organizationUniqueIdentifier(): AsyncValidatorFn{
return (control: AbstractControl) :Observable<ValidationErrors | null> =>{
return control.valueChanges.pipe(
debounceTime(600),
mergeMap(value=>this.externalSourcesService.searchDMPOrganizations('',value)),
takeUntil(this._destroyed),
map((response)=>{
if(response && response.length){
const internalOrganizations = (response as Array<any>).filter(organization=> organization.key === "Internal");
if(internalOrganizations && internalOrganizations.length){
return {organizationIdentifierExists:true};
}
}
return null;
})
).pipe(first())
}
}
}