From ea02576095e2abb25257d7438194b7bad94b57ea Mon Sep 17 00:00:00 2001 From: marcio1002 Date: Fri, 14 Jul 2023 17:04:29 -0300 Subject: [PATCH] =?UTF-8?q?Corre=C3=A7=C3=B5es?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/pages/telemetria/index.tsx | 1310 +++++++++++++++++++------------- 1 file changed, 776 insertions(+), 534 deletions(-) diff --git a/src/pages/telemetria/index.tsx b/src/pages/telemetria/index.tsx index 7a8e242..0cc365a 100644 --- a/src/pages/telemetria/index.tsx +++ b/src/pages/telemetria/index.tsx @@ -1,37 +1,42 @@ -import React, { useEffect, useState } from 'react'; +import React, { useEffect, useState } from 'react' -import FormControl from '@mui/material/FormControl'; -import InputLabel from '@mui/material/InputLabel'; -import MenuItem from '@mui/material/MenuItem'; -import Select from '@mui/material/Select'; -import Head from 'next/head'; -import GradientButton from '../../components/buttons/gradientButton/GradientButton'; -import Header from '../../components/header/Header'; -import { Buttons, ChartFilters, TableHeader, TelemetriaView } from '../../styles/layouts/Telemetria/TelemetriaView'; +import FormControl from '@mui/material/FormControl' +import InputLabel from '@mui/material/InputLabel' +import MenuItem from '@mui/material/MenuItem' +import Select from '@mui/material/Select' +import Head from 'next/head' +import GradientButton from '../../components/buttons/gradientButton/GradientButton' +import Header from '../../components/header/Header' +import { + Buttons, + ChartFilters, + TableHeader, + TelemetriaView +} from '../../styles/layouts/Telemetria/TelemetriaView' -import MuiAlert, { AlertProps } from '@mui/material/Alert'; -import Snackbar from '@mui/material/Snackbar'; -import { GetServerSideProps } from 'next'; -import { parseCookies } from 'nookies'; -import { DemRegXDemConChart } from '../../components/graph/DemRegXDemConChart'; -import getAPIClient from '../../services/ssrApi'; -import RenderIf from '../../utils/renderIf'; +import MuiAlert, { AlertProps } from '@mui/material/Alert' +import Snackbar from '@mui/material/Snackbar' +import { GetServerSideProps } from 'next' +import { parseCookies } from 'nookies' +import { DemRegXDemConChart } from '../../components/graph/DemRegXDemConChart' +import getAPIClient from '../../services/ssrApi' +import RenderIf from '../../utils/renderIf' -import Tab from '@mui/material/Tab'; -import Tabs from '@mui/material/Tabs'; +import Tab from '@mui/material/Tab' +import Tabs from '@mui/material/Tabs' -import TextField from '@mui/material/TextField'; -import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns'; -import { DesktopDatePicker } from '@mui/x-date-pickers/DesktopDatePicker'; -import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; -import { format } from 'date-fns'; -import BasicButton from '../../components/buttons/basicButton/BasicButton'; -import { DiscretizedConsumptionChart } from '../../components/graph/DiscretizedConsumptionChart'; -import FatorPotenciaChart from '../../components/graph/fatorPotenciaChart'; -import PageTitle from '../../components/pageTitle/PageTitle'; -import { getDemand } from '../../services/charts/telemetry/getDemand'; -import { getDiscretization } from '../../services/charts/telemetry/getDiscretization'; -import { getPowerFactorData } from '../../services/charts/telemetry/getPowerFactor'; +import TextField from '@mui/material/TextField' +import { AdapterDateFns } from '@mui/x-date-pickers/AdapterDateFns' +import { DesktopDatePicker } from '@mui/x-date-pickers/DesktopDatePicker' +import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider' +import { format } from 'date-fns' +import BasicButton from '../../components/buttons/basicButton/BasicButton' +import { DiscretizedConsumptionChart } from '../../components/graph/DiscretizedConsumptionChart' +import FatorPotenciaChart from '../../components/graph/fatorPotenciaChart' +import PageTitle from '../../components/pageTitle/PageTitle' +import { getDemand } from '../../services/charts/telemetry/getDemand' +import { getDiscretization } from '../../services/charts/telemetry/getDiscretization' +import { getPowerFactorData } from '../../services/charts/telemetry/getPowerFactor' const Alert = React.forwardRef(function Alert( props, @@ -40,20 +45,33 @@ const Alert = React.forwardRef(function Alert( return }) +const months = [ + 'Jan', + 'Fev', + 'Mar', + 'Abr', + 'Mai', + 'Jun', + 'Jul', + 'Ago', + 'Set', + 'Out', + 'Nov', + 'Dez' +] + export default function Telemetria({ userName, clients }: any) { - const [unity, setUnity] = useState(clients[0]?.codigo_scde); - const [startDate, setStartDate] = useState(new Date()); - const [endDate, setEndDate] = useState(new Date()); - const [month, setMonth] = useState(new Date().getMonth()); - const [endMonth, setEndMonth] = useState(new Date().getMonth() + 1); - const [discretization, setDiscretization] = useState('1_hora'); + const [unity, setUnity] = useState(clients[0]?.codigo_scde) + const [startDate, setStartDate] = useState(new Date()) + const [endDate, setEndDate] = useState(new Date()) + const [month, setMonth] = useState(new Date().getMonth()) + const [endMonth, setEndMonth] = useState(new Date().getMonth() + 1) + const [discretization, setDiscretization] = useState('1_hora') const [openSnackSuccess, setOpenSnackSuccess] = useState(false) const [openSnackError, setOpenSnackError] = useState(false) const [openSnackFields, setOpenSnackFields] = useState(false) - const months = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'] - const handleCloseSnack = ( event?: React.SyntheticEvent | Event, reason?: string @@ -68,67 +86,61 @@ export default function Telemetria({ userName, clients }: any) { } function downloadCSVFile(csv, filename) { - /*exemplo caso mudar o type do blob não resolva + const csv_file = new Blob([csv], { type: 'text/csv;charset=utf-8' }) - var csvContent = 'éà; ça; 12\nà@€; çï; 13', - textEncoder = new TextEncoder('windows-1252'); - */ + const download_link = document.createElement('a') - const csv_file = new Blob([csv], { type: "text/csv;charset=utf-8" }); + download_link.download = filename - const download_link = document.createElement("a"); + download_link.href = window.URL.createObjectURL(csv_file) - download_link.download = filename; + download_link.style.display = 'none' - download_link.href = window.URL.createObjectURL(csv_file); + document.body.appendChild(download_link) - download_link.style.display = "none"; - - document.body.appendChild(download_link); - - download_link.click(); + download_link.click() } - function htmlToCSV(html, filename) { - const data = []; - const rows = document.querySelectorAll("table tr"); + function htmlToCSV(filename) { + const data = [] + const rows = document.querySelectorAll('table tr') for (let i = 0; i < rows.length; i++) { - const row = [], cols: any = rows[i].querySelectorAll("td, th"); + const row = [], + cols: any = rows[i].querySelectorAll('td, th') for (let j = 0; j < cols.length; j++) { - row.push(cols[j].innerText); + row.push(cols[j].innerText) } - data.push(row.join(";")); + data.push(row.join(';')) } - downloadCSVFile(data.join("\n"), filename); + downloadCSVFile(data.join('\n'), filename) } const [tableData, setTableData] = useState(null) const [loader, setLoader] = useState(false) - const [menu, setMenu] = useState(0); + const [menu, setMenu] = useState(0) - const [showChart, setShowChart] = useState(false); + const [showChart, setShowChart] = useState(false) - const [send, setSend] = useState(false); - - const [open, setOpen] = useState(false); + const [send, setSend] = useState(false) const handleChangeStartDate = (newValue: Date | null) => { setStartDate(newValue) - }; + } const handleChangeEndDate = (newValue: Date | null) => { setEndDate(newValue) - }; + } - - const [fatorPotenciaData, setFatorPotenciaData] = useState([]); - const [demRegXDemCon, setDemRegXDemCon] = useState([]); - const [discretizedConsumptionData, setDiscretizedConsumptionData] = useState([]); + const [fatorPotenciaData, setFatorPotenciaData] = useState([]) + const [demRegXDemCon, setDemRegXDemCon] = useState([]) + const [discretizedConsumptionData, setDiscretizedConsumptionData] = useState( + [] + ) useEffect(() => { setSend(false) @@ -136,26 +148,53 @@ export default function Telemetria({ userName, clients }: any) { useEffect(() => { const firstOfTheMonth = format(new Date(startDate).setDate(2), 'yyyy-MM-dd') - const lastOfTheMonth = format(new Date(startDate.getFullYear(), startDate.getMonth() + 1, 0), 'yyyy-MM-dd') + const lastOfTheMonth = format( + new Date(startDate.getFullYear(), startDate.getMonth() + 1, 0), + 'yyyy-MM-dd' + ) setStartDate(new Date(firstOfTheMonth)) setLoader(true) - getDiscretization(unity, new Date(firstOfTheMonth), new Date(lastOfTheMonth), discretization) - .then(result => { setDiscretizedConsumptionData(result); setSend(false); setLoader(false) }) - .catch(() => { setSend(false); setOpenSnackFields(true) }) + getDiscretization( + unity, + new Date(firstOfTheMonth), + new Date(lastOfTheMonth), + discretization + ) + .then((result) => { + setDiscretizedConsumptionData(result) + setSend(false) + setLoader(false) + }) + .catch(() => { + setSend(false) + setOpenSnackFields(true) + }) getDemand(unity, startDate, endDate, discretization) - .then(result => { - setDemRegXDemCon(result); - setSend(false); + .then((result) => { + setDemRegXDemCon(result) + setSend(false) setTableData(result) }) - .catch(() => { setSend(false); setOpenSnackFields(true); setLoader(false) }) + .catch(() => { + setSend(false) + setOpenSnackFields(true) + setLoader(false) + }) getPowerFactorData(unity, startDate, endDate, discretization) - .then(result => { setFatorPotenciaData(result); setSend(false); setLoader(false) }) - .catch(() => { setSend(false); setOpenSnackFields(true); setLoader(false) }) + .then((result) => { + setFatorPotenciaData(result) + setSend(false) + setLoader(false) + }) + .catch(() => { + setSend(false) + setOpenSnackFields(true) + setLoader(false) + }) }, []) return ( @@ -163,6 +202,7 @@ export default function Telemetria({ userName, clients }: any) { Smart Energia - Telemetria + + - Não foi possivel pegar os dados! + Não foi possível pegar os dados! @@ -205,450 +246,648 @@ export default function Telemetria({ userName, clients }: any) {
- +
- { - typeof window === 'undefined' || typeof window === undefined ? null : - - {/* + {/* */} - - - - setMenu(nv)} aria-label=""> - - - - - - - {/* discretization chart */} - - -
- - Unidade - - -
-
- - Discretização - - -
- { - discretization === '1_mes' ? - <> - - Discretização - - - {discretization === '1_mes' && - Discretização - - } - - : - -
- } - /> -
-
- handleChangeEndDate(newValue)} - renderInput={(params) => } - /> -
-
- } -
- { - setLoader(true) - getDiscretization(unity, startDate, endDate, discretization) - .then(result => { setDiscretizedConsumptionData(result); setSend(false); setLoader(false); setTableData(result) }) - .catch(exception => { setSend(false); setOpenSnackFields(true); setLoader(false) }) - }} /> -
-
- value.minut)} dataset={'Consumo'} dataset1='Estimado' month /> -
- - {/* demand chart */} - - -
- - Unidade - - -
-
- - Discretização - - -
- -
- } - /> -
-
- handleChangeEndDate(newValue)} - renderInput={(params) => } - /> -
-
-
- { - setLoader(true) - getDemand(unity, startDate, endDate, discretization) - .then(result => { setDemRegXDemCon(result); setSend(false); setLoader(false); setTableData(result) }) - .catch(exception => { setSend(false); setOpenSnackFields(true); setLoader(false) }) - }} /> -
-
- value.hora)} title='Demanda Contratada X Registrada' subtitle='' red /> -
- - {/* power factor chart */} - - -
- - Unidade - - -
-
- - Discretização - - -
- -
- } - /> -
-
- handleChangeEndDate(newValue)} - renderInput={(params) => } - /> -
-
-
- { - setLoader(true) - getPowerFactorData(unity, startDate, endDate, discretization) - .then(result => { setFatorPotenciaData(result); setSend(false); setLoader(false); setTableData(result) }) - .catch(exception => { setSend(false); setOpenSnackFields(true); setLoader(false) }) - }} /> -
-
- (value.day_formatted))} /> -
-
- - -
-
- - - - - -
-
-
- - - - - - - - - - - - - - - - - - - - - { - fatorPotenciaData !== null ? - fatorPotenciaData?.map((value, index) => { - return <> - - - - - - - - - - - - - - - - - }) - : - null + + setMenu(nv)} aria-label=""> + -
UnidadePontoNumero do diaDia formatadoHoraMinutof_refConsumoReativafpdem contratadadem registradadem tolerancia
{unity}{value?.ponto}{parseFloat(value?.dia_num)}{value?.day_formatted}{value?.hora}{value.minut}{value?.f_ref}{parseFloat(value?.consumo).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2 })}{parseFloat(value?.reativa).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2 })}{parseFloat(value?.fp)}{value?.dem_cont}{value?.dem_reg}{value?.dem_tolerancia}
+ /> + - - value.hora)} title='Demanda Contratada X Registrada' subtitle='' red /> - + + + - - {/* setShowChart(!showChart)} purple /> */} - {/* handleVerifyFields()} orange /> */} - { - const html = document.querySelector("table")?.outerHTML; - htmlToCSV(html, `${menu === 2 ? 'fator_potencia' : menu === 1 ? 'demanda' : 'consumo_discretizado'}.csv`); - }} /> - -

- - Fonte: Dados coletados do Sistema de Coleta de Dados - de Energia - SCDE da Câmara de Comercialização
- Energia Elétrica – CCEE, sendo que as quantidades aqui - informadas são de responsabilidade
do agente de - medição - Distribuidora. -
-

-
- } + {/* discretization chart */} + + +
+ + Unidade + + +
+
+ + Discretização + + +
+ + {discretization === '1_mes' ? ( + <> + + Discretização + + + {discretization === '1_mes' && ( + + Discretização + + + )} + + ) : ( + +
+ ( + + )} + /> +
+
+ + handleChangeEndDate(newValue) + } + renderInput={(params) => ( + + )} + /> +
+
+ )} +
+ { + setLoader(true) + getDiscretization(unity, startDate, endDate, discretization) + .then((result) => { + setDiscretizedConsumptionData(result) + setSend(false) + setLoader(false) + setTableData(result) + }) + .catch((exception) => { + setSend(false) + setOpenSnackFields(true) + setLoader(false) + }) + }} + /> +
+
+ + value.minut)} + dataset={'Consumo'} + dataset1="Estimado" + month + /> +
+ + {/* demand chart */} + + +
+ + Unidade + + +
+
+ + Discretização + + +
+ +
+ ( + + )} + /> +
+
+ handleChangeEndDate(newValue)} + renderInput={(params) => ( + + )} + /> +
+
+
+ { + setLoader(true) + getDemand(unity, startDate, endDate, discretization) + .then((result) => { + setDemRegXDemCon(result) + setSend(false) + setLoader(false) + setTableData(result) + }) + .catch((exception) => { + setSend(false) + setOpenSnackFields(true) + setLoader(false) + }) + }} + /> +
+
+ value.hora)} + title="Demanda Contratada X Registrada" + subtitle="" + red + /> +
+ + {/* power factor chart */} + + +
+ + Unidade + + +
+
+ + Discretização + + +
+ +
+ ( + + )} + /> +
+
+ handleChangeEndDate(newValue)} + renderInput={(params) => ( + + )} + /> +
+
+
+ { + setLoader(true) + getPowerFactorData( + unity, + startDate, + endDate, + discretization + ) + .then((result) => { + setFatorPotenciaData(result) + setSend(false) + setLoader(false) + setTableData(result) + }) + .catch((exception) => { + setSend(false) + setOpenSnackFields(true) + setLoader(false) + }) + }} + /> +
+
+ value.day_formatted)} + /> +
+ + +
+
+ + + + + +
+
+
+ + + + + + + + + + + + + + + + + + + + + {fatorPotenciaData !== null + ? fatorPotenciaData?.map((value, index) => { + return ( + + + + + + + + + + + + + + + + ) + }) + : null} + +
UnidadePontoNumero do diaDia formatadoHoraMinutof_refConsumoReativafpdem contratadadem registradadem tolerancia
{unity}{value?.ponto} + {parseFloat(value?.dia_num)} + {value?.day_formatted}{value?.hora}{value.minut}{value?.f_ref} + {parseFloat(value?.consumo).toLocaleString('pt-br', { + style: 'currency', + currency: 'BRL', + minimumFractionDigits: 2 + })} + + {parseFloat(value?.reativa).toLocaleString('pt-br', { + style: 'currency', + currency: 'BRL', + minimumFractionDigits: 2 + })} + {parseFloat(value?.fp)}{value?.dem_cont}{value?.dem_reg}{value?.dem_tolerancia}
+ + + value.hora)} + title="Demanda Contratada X Registrada" + subtitle="" + red + /> + + + + {/* setShowChart(!showChart)} purple /> */} + {/* handleVerifyFields()} orange /> */} + { + htmlToCSV( + `${menu === 2 + ? 'fator_potencia' + : menu === 1 + ? 'demanda' + : 'consumo_discretizado' + }.csv` + ) + }} + /> + + +

+ + Fonte: Dados coletados do Sistema de Coleta de Dados de Energia - + SCDE da Câmara de Comercialização
+ Energia Elétrica – CCEE, sendo que as quantidades aqui informadas + são de responsabilidade
+ do agente de medição - Distribuidora. +
+

+ + )} ) } @@ -662,22 +901,26 @@ export const getServerSideProps: GetServerSideProps = async (ctx) => { let clients = [] - await apiClient.post('/units', { - "filters": [ - { "type": "=", "field": "dados_cadastrais.cod_smart_cliente", "value": client_id }, - { "type": "not_in", "field": "dados_cadastrais.codigo_scde", "value": ["0P"] } - ], - "fields": [ - "unidade", - "cod_smart_unidade", - "codigo_scde"], - "distinct": true - }).then(res => { - console.log(res.data) - clients = res.data.data - }).catch(res => { - // console.log(res) - }) + await apiClient + .post('/units', { + filters: [ + { + type: '=', + field: 'dados_cadastrais.cod_smart_cliente', + value: client_id + }, + { type: 'not_in', field: 'dados_cadastrais.codigo_scde', value: ['0P'] } + ], + fields: ['unidade', 'cod_smart_unidade', 'codigo_scde'], + distinct: true + }) + .then((res) => { + console.log(res.data) + clients = res.data.data + }) + .catch((res) => { + // console.log(res) + }) if (!token) { return { @@ -695,4 +938,3 @@ export const getServerSideProps: GetServerSideProps = async (ctx) => { } } } -