import { Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core'; import { Validators } from '@angular/forms'; import { AdHocReportingUI } from '@core/typings/ui/ad-hoc-reporting.typing'; import { ReportFieldDataOptions } from '@features/configure-forms/form.typing'; import { AdHocReportingService } from '@features/reporting/services/ad-hoc-reporting.service'; import { TypeaheadSelectOption, TypeSafeFormBuilder, TypeSafeFormGroup } from '@yourcause/common'; import { Subscription } from 'rxjs'; @Component({ selector: 'gc-report-field-data-options-widget', templateUrl: './report-field-data-options-widget.component.html', styleUrls: ['./report-field-data-options-widget.component.scss'] }) export class ReportFieldDataOptionsComponent implements OnInit, OnDestroy { @Input() reportFieldDataOptions: ReportFieldDataOptions; @Output() isValidChange = new EventEmitter(); @Output() onChange = new EventEmitter(); formGroup: TypeSafeFormGroup; objectOptions: TypeaheadSelectOption[]; displayOptions: TypeaheadSelectOption[]; buckets: AdHocReportingUI.ColumnBucket[]; sub = new Subscription(); constructor ( private formBuilder: TypeSafeFormBuilder, private adHocReportingService: AdHocReportingService ) { } ngOnInit () { this.setOptions(); this.setupFormGroup(); } setupFormGroup () { this.setDisplayOptions( this.reportFieldDataOptions?.reportFieldObject || 'application' ); this.formGroup = this.formBuilder.group ({ reportFieldObject: [ this.reportFieldDataOptions?.reportFieldObject || 'application', Validators.required ], reportFieldDisplay: [ this.reportFieldDataOptions?.reportFieldDisplay || 'totalCashAwardAmount', Validators.required ] }); this.sub.add(this.formGroup.statusChanges.subscribe(() => { this.isValidChange.emit(this.formGroup.valid); })); this.handleDataChange(this.formGroup.value.reportFieldDisplay); } setOptions () { this.buckets = this.adHocReportingService.getReportfieldBuckets(); this.objectOptions = this.buckets.map((bucket) => { return { label: bucket.display, value: bucket.property }; }); } handleDataChange (reportFieldDisplay: string) { if (reportFieldDisplay) { this.onChange.emit(this.formGroup.value); } } setDisplayOptions (bucketProp: string) { this.displayOptions = this.adHocReportingService.getReportFieldColumnsByBucket( this.buckets, bucketProp ).map((option) => { return { label: option.definition.display, value: option.definition.column }; }); const reportFieldDisplay = this.formGroup?.value?.reportFieldDisplay; if (!!reportFieldDisplay) { // If items change, check if reportFieldDisplay should be reset const itemExists = this.displayOptions.some((item) => { return item.value === reportFieldDisplay; }); if (!itemExists) { this.formGroup.get('reportFieldDisplay').setValue( this.displayOptions[0].value ); } } } ngOnDestroy () { this.sub.unsubscribe(); } }