import { Component, ElementRef, Input, OnChanges, ViewChild } from '@angular/core'; import { CurrencyService } from '@core/services/currency.service'; import { TopLevelStats } from '@core/typings/budget.typing'; import { ClientSettingsService } from '@features/client-settings/client-settings.service'; import { ChartService } from '@yourcause/common'; import { I18nService } from '@yourcause/common/i18n'; import { ChartData, ChartOptions, ChartType, TooltipItem } from 'chart.js'; @Component({ selector: 'gc-budget-top-level-pie-chart', templateUrl: './budget-top-level-pie-chart.component.html', styleUrls: ['./budget-top-level-pie-chart.component.scss'] }) export class BudgetTopLevelPieChartComponent implements OnChanges { @Input() topLevelStats: TopLevelStats; @ViewChild('pieChart') pieChart: ElementRef; hidePie = false; data: number[]; branding = this.clientSettingsService.get('clientBranding'); backgroundColors: string[] = []; legendData: { label: string; color: string; }[]; labels = [ this.i18n.translate( 'BUDGET:textTotalRemaining', {}, 'Total remaining' ), this.i18n.translate( 'BUDGET:textTotalSpent', {}, 'Total spent' ), this.i18n.translate( 'GLOBAL:textTotalUnavailable', {}, 'Total unavailable' ) ]; totalReserveText = this.i18n.translate( 'BUDGET:textTotalReserved', {}, 'Total reserved' ); chartOptions: ChartOptions = { responsive: true, plugins: { legend: { display: false } }, tooltips: { callbacks: { label: (tooltipItem: TooltipItem, data: ChartData) => { return this.chartService.getLabelForTooltip( tooltipItem, data ); }, afterLabel: (tooltipItem: TooltipItem, data: ChartData) => { const amount = this.chartService.getAmountForTooltip( tooltipItem, data ); return this.currencyService.formatMoney( amount ); } } } } as ChartOptions; constructor ( private i18n: I18nService, private clientSettingsService: ClientSettingsService, private chartService: ChartService, private currencyService: CurrencyService ) { } get canReserveFunds () { return this.clientSettingsService.get('clientSettings').reserveFunds; } ngOnChanges () { if (this.canReserveFunds && this.topLevelStats.totalReserved) { this.labels = [ ...this.labels, this.totalReserveText ]; } this.pieChartSetup(); } pieChartSetup () { this.data = [ this.topLevelStats.totalRemaining, this.topLevelStats.totalSpent, this.topLevelStats.totalUnavailableAmount ]; if (this.canReserveFunds && this.topLevelStats.totalReserved) { this.data = [ ...this.data, this.topLevelStats.totalReserved ]; } this.hidePie = !this.topLevelStats.totalRemaining && !this.topLevelStats.totalSpent; this.backgroundColors = this.chartService.getFixedAmountOfColors( this.data.length, [ this.branding.brandPrimary, this.branding.brandSecondary, this.branding.brandUtility ] ); this.legendData = this.chartService.generateLegendData( this.data, this.labels, this.backgroundColors ); } }