import {of as observableOf, Observable } from 'rxjs'; import {map, takeUntil } from 'rxjs/operators'; import { Component, OnInit } from '@angular/core'; import { AbstractControl, FormArray, FormControl, FormGroup } from '@angular/forms'; import { MatDialog } from '@angular/material/dialog'; import { MatSnackBar } from '@angular/material/snack-bar'; import { ActivatedRoute, Params, Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { environment } from '../../../../environments/environment'; import { ValidationErrorModel } from '../../../common/forms/validation/error-model/validation-error-model'; import { BaseComponent } from '../../../core/common/base/base.component'; import { GrantType } from '../../../core/common/enum/grant-type'; import { GrantListingModel } from '../../../core/model/grant/grant-listing'; import { GrantFileUploadService } from '../../../core/services/grant/grant-file-upload.service'; import { GrantService } from '../../../core/services/grant/grant.service'; import { ConfirmationDialogComponent } from '../../../library/confirmation-dialog/confirmation-dialog.component'; import { SnackBarNotificationComponent } from '../../../library/notification/snack-bar/snack-bar-notification.component'; import { BreadcrumbItem } from '../../misc/breadcrumb/definition/breadcrumb-item'; import { IBreadCrumbComponent } from '../../misc/breadcrumb/definition/IBreadCrumbComponent'; import { GrantEditorModel } from './grant-editor.model'; import { SnackBarNotificationLevel, UiNotificationService } from '../../../core/services/notification/ui-notification-service'; @Component({ selector: 'app-grant-editor-component', templateUrl: 'grant-editor.component.html', styleUrls: ['./grant-editor.component.scss'] }) export class GrantEditorComponent extends BaseComponent implements OnInit, IBreadCrumbComponent { breadCrumbs: Observable = observableOf([]); isNew = true; grant: GrantEditorModel; formGroup: FormGroup = null; host = environment.Server; editMode = false; sizeError = false; maxFileSize: number = 1048576; constructor( private grantService: GrantService, private route: ActivatedRoute, public snackBar: MatSnackBar, public router: Router, public language: TranslateService, private dialog: MatDialog, private grantFileUploadService: GrantFileUploadService, private uiNotificationService: UiNotificationService ) { super(); } ngOnInit() { this.route.params .pipe(takeUntil(this._destroyed)) .subscribe((params: Params) => { const itemId = params['id']; if (itemId != null) { this.isNew = false; this.grantService.getSingle(itemId).pipe(map(data => data as GrantListingModel)) .pipe(takeUntil(this._destroyed)) .subscribe(data => { this.grant = new GrantEditorModel().fromModel(data); this.formGroup = this.grant.buildForm(null, this.grant.type === GrantType.External || !this.editMode); const breadCrumbs = []; breadCrumbs.push({ parentComponentName: null, label: this.language.instant('NAV-BAR.GRANTS').toUpperCase(), url: '/grants' }); breadCrumbs.push({ parentComponentName: 'GrantListingComponent', label: this.grant.label, url: '/grants/edit/' + this.grant.id }); this.breadCrumbs = observableOf(breadCrumbs); }); } else { this.language.get('QUICKWIZARD.CREATE-ADD.CREATE.QUICKWIZARD_CREATE.ACTIONS.CREATE-NEW-GRANT').pipe(takeUntil(this._destroyed)).subscribe(x => { this.breadCrumbs = observableOf([ { parentComponentName: null, label: this.language.instant('NAV-BAR.GRANTS').toUpperCase(), url: '/grants' }, { parentComponentName: 'GrantListingComponent', label: x, url: '/grants/new/' }] ); }); this.grant = new GrantEditorModel(); setTimeout(() => { this.formGroup = this.grant.buildForm(); }); } }); } formSubmit(): void { this.touchAllFormFields(this.formGroup); if (!this.isFormValid()) { return; } this.onSubmit(); } public isFormValid() { return this.formGroup.valid; } onSubmit(): void { this.grantService.createGrant(this.formGroup.value) .pipe(takeUntil(this._destroyed)) .subscribe( complete => this.onCallbackSuccess(), error => this.onCallbackError(error) ); } onCallbackSuccess(): void { this.uiNotificationService.snackBarNotification(this.isNew ? this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-CREATION') : this.language.instant('GENERAL.SNACK-BAR.SUCCESSFUL-UPDATE'), SnackBarNotificationLevel.Success); this.router.navigate(['/grants']); } onCallbackError(errorResponse: any) { this.setErrorModel(errorResponse.error.payload); this.validateAllFormFields(this.formGroup); } public setErrorModel(validationErrorModel: ValidationErrorModel) { Object.keys(validationErrorModel).forEach(item => { (this.grant.validationErrorModel)[item] = (validationErrorModel)[item]; }); } public cancel(): void { this.router.navigate(['/grants']); } public delete(): void { const dialogRef = this.dialog.open(ConfirmationDialogComponent, { maxWidth: '300px', data: { message: this.language.instant('GENERAL.CONFIRMATION-DIALOG.DELETE-ITEM'), confirmButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CONFIRM'), cancelButton: this.language.instant('GENERAL.CONFIRMATION-DIALOG.ACTIONS.CANCEL'), isDeleteConfirmation: true } }); dialogRef.afterClosed().pipe(takeUntil(this._destroyed)).subscribe(result => { if (result) { this.grantService.delete(this.grant.id) .pipe(takeUntil(this._destroyed)) .subscribe( complete => { this.onCallbackSuccess() }, error => this.onCallbackError(error) ); } }); } public touchAllFormFields(formControl: AbstractControl) { if (formControl instanceof FormControl) { formControl.markAsTouched(); } else if (formControl instanceof FormGroup) { Object.keys(formControl.controls).forEach(item => { const control = formControl.get(item); this.touchAllFormFields(control); }); } else if (formControl instanceof FormArray) { formControl.controls.forEach(item => { this.touchAllFormFields(item); }); } } public validateAllFormFields(formControl: AbstractControl) { if (formControl instanceof FormControl) { formControl.updateValueAndValidity({ emitEvent: false }); } else if (formControl instanceof FormGroup) { Object.keys(formControl.controls).forEach(item => { const control = formControl.get(item); this.validateAllFormFields(control); }); } else if (formControl instanceof FormArray) { formControl.controls.forEach(item => { this.validateAllFormFields(item); }); } } public enableForm() { if (!this.isExternalGrant()) { this.editMode = true; this.formGroup.enable(); } } public disableForm() { this.editMode = false; this.formGroup.disable(); } public imgEnable(): boolean { if (this.isNew || this.editMode) { return true; } return false; } public goToGrantDmps() { this.router.navigate(['plans/grant/' + this.grant.id], { queryParams: { grantLabel: this.grant.label } }); } public isExternalGrant() { return this.grant.type === GrantType.External; } public previewImage(event): void { const fileList: FileList | File = event.target.files; const size: number = event.target.files[0].size; // Get file size. this.sizeError = size > this.maxFileSize; // Checks if file size is valid. const formdata: FormData = new FormData(); if (!this.sizeError) { if (fileList instanceof FileList) { for (let i = 0; i < fileList.length; i++) { formdata.append('file', fileList[i]); } } else { formdata.append('file', fileList); } this.grantFileUploadService.uploadFile(formdata) .pipe(takeUntil(this._destroyed)) .subscribe(files => this.formGroup.get('files').patchValue(files)); } } }