Skip to content

Commit

Permalink
graphics done, hope...
Browse files Browse the repository at this point in the history
  • Loading branch information
AlejandroAlberoni committed Oct 14, 2024
1 parent 03370d0 commit 144a400
Show file tree
Hide file tree
Showing 2 changed files with 104 additions and 74 deletions.
93 changes: 47 additions & 46 deletions app/home/metrics/chart.tsx
Original file line number Diff line number Diff line change
@@ -1,61 +1,62 @@
import React, { useState, useEffect } from 'react';
"use client"
import React, { useState, useEffect, useMemo } from 'react';
import { LineChart, Line, CartesianGrid, YAxis, XAxis, Tooltip, Legend } from 'recharts';
import { fetchMetricTypes } from '@/lib/shared_fetchers';
import { Metric } from '@/lib/types';

const transformData = (metrics: any[]) => {
const groupedData: { [key: string]: any } = {};

metrics.forEach((metric) => {
const dateKey = new Date(metric.datetime).toISOString(); // Garantir que datetime esteja formatado corretamente
if (!groupedData[dateKey]) {
groupedData[dateKey] = { datetime: dateKey };
const separateDataByMetricType = (data: any[]) => {
return data.reduce((acc: { [key: number]: any[] }, metric) => {
if (!acc[metric.metric_type_id]) {
acc[metric.metric_type_id] = [];
}
groupedData[dateKey][`metric_${metric.metric_type_id}`] = metric.value;
});

return Object.values(groupedData);
const readableMetric = {
...metric,
datetime: new Date(metric.datetime).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
};
acc[metric.metric_type_id].push(readableMetric);
return acc;
}, {});
};

const Chart = ({ data }: any) => {
const [ChartData, setChartData] = useState<any>(null);
const Chart = ({ data } : { data: Metric[]}) => {
const [metricTypes, setMetricTypes] = useState<Metric[] | null>(null);

const separateDataByMetricType = (data: any[]) => {
return data.reduce((acc: { [key: number]: any[] }, metric) => {
if (!acc[metric.metric_type_id]) {
acc[metric.metric_type_id] = [];
}
acc[metric.metric_type_id].push(metric);
return acc;
}, {});
};
const ChartData = useMemo(() => {
return data ? separateDataByMetricType(data) : null;
}, [data]);

useEffect(() => {
const separatedData = separateDataByMetricType(data);
setChartData(separatedData);
console.log(separatedData);
const fetchData = async () => {
const metricTypes = await fetchMetricTypes();
setMetricTypes(metricTypes);
};
fetchData();
}, []);

return (
<div className='grid grid-cols-1 md:grid-cols-2'>
<div className='grid grid-cols-1 md:grid-cols-2 md:gap-y-10'>
{
ChartData && Object.keys(ChartData).map((key) => (
<div className=''>
<h1 className='text-center text-xl font-montserrat'>{key}</h1>
<LineChart
key={key}
width={800}
height={400}
data={ChartData[key]}
margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
>
<CartesianGrid stroke="#ccc" />
<XAxis dataKey="datetime" />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="value" stroke="#8884d8" />
</LineChart>
</div>
))
ChartData && Object.keys(ChartData).map((key) => (
<div className=''>
<h1 className='text-center text-xl font-montserrat text-white font-bold'>
{metricTypes?.find(metric => metric.id === Number(key))?.name || "Métrica desconhecida"}
</h1>
<LineChart
key={key}
width={800}
height={400}
data={ChartData[Number(key)]}
margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
>
<CartesianGrid stroke="#ccc" />
<XAxis dataKey="datetime" />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="value" stroke="#8884d8" />
</LineChart>
</div>
))
}
</div>
);
Expand Down
85 changes: 57 additions & 28 deletions app/home/metrics/page.tsx
Original file line number Diff line number Diff line change
@@ -1,39 +1,66 @@
"use client";
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useMemo } from 'react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, SelectGroup, SelectLabel } from '@/components/ui/select';
import { fetchLocations, getDevices, getMetricsByDeviceId } from '@/lib/shared_fetchers';
import { TLocationSchema, TDeviceSchema, Metric, generateSensorData } from '@/lib/types';
import { TLocationSchema, TDeviceSchema } from '@/lib/types';
import Chart from './chart';

const dummyDevices: TDeviceSchema[] = [
{ id: 1, serial_number: 'SN001', model: 'Model A', location_id: 1 },
{ id: 2, serial_number: 'SN002', model: 'Model B', location_id: 1 },
{ id: 3, serial_number: 'SN003', model: 'Model C', location_id: 2 },
];


const METRICS = () => {
const [locations, setLocations] = useState<TLocationSchema[] | null>(null);
const [devices, setDevices] = useState<TDeviceSchema[] | null>(dummyDevices);
const [filteredDevices, setFilteredDevices] = useState<TDeviceSchema[] | null>(null);
const [selectedDeviceID, setSelectedDeviceID] = useState<string>();
const [deviceIDMetricData, setDeviceIDMetricData] = useState<any[] | null>(generateSensorData(new Date()));
const [devices, setDevices] = useState<TDeviceSchema[] | null>(null);
const [selectedLocation, setSelectedLocation] = useState<string>();
const [selectedDevice, setSelectedDevice] = useState<string>();
const [deviceIDMetricData, setDeviceIDMetricData] = useState<any[] | null>(null);

const filteredDevices = useMemo(() => {
return selectedLocation == 'all' ? devices : devices?.filter(device => device.location_id == Number(selectedLocation));
}, [selectedLocation])

//useEffect(() => {
// const fetchData = async () => {
// //const locationdata = await fetchLocations();
// const devicedata = await getDevices();
// //setLocations(locationdata);
// setDevices(devicedata);
// }
// fetchData();
//}, [])
useEffect(() => {
const fetchData = async () => {
const locationdata = await fetchLocations();
const devicedata = await getDevices();
setLocations(locationdata);
setDevices(devicedata);
}
fetchData();
}, [])

const handleButton = () => {
return selectedDevice ?
getMetricsByDeviceId(Number(selectedDevice)).then((data) => { setDeviceIDMetricData(data) }) : console.log('Selecione um dispositivo');
}
return (
<div className='flex justify-center'>
<div className=''>
<div className='flex justify-center flex-col md:flex-row md:mt-4 items-center md:items-baseline space-y-4 md:space-y-0 space-x-0 md:space-x-6 rounded-3xl py-8 px-4'>
<Select value={selectedDeviceID} onValueChange={setSelectedDeviceID}>

<Select value={selectedLocation} onValueChange={setSelectedLocation}>
<SelectTrigger className='w-[300px] bg-white'>
<SelectValue placeholder="Selecione a localização:" />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectLabel>
Localizações
</SelectLabel>
<SelectItem key="all" value='all'>
<p>Todas</p>
</SelectItem>
{
locations &&
locations.map((location) => (
<SelectItem key={location.id} value={`${location.id}`}>
<p>{location.campus} - {location.building} - {location.room}</p>
</SelectItem>
))
}
</SelectGroup>
</SelectContent>
</Select>

<Select value={selectedDevice} onValueChange={setSelectedDevice}>
<SelectTrigger className='w-[300px] bg-white'>
<SelectValue placeholder="Selecione o dispositivo:" />
</SelectTrigger>
Expand All @@ -43,8 +70,8 @@ const METRICS = () => {
Dispositivos
</SelectLabel>
{
devices &&
devices.map((device) => (
filteredDevices &&
filteredDevices.map((device) => (
<SelectItem key={device.id} value={`${device.id}`}>
<p>{device.serial_number} - {device.model}</p>
</SelectItem>
Expand All @@ -53,14 +80,16 @@ const METRICS = () => {
</SelectGroup>
</SelectContent>
</Select>
<button onClick={() => getMetricsByDeviceId(Number(selectedDeviceID)).then((data) => {setDeviceIDMetricData(data)})} className='px-10 py-2 rounded-xl text-white bg-purple-600 hover:bg-purple-700 shadow-md font-bold text-lg'>

<button onClick={handleButton} className='px-10 py-2 rounded-xl text-white bg-purple-600 hover:bg-purple-700 shadow-md font-bold text-lg'>
Ver métricas
</button>

</div>
{/*
{
deviceIDMetricData &&
<Chart data={deviceIDMetricData} />
*/}
<Chart data={deviceIDMetricData} />
}
</div>
</div>
);
Expand Down

0 comments on commit 144a400

Please sign in to comment.