Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Añadido filtro a gráfica de resumen #368

Merged
merged 2 commits into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ <h2>{{'overview.barChart.title' | translate}}</h2>
[maxDate]="today"
/>
</form>
<p-button label="{{'app.weeks' | translate }}" [disabled]="timeFilterSelected === timesFilter.WEEK || !obsFiltered.length" (onClick)="timeFilter(timesFilter.WEEK)" />
<p-button label="{{'app.weeks' | translate }}" [disabled]="timeFilterSelected === timesFilter.WEEKS || !obsFiltered.length" (onClick)="timeFilter(timesFilter.WEEKS)" />
<p-button label="{{'app.weekdays' | translate }}" [disabled]="timeFilterSelected === timesFilter.WEEKDAYS || !obsFiltered.length" (onClick)="timeFilter(timesFilter.WEEKDAYS)" />
<p-button label="{{'app.months' | translate }}" [disabled]="timeFilterSelected === timesFilter.MONTH || !obsFiltered.length" (onClick)="timeFilter(timesFilter.MONTH)" />
<p-button label="{{'app.years' | translate }}" [disabled]="timeFilterSelected === timesFilter.YEAR || !obsFiltered.length" (onClick)="timeFilter(timesFilter.YEAR)" />
<p-button icon="pi pi-times" [disabled]="timeFilterSelected === timesFilter.DELETE || !obsFiltered.length" (onClick)="timeFilter(timesFilter.DELETE)" />
Expand Down
220 changes: 132 additions & 88 deletions src/app/modules/overview/components/bar-chart/bar-chart.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ type EChartsOption = echarts.ComposeOption<
templateUrl: './bar-chart.component.html',
styleUrl: './bar-chart.component.scss',
})
export class BarChartComponent implements OnInit, AfterViewInit, OnDestroy {
export class BarChartComponent implements OnInit, OnDestroy {
private translate = inject(TranslateService);
private observationService: ObservationsService = inject(ObservationsService);
private subscriptions = new Subscription();
Expand All @@ -42,7 +42,8 @@ export class BarChartComponent implements OnInit, AfterViewInit, OnDestroy {
private options: EChartsOption;
public timesFilter = {
DELETE: 'delete',
WEEK: 'week',
WEEKDAYS: 'weekdays',
WEEKS: 'weeks',
MONTH: 'month',
YEAR: 'year',
};
Expand Down Expand Up @@ -101,6 +102,91 @@ export class BarChartComponent implements OnInit, AfterViewInit, OnDestroy {
this.observationService.getAllObservationsFormated().subscribe((data) => {
this.minDate = data[0].completeDay;
})



const chartDom = document.getElementById('bar-chart-container');
this.myChart = echarts.init(chartDom);
this.myChart.showLoading('default', this.loadingOptions);

this.subscriptions.add(
this.observationService.getAllObservationsFormated().subscribe((data) => {
try {
this.observations = data;
this.minDate = data[0].completeDay;
const arr30DaysBefore = data.filter((obs) => {
const isBeforeToday = obs.completeDay <= this.today;
const isAfterLastDay30 = obs.completeDay >= this.lastDay30;
if (isBeforeToday && isAfterLastDay30) return true;
return false;
});

this.obsFiltered = arr30DaysBefore;

const getFirstDayOfEachMonth =
this.getFirstDayOfEachMonth(arr30DaysBefore);

this.options = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'none',
},
formatter: (params: CallbackDataParams[]) => {
if (this.timeFilterSelected === this.timesFilter.DELETE) {
return `
<b>${this.translate.instant(
'overview.barChart.tooltip.date'
)}:</b>${this.obsFiltered[params[0].dataIndex].date} <br>
<b>${this.translate.instant(
'overview.barChart.tooltip.numObs'
)}:</b> ${params[0].data}
`;
}
return `
<b>${this.translate.instant(
'overview.barChart.tooltip.numObs'
)}:</b> ${params[0].data}
`;
},
},
xAxis: [
{
type: 'category',
data: getFirstDayOfEachMonth,
axisLabel: {
interval: 0, // This forces displaying all labels
rotate: 45, // Optional: you can rotate labels to prevent overlapping
},
position: 'bottom',
},
],
yAxis: {
name: this.translate.instant('overview.barChart.yAxis'),
nameLocation: 'middle',
nameGap: 35,
type: 'value',
nameTextStyle: {
fontSize: 15,
fontWeight: 600,
},
},
series: [
{
data: arr30DaysBefore.map((obs) => obs.count),
type: 'bar',
},
],
};
this.myChart.hideLoading();

this.myChart.setOption(this.options);
} catch (error) {
console.error('after',error)
throw Error('Error getting all observations', error);
}
})
);
}

private updateChart(xAxis: string[], serieData: number[]) {
Expand All @@ -124,6 +210,20 @@ export class BarChartComponent implements OnInit, AfterViewInit, OnDestroy {
return day;
}

private currentYearWeek(date: Date) {
//calculamos la semana del año teniendo en cuenta que la primera semana del año no tiene por que empezar en lunes y que la semana actual puede empezar en el año anterior
function getWeek(date: Date) {
const dateCopy = new Date(date.getTime());
dateCopy.setHours(0, 0, 0, 0);
dateCopy.setDate(dateCopy.getDate() + 3 - ((dateCopy.getDay() + 6) % 7));
const week1 = new Date(dateCopy.getFullYear(), 0, 4);
return ( 1 + Math.round(((dateCopy.getTime() - week1.getTime()) / 86400000 -3 + ((week1.getDay() + 6) % 7)) / 7 ) );
}

const week = getWeek(date);
return `${date.getFullYear()}-${week}`;
}

public timeFilter(filter: string) {
try {
//Get obs filtered by the days selected
Expand All @@ -138,7 +238,32 @@ export class BarChartComponent implements OnInit, AfterViewInit, OnDestroy {
let dataXaxis: string[] = [];
let dataSerie: number[] = [];
if (filter !== this.timesFilter.DELETE) {
if (filter === this.timesFilter.WEEK) {

//Semenas seleccionadas en el filtro, en la fila x mostramos el numero de la semana en el año
if (filter === this.timesFilter.WEEKS) {

const weeksSelected = obsFiltered.reduce((acc, curr) => {
if (acc.includes(this.currentYearWeek(curr.completeDay))) return acc;
return [...acc, this.currentYearWeek(curr.completeDay)];
}, []);
const series = weeksSelected.map((week) => {
const groupOfWeekSelected = obsFiltered.filter(
(obs) => this.currentYearWeek(obs.completeDay) === week
);
return groupOfWeekSelected.reduce(
(acc, curr) => acc + curr.count,
0
);
});
dataXaxis = weeksSelected.map((week) => week);
dataSerie = weeksSelected.map((week) => {
const index = weeksSelected.indexOf(week);
return series[index];
});
}

//Dias de la semana
if (filter === this.timesFilter.WEEKDAYS) {
const daysOfWeekSelected = obsFiltered.reduce((acc, curr) => {
if (acc.includes(this.currentWeek(curr.completeDay))) return acc;
return [...acc, this.currentWeek(curr.completeDay)];
Expand All @@ -158,6 +283,8 @@ export class BarChartComponent implements OnInit, AfterViewInit, OnDestroy {
return series[index];
});
}

//mes
if (filter === this.timesFilter.MONTH) {
const months: number[] = obsFiltered.reduce((acc, curr) => {
const month = curr.completeDay.getMonth();
Expand All @@ -180,6 +307,8 @@ export class BarChartComponent implements OnInit, AfterViewInit, OnDestroy {
);
});
}

//año
if (filter === this.timesFilter.YEAR) {
dataXaxis = obsFiltered.reduce((acc, curr) => {
const year = curr.completeDay.getFullYear();
Expand Down Expand Up @@ -232,91 +361,6 @@ export class BarChartComponent implements OnInit, AfterViewInit, OnDestroy {
}
}

async ngAfterViewInit(): Promise<void> {
const chartDom = document.getElementById('bar-chart-container');
this.myChart = echarts.init(chartDom);
this.myChart.showLoading('default', this.loadingOptions);

this.subscriptions.add(
this.observationService.getAllObservationsFormated().subscribe((data) => {
try {
this.observations = data;
this.minDate = data[0].completeDay;
const arr30DaysBefore = data.filter((obs) => {
const isBeforeToday = obs.completeDay <= this.today;
const isAfterLastDay30 = obs.completeDay >= this.lastDay30;
if (isBeforeToday && isAfterLastDay30) return true;
return false;
});

this.obsFiltered = arr30DaysBefore;

const getFirstDayOfEachMonth =
this.getFirstDayOfEachMonth(arr30DaysBefore);

this.options = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'none',
},
formatter: (params: CallbackDataParams[]) => {
if (this.timeFilterSelected === this.timesFilter.DELETE) {
return `
<b>${this.translate.instant(
'overview.barChart.tooltip.date'
)}:</b>${this.obsFiltered[params[0].dataIndex].date} <br>
<b>${this.translate.instant(
'overview.barChart.tooltip.numObs'
)}:</b> ${params[0].data}
`;
}
return `
<b>${this.translate.instant(
'overview.barChart.tooltip.numObs'
)}:</b> ${params[0].data}
`;
},
},
xAxis: [
{
type: 'category',
data: getFirstDayOfEachMonth,
axisLabel: {
interval: 0, // This forces displaying all labels
rotate: 45, // Optional: you can rotate labels to prevent overlapping
},
position: 'bottom',
},
],
yAxis: {
name: this.translate.instant('overview.barChart.yAxis'),
nameLocation: 'middle',
nameGap: 35,
type: 'value',
nameTextStyle: {
fontSize: 15,
fontWeight: 600,
},
},
series: [
{
data: arr30DaysBefore.map((obs) => obs.count),
type: 'bar',
},
],
};
this.myChart.hideLoading();

this.myChart.setOption(this.options);
} catch (error) {
console.error('after',error)
throw Error('Error getting all observations', error);
}
})
);
}

ngOnDestroy(): void {
this.subscriptions.unsubscribe();
}
Expand Down
32 changes: 0 additions & 32 deletions src/app/modules/soundscape/page/soundscape.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -544,38 +544,6 @@ export class SoundscapeComponent implements AfterViewInit, OnDestroy {
},
});

// Agregar capa para los paths individuales
this.map.addLayer({
id: 'LineString',
type: 'line',
//filtramos si es zoom es mayor que 14
//minzoom: 14,
source: 'polylines',
layout: {
'line-join': 'round',
'line-cap': 'round'
},
paint: {
'line-color':
[
'case',
['==', ['get', 'pause'], true],
'#FFF', // Dasharray si pause es 1
['get', 'color'] // Sin dasharray si pause no es 1
]
,
'line-width': 20,//['get', 'width'],
"line-dasharray": [
0, 1.2
// 'case',
// ['==', ['get', 'pause'], true],
// [2, 3], // Dasharray si pause es 1
// [1, 0] // Sin dasharray si pause no es 1
]
}
});


// cluster de los puntos de inicio
this.map.addLayer({
id: 'clusters',
Expand Down
Loading