Skip to content

Commit

Permalink
AC-253 date controller updated
Browse files Browse the repository at this point in the history
  • Loading branch information
Minotriz02 authored and Minotriz02 committed Oct 30, 2024
1 parent 080c865 commit deca4d2
Show file tree
Hide file tree
Showing 3 changed files with 109 additions and 50 deletions.
42 changes: 24 additions & 18 deletions src/src/components/weatherChart/WeatherChart.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from "react";
import React, { useMemo } from "react";
import { Col } from "react-bootstrap";
import { Line } from "react-chartjs-2";
import {
Expand Down Expand Up @@ -28,46 +28,52 @@ const WeatherChart = ({
unit,
chartOptions,
chartConfig,
days,
color,
}) => {
const filteredData = data.slice(-days);

const maxItem = filteredData.reduce(
(max, item) => (item.value > max.value ? item : max),
filteredData[0] || { label: "N/A", value: 0 }
const maxItem = useMemo(
() =>
data.reduce(
(max, item) => (item.value > max.value ? item : max),
data[0] || { label: "N/A", value: 0 }
),
[data]
);
const minItem = filteredData.reduce(
(min, item) => (item.value < min.value ? item : min),
filteredData[0] || { label: "N/A", value: 0 }

const minItem = useMemo(
() =>
data.reduce(
(min, item) => (item.value < min.value ? item : min),
data[0] || { label: "N/A", value: 0 }
),
[data]
);

const formatLabel = (label) => label.split("T")[0];

return (
<Col lg={6} className="mb-4">
<div className="bg-white rounded p-4 text-dark">
<h5>{title}</h5>
<hr />
<p>
La gráfica muestra la evolución de {title.toLowerCase()} registrada en
la estación meteorológica durante los <b>{days} últimos</b> días. En
ella se destaca que el día con la {title.toLowerCase()} más alta fue
el <b>{maxItem.label}</b>, alcanzando un máximo de{" "}
la estación meteorológica durante los{" "}
<b>últimos {data.length} días</b>. En ella se destaca que el día con
la {title.toLowerCase()} más alta fue el{" "}
<b>{formatLabel(maxItem.label)}</b>, alcanzando un máximo de{" "}
<b>
{maxItem.value.toFixed(2)} {unit}
</b>
, mientras que el día con la {title.toLowerCase()} más baja fue el{" "}
<b>{minItem.label}</b>, con una {title.toLowerCase()} de{" "}
<b>{formatLabel(minItem.label)}</b>, con una {title.toLowerCase()} de{" "}
<b>
{minItem.value.toFixed(2)} {unit}
</b>
. Esta visualización permite analizar las variaciones diarias de{" "}
{title.toLowerCase()} y ofrece una referencia clara para identificar
patrones climáticos recientes en la región.
</p>
<Line
data={chartConfig(title, filteredData, `${color}`)}
options={chartOptions}
/>
<Line data={chartConfig(title, data, color)} options={chartOptions} />
</div>
</Col>
);
Expand Down
109 changes: 81 additions & 28 deletions src/src/pages/dashboard/Dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { MapContainer, Marker, TileLayer, ZoomControl } from "react-leaflet";
import L from "leaflet";
import "./Dashboard.css";
import WeatherChart from "../../components/weatherChart/WeatherChart";
import { IconCalendarMonth } from "@tabler/icons-react";

const Dashboard = () => {
const [data, setData] = useState({
Expand All @@ -18,14 +19,15 @@ const Dashboard = () => {
const [stations, setStations] = useState([]);
const [currentStation, setCurrentStation] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [selectedDays, setSelectedDays] = useState(7);
const [startDate, setStartDate] = useState();
const [endDate, setEndDate] = useState();
const { idWS } = useParams();
const navigate = useNavigate();

const iconMarker = new L.Icon({
const iconMarker = useMemo(() => new L.Icon({
iconUrl: require("../../assets/img/marker.png"),
iconSize: [48, 48],
});
}), []);

useEffect(() => {
const fetchStations = async () => {
Expand All @@ -52,12 +54,23 @@ const Dashboard = () => {
if (!currentStation) return;
setIsLoading(true);
try {
const response = await Services.getDailyWeather(12, 2022, idWS);
const parsedData = parseWeatherData(
response.daily_readings,
response.month,
response.year
const lastDataAvailable = await Services.getLastDailyWeather(idWS);
const formattedEndDate = new Date(lastDataAvailable[0].date)
.toISOString()
.split("T")[0];
setEndDate(formattedEndDate);

const startDate = new Date(lastDataAvailable[0].date);
startDate.setDate(startDate.getDate() - 7);
const formattedStartDate = startDate.toISOString().split("T")[0];
setStartDate(formattedStartDate);

const response = await Services.getDailyWeather(
formattedStartDate,
formattedEndDate,
idWS
);
const parsedData = parseWeatherData(response.daily_data);
setData(parsedData);
} catch (error) {
console.error("Error fetching daily weather data:", error);
Expand All @@ -68,7 +81,28 @@ const Dashboard = () => {
fetchData();
}, [currentStation, idWS]);

const parseWeatherData = (readings, month, year) => {
useEffect(() => {
const fetchData = async () => {
if (!currentStation || !startDate || !endDate) return;
setIsLoading(true);
try {
const response = await Services.getDailyWeather(
startDate,
endDate,
idWS
);
const parsedData = parseWeatherData(response.daily_data);
setData(parsedData);
} catch (error) {
console.error("Error fetching daily weather data:", error);
} finally {
setIsLoading(false);
}
};
fetchData();
}, [startDate, endDate, currentStation, idWS]);

const parseWeatherData = (readings) => {
const result = {
tempMax: [],
tempMin: [],
Expand All @@ -77,7 +111,7 @@ const Dashboard = () => {
};

readings.forEach((reading) => {
const dayLabel = `${reading.day}/${month}/${year}`;
const dayLabel = `${reading.date}`;
result.tempMax.push({
label: dayLabel,
value:
Expand Down Expand Up @@ -111,9 +145,9 @@ const Dashboard = () => {
setCurrentStation(station);
};

const handleDaysChange = (event) => {
const value = event.target.value;
setSelectedDays(value === "" ? 7 : parseInt(value, 10));
const handleStartDateChange = (e) => {
const newStartDate = e.target.value;
setStartDate(newStartDate);
};

const chartConfig = (label, data, color) => ({
Expand Down Expand Up @@ -155,16 +189,39 @@ const Dashboard = () => {
) : (
<>
<Col className="bg-white rounded p-4 my-2 text-dark">
<div className="d-flex justify-content-between mb-2">
<Form.Select
aria-label="Periodo de tiempo"
className="w-auto"
onChange={handleDaysChange}
>
<option value="7">Últimos 7 días</option>
<option value="15">Últimos 15 días</option>
<option value="30">Últimos 30 días</option>
</Form.Select>
<div className="d-flex justify-content-between align-items-center mb-2">
<Form.Group className="d-flex">
<div className="d-flex flex-column">
<Form.Label className="me-2">
{" "}
<IconCalendarMonth className="me-2" /> Fecha de inicio:
</Form.Label>
<Form.Control
type="date"
aria-label="Fecha de inicio"
className="me-2"
value={startDate}
onChange={handleStartDateChange}
max={endDate}
/>
</div>
<div className="d-flex flex-column pb-2 justify-content-end mx-3">
-
</div>
<div className="d-flex flex-column">
<Form.Label className="me-2">
{" "}
<IconCalendarMonth className="me-2" />
Fecha de fin:
</Form.Label>
<Form.Control
type="date"
aria-label="Fecha de fin"
value={endDate}
disabled
/>
</div>
</Form.Group>
<Button variant="primary text-light">
Comparar con datos satelitales
</Button>
Expand Down Expand Up @@ -216,7 +273,6 @@ const Dashboard = () => {
unit="mm"
chartOptions={chartOptions}
chartConfig={chartConfig}
days={selectedDays}
color="rgba(26, 51, 237, 1)"
/>
<WeatherChart
Expand All @@ -225,7 +281,6 @@ const Dashboard = () => {
unit="°C"
chartOptions={chartOptions}
chartConfig={chartConfig}
days={selectedDays}
color="rgba(163, 36, 36, 1)"
/>
</Row>
Expand All @@ -236,7 +291,6 @@ const Dashboard = () => {
unit="°C"
chartOptions={chartOptions}
chartConfig={chartConfig}
days={selectedDays}
color="rgba(54, 227, 224, 1)"
/>
<WeatherChart
Expand All @@ -245,7 +299,6 @@ const Dashboard = () => {
unit="MJ"
chartOptions={chartOptions}
chartConfig={chartConfig}
days={selectedDays}
color="rgba(237, 185, 12, 1)"
/>
</Row>
Expand All @@ -256,4 +309,4 @@ const Dashboard = () => {
);
};

export default Dashboard;
export default Dashboard;
8 changes: 4 additions & 4 deletions src/src/services/Services.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ class Services {

/**
* Fetches daily weather data for a specific station.
* @param {number} month - The month for which to fetch data.
* @param {number} year - The year for which to fetch data.
* @param {number} startDate - The start date for which to fetch data.
* @param {number} endDate - The end date for which to fetch data.
* @param {string} stationId - The ID of the weather station.
* @returns {Promise<Object>} A promise that resolves to the daily weather data.
* @throws Will throw an error if the request fails.
*/
async getDailyWeather(month, year, stationId) {
const url = `/DailyWeatherData/Climatology/${stationId}/json?year=${year}&month=${month}`;
async getDailyWeather(startDate, endDate, stationId) {
const url = `/DailyWeatherData/Climatology/${stationId}/json?startDate=${startDate}&endDate=${endDate}`;
try {
const response = await apiClient.get(url);
return response.data;
Expand Down

0 comments on commit deca4d2

Please sign in to comment.