diff --git a/public/assets/smart-energia-terms-image.png b/public/assets/smart-energia-terms-image.png new file mode 100644 index 0000000..ffbc8f6 Binary files /dev/null and b/public/assets/smart-energia-terms-image.png differ diff --git a/src/components/administrativeTables/ClientsTable.tsx b/src/components/administrativeTables/ClientsTable.tsx index 90ccfaf..259bdb2 100644 --- a/src/components/administrativeTables/ClientsTable.tsx +++ b/src/components/administrativeTables/ClientsTable.tsx @@ -10,16 +10,23 @@ import TablePagination from '@mui/material/TablePagination'; import TableRow from '@mui/material/TableRow'; import TableSortLabel from '@mui/material/TableSortLabel'; import { visuallyHidden } from '@mui/utils'; -import React, { useState, useEffect } from 'react'; +import React, { useEffect, useState } from 'react'; + +import Image from 'next/image'; -import Snackbar from '@mui/material/Snackbar'; import MuiAlert, { AlertProps } from '@mui/material/Alert'; +import Snackbar from '@mui/material/Snackbar'; import Modal from '@mui/material/Modal'; +import { FormControl, InputLabel, MenuItem, Select, TextField, Typography } from '@mui/material'; +import FormData from 'form-data'; +import { InputUploadView } from '../inputUploadImg/inputUploadView'; -import { TableView, StyledStatus } from './TableView'; import { api } from '../../services/api'; +import FaqButton1 from '../buttons/faqButton/FaqButton1'; +import FaqButton2 from '../buttons/faqButton/FaqButton2'; +import { StyledStatus, TableView } from './TableView'; const style = { position: 'absolute' as const, @@ -100,19 +107,19 @@ const headCells: readonly HeadCell[] = [ }, { id: 'name', - numeric: true, + numeric: false, disablePadding: false, label: 'name', }, { id: 'unity', - numeric: true, + numeric: false, disablePadding: false, label: 'unity', }, { id: 'status', - numeric: true, + numeric: false, disablePadding: false, label: 'status', }, @@ -180,9 +187,9 @@ interface ClientsTableInterface { onChange: any } -export default function ClientTable({clients, onChange}: ClientsTableInterface) { +export default function ClientTable({ clients, onChange }: ClientsTableInterface) { const [order, setOrder] = useState('asc'); - const [orderBy, setOrderBy] = useState('status'); + const [orderBy, setOrderBy] = useState('asc'); const [selected, setSelected] = useState([]); const [page, setPage] = useState(0); const [dense, setDense] = useState(false); @@ -195,13 +202,12 @@ export default function ClientTable({clients, onChange}: ClientsTableInterface) const handleOpen = () => setOpen(true); const handleClose = () => setOpen(false); - const [cod_client, setCod_client] = useState() const [units, setUnits] = useState([]) function getClientUnits(client_id: number) { api.post('/units', { "filters": [ - {"type" : "=", "field": "dados_cadastrais.cod_smart_cliente", "value": client_id} + { "type": "=", "field": "dados_cadastrais.cod_smart_cliente", "value": client_id } ], "fields": ["unidade"], "distinct": true @@ -276,6 +282,60 @@ export default function ClientTable({clients, onChange}: ClientsTableInterface) const emptyRows = page > 0 ? Math.max(0, (1 + page) * rowsPerPage - clients.length) : 0; + const formData = new FormData() + + const [clientEdit, setClientEdit] = useState({}) + const [logo, setLogo] = useState(false) + const [imageURLS, setImageURLs] = useState([]) + const [images, setImages] = useState([] as any) + const [nivelAcess, setnivelAcess] = useState(2); + const [openEditUserModal, setOpenEditUserModal] = useState(false); + + const [selectedClient, setSelectedClient] = useState(2); + const [search, setSearch] = useState('') + + useEffect(() => { + if (images.length < 1) return + const newImageUrls: any = [] + images.forEach((image: any) => + newImageUrls.push(URL.createObjectURL(image)) + ) + setImageURLs(newImageUrls) + }, [images]) + + function onImageChange(e: any) { + setImages([...e.target.files]) + setLogo(e.target.files[0]) + } + + const [openSnackSuccess, setOpenSnackSuccess] = useState(false) + + function handleUpdateClient({ + name, + email, + password, + password_confirmation, + client_id + }, id) { + formData.append('name', name) + formData.append('email', email) + formData.append('password', password) + formData.append('password_confirmation', password_confirmation) + formData.append('client_id', client_id) + formData.append('profile_picture', logo) + formData.append('role', nivelAcess) + + api.put(`/user/${id}`, formData) + .then((res) => { + setOpenSnackSuccess(true) + setOpenModalInativar(false) + // window.location.reload() + }) + .catch((res) => { + setOpenSnackError(true) + }) + } + return ( @@ -283,6 +343,7 @@ export default function ClientTable({clients, onChange}: ClientsTableInterface) Não foi possivel encontrar unidades do client! + setSearch(e.target.value)} placeholder='persquisar por nome:' /> {stableSort(clients, getComparator(order, orderBy)) + .filter(client => client.name.toLowerCase().includes(search.toLowerCase())) .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .map((row, index) => { const isItemSelected = isSelected(row.id); @@ -332,12 +394,17 @@ export default function ClientTable({clients, onChange}: ClientsTableInterface) > Client - {row.client_id} - {row.name} - { + { + setOpenEditUserModal(true) + setSelectedClient(row) + setClientEdit(row) + }}>{row.name} + { setOpen(true) getClientUnits(row.client_id) + setSelectedClient(row) }}>clique aqui para ver as unidades - {row.deleted_at? 'inativo' : 'ativo'} + {row.deleted_at ? 'inativo' : 'ativo'} ); })} @@ -363,20 +430,157 @@ export default function ClientTable({clients, onChange}: ClientsTableInterface) onRowsPerPageChange={handleChangeRowsPerPage} /> + setOpenEditUserModal(false)} + aria-labelledby="modal-modal-title" + aria-describedby="modal-modal-description" + > + +

Editar Cliente - {selectedClient.name}

+ + Adicionar Cliente Smart Energia + +
+ { + setClientEdit({ + ...clientEdit, + name: value.target.value + }) + }} + variant="outlined" + /> + { + setClientEdit({ + ...clientEdit, + email: value.target.value.toLowerCase() + }) + }} + variant="outlined" + /> + { + setClientEdit({ + ...clientEdit, + password: value.target.value + }) + }} + variant="outlined" + /> + { + setClientEdit({ + ...clientEdit, + password_confirmation: value.target.value + }) + }} + variant="outlined" + /> + { + setClientEdit({ + ...clientEdit, + client_id: value.target.value + }) + }} + variant="outlined" + /> + +
+
+ {imageURLS.map((imageSrc, index) => { + return + })} +
+
+
+
+
+ + +
+ +
+
+ +
+ + + Nivel de acesso + + +
+ + setOpenEditUserModal(false)} /> + handleUpdateClient(clientEdit, selectedClient.id)} + /> +
+
+ + > { units.map((units, index) => { return <>
  • {units.unidade}
  • -
    + listStyle: 'none' + }} key={index}>{units.unidade} +
    }) } diff --git a/src/components/graph/costIndicatorChart/index.tsx b/src/components/graph/costIndicatorChart/index.tsx index e3937fe..b850fe5 100644 --- a/src/components/graph/costIndicatorChart/index.tsx +++ b/src/components/graph/costIndicatorChart/index.tsx @@ -1,21 +1,20 @@ -import React from 'react' -import { draw } from 'patternomaly' +import { draw } from 'patternomaly'; -import { Bar } from 'react-chartjs-2'; import { - Chart as ChartJS, - CategoryScale, - LinearScale, BarElement, + CategoryScale, + Chart as ChartJS, + Legend, + LinearScale, Title, - Tooltip, - Legend -} from 'chart.js' + Tooltip +} from 'chart.js'; +import { Bar } from 'react-chartjs-2'; -import { CostIndicatorChartView } from './CostIndicatorChartView'; import ChartTitle from '../ChartTitle'; import { config } from '../config'; +import { CostIndicatorChartView } from './CostIndicatorChartView'; ChartJS.register( CategoryScale, @@ -34,19 +33,22 @@ interface ChartInterface { single?: any label: any, miniature?: boolean | undefined + years?: string[] } -export default function CostIndicatorChart({ title, data1, data2, label, subtitle, miniature }: ChartInterface) { +export default function CostIndicatorChart({ title, data1, data2, label, subtitle, miniature, years }: ChartInterface) { const labels = label; const options: any = config(miniature) + console.log(new Date().getFullYear()) + const data = { labels, datasets: [ { - label: '2021', + label: years[0], data: data1?.map(value => value), skipNull: data2?.map(value => value)?.includes(null), borderRadius: 8, @@ -64,7 +66,7 @@ export default function CostIndicatorChart({ title, data1, data2, label, subtitl }, }, { - label: '2022', + label: years[1], data: data2?.map(value => value), skipNull: data1?.map(value => value)?.includes(null), borderRadius: 8, diff --git a/src/components/graph/grossAnualChart/GrossAnualChart.tsx b/src/components/graph/grossAnualChart/GrossAnualChart.tsx index 09f058e..e029ed0 100644 --- a/src/components/graph/grossAnualChart/GrossAnualChart.tsx +++ b/src/components/graph/grossAnualChart/GrossAnualChart.tsx @@ -1,12 +1,11 @@ import { BarElement, CategoryScale, Chart as ChartJS, Legend, LinearScale, Title, Tooltip } from 'chart.js'; import ChartDataLabels from 'chartjs-plugin-datalabels'; -import { draw } from 'patternomaly' -import React, { useEffect } from 'react'; -import { Chart } from 'react-chartjs-2'; import 'chartjs-plugin-style'; +import { draw } from 'patternomaly'; +import { Chart } from 'react-chartjs-2'; -import { GrossAnualChartView } from './GrossAnualChartView'; import ChartTitle from '../ChartTitle'; +import { GrossAnualChartView } from './GrossAnualChartView'; ChartJS.register( CategoryScale, @@ -18,7 +17,7 @@ ChartJS.register( ChartDataLabels, ); -interface SingleBarInterface{ +interface SingleBarInterface { title: string, subtitle: string, dataProps: any, @@ -29,9 +28,9 @@ interface SingleBarInterface{ bruta?: boolean | undefined } -export function GrossAnualChart({ title, subtitle, dataProps=[], label, dataset, barLabel, miniature, bruta }: SingleBarInterface) { +export function GrossAnualChart({ title, subtitle, dataProps = [], label, dataset, barLabel, miniature, bruta }: SingleBarInterface) { function spacement(string) { - const spaces = string.length===1?'' : string.length===2? '' : string.length===3? ' ' : string.length===4? ' ' : string.length===5? ' ' : '' + const spaces = string.length === 1 ? '' : string.length === 2 ? '' : string.length === 3 ? ' ' : string.length === 4 ? ' ' : string.length === 5 ? ' ' : '' return spaces } @@ -46,20 +45,20 @@ export function GrossAnualChart({ title, subtitle, dataProps=[], label, dataset, }, ticks: { font: { - size: !miniature? window.innerWidth/90 : window.innerWidth/125 + size: !miniature ? window.innerWidth / 90 : window.innerWidth / 125 } }, }, y: { stacked: false, - max: Number.parseInt(dataProps.reduce((prev, current) => prev.economia_acumulada < current.economia_acumulada ? prev.economia_acumulada : current.economia_acumulada,0)) + 350, + max: Number.parseInt(dataProps.reduce((prev, current) => prev.economia_acumulada < current.economia_acumulada ? prev.economia_acumulada : current.economia_acumulada, 0)) + 350, min: 0, grid: { display: false }, ticks: { font: { - size: !miniature? window.innerWidth/90 : window.innerWidth/125 + size: !miniature ? window.innerWidth / 90 : window.innerWidth / 125 } }, }, @@ -78,22 +77,22 @@ export function GrossAnualChart({ title, subtitle, dataProps=[], label, dataset, let sum = 0; const dataArr = ctx.chart.data.datasets[0].data; dataArr.map(data => { - sum += data; + sum += data; }); - const percentage = (dataProps[ctx.dataIndex]?.econ_percentual*100).toFixed(0)+"%"; + const percentage = (dataProps[ctx.dataIndex]?.econ_percentual * 100).toFixed(0) + "%"; const result = `${spacement(parseInt(value).toLocaleString('pt-br'))}${percentage}\n${parseInt(value).toLocaleString('pt-br')}${spacement(parseInt(value).toLocaleString('pt-br'))}` - return value==null? null : result + return value == null ? null : result }, display: true, anchor: "end", align: "end", font: { weight: 'bold', - size: !miniature? window.innerWidth/80 : window.innerWidth/125, + size: !miniature ? window.innerWidth / 80 : window.innerWidth / 125, }, color: (value) => { - return value.dataset.label==='Consolidada'? '#fff' : '#255488' + return value.dataset.label === 'Consolidada' ? '#fff' : '#255488' }, }, legend: { @@ -106,8 +105,8 @@ export function GrossAnualChart({ title, subtitle, dataProps=[], label, dataset, }, }; - const labels: string[] = label.filter(function(item, pos) { - return label.indexOf(item) == pos; + const labels: string[] = label.filter((item, pos) => { + return label.indexOf(item) == pos; }); const data: any = { @@ -141,11 +140,8 @@ export function GrossAnualChart({ title, subtitle, dataProps=[], label, dataset, return 0 }) }, - data: [null].concat(dataProps.filter(value => value.dad_estimado === true).map((value, index) => { - if (value.dad_estimado) - return parseFloat(value.economia_acumulada) - else - return 0 + data: [].concat(dataProps.filter(value => value.dad_estimado === true).slice(0, 7).map((value, index) => { + return parseFloat(value?.economia_acumulada) })), borderRadius: 10, backgroundColor: draw('diagonal-right-left', '#C2d5fb'), @@ -156,7 +152,7 @@ export function GrossAnualChart({ title, subtitle, dataProps=[], label, dataset, return ( - + ) } diff --git a/src/components/graph/grossMensalChart/GrossMensalChart.tsx b/src/components/graph/grossMensalChart/GrossMensalChart.tsx index d49c9b4..cd348de 100644 --- a/src/components/graph/grossMensalChart/GrossMensalChart.tsx +++ b/src/components/graph/grossMensalChart/GrossMensalChart.tsx @@ -1,65 +1,120 @@ -import React, { useEffect, useState } from 'react' +import { useEffect, useState } from 'react' -import { Bar, Line, Chart as ChartJs } from 'react-chartjs-2'; import { - Chart as ChartJS, - CategoryScale, - LinearScale, - BarElement, - Title, - Tooltip, - Legend + BarElement, CategoryScale, Chart as ChartJS, Legend, LinearScale, Title, + Tooltip } from 'chart.js' +import { Chart as ChartJs } from 'react-chartjs-2' -import document from 'next/document'; -import { draw, generate } from 'patternomaly' +import { draw } from 'patternomaly' -import { GrossMensalChartView } from './GrossMensalChartView'; -import ChartTitle from '../ChartTitle'; -import { config } from '../config'; +import ChartTitle from '../ChartTitle' +import { GrossMensalChartView } from './GrossMensalChartView' // import { data } from './LineBarChart'; -ChartJS.register( - CategoryScale, - LinearScale, - BarElement, - Title, - Tooltip, - Legend -) +ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend) interface ChartInterface { - title: string, - subtitle: string, + title: string + subtitle: string - data1: any, - data2: any, + data1: any + data2: any single?: any - label: any, + label: any miniature?: boolean | undefined } -export default function GrossMensalChart({ title, data1, data2, label, subtitle, miniature }: ChartInterface) { - function spacement(string) { - const spaces = string.length===1?'' : string.length===2? '' : string.length===3? ' ' : string.length===4? ' ' : string.length===5? ' ' : '' - return spaces - } - +export default function GrossMensalChart({ + title, + data1, + data2, + label, + subtitle, + miniature +}: ChartInterface) { const [lastDataS, setLastData] = useState('') useEffect(() => { let lastData = '0' - let index=0 + let index = 0 while (index < data1.length) { - data1[index].dad_estimado? lastData=data1[index].economia_acumulada : null + data1[index].dad_estimado + ? (lastData = data1[index].economia_acumulada) + : null index++ - setLastData(`economia acumulada: R$ ${parseFloat(lastData).toLocaleString('pt-br', {minimumFractionDigits: 2})}`) + setLastData( + `economia acumulada: R$ ${parseFloat(lastData).toLocaleString('pt-br', { + minimumFractionDigits: 2 + })}` + ) } }, [data1]) - const options: any = config(miniature) + const options: any = { + responsive: true, + scales: { + x: { + stacked: true, + grid: { + display: false + }, + ticks: { + font: { + size: !miniature ? window.innerWidth / 90 : window.innerWidth / 125 + } + } + }, + y: { + stacked: true, + grid: { + display: false + }, + ticks: { + font: { + size: !miniature ? window.innerWidth / 90 : window.innerWidth / 125 + } + } + } + }, + plugins: { + datalabels: { + display: true, + color: '#255488', + formatter: (value, ctx) => { + let sum = 0 + const dataArr = ctx.chart.data.datasets[0].data + const percentage = + (data1[ctx?.dataIndex]?.econ_percentual * 100).toFixed(0) + '%' + + console.log(percentage) + dataArr.map((data) => { + sum += data + }) + const result = `${percentage}\n${parseFloat( + parseFloat(value).toLocaleString('pt-br') + )}` + + return value == null ? null : result + }, + anchor: 'end', + align: 'end', + font: { + weight: 'bold', + size: !miniature ? window.innerWidth / 80 : window.innerWidth / 125 + } + }, + legend: { + position: 'bottom' as const + }, + title: { + display: true, + text: '' + } + } + } const data: any = { labels: label, @@ -67,7 +122,9 @@ export default function GrossMensalChart({ title, data1, data2, label, subtitle, { type: 'bar', label: 'Consolidado', - data: data1.map(value => !value.dad_estimado? value?.economia_acumulada : null), + data: data1.map((value) => + !value.dad_estimado ? value?.economia_acumulada : null + ), skipNull: true, borderRadius: 8, backgroundColor: '#255488', @@ -76,21 +133,21 @@ export default function GrossMensalChart({ title, data1, data2, label, subtitle, { type: 'bar', label: 'Estimado', - data: data2.map(value => value.dad_estimado? value?.economia_acumulada : null), + data: data2.map((value) => + value.dad_estimado ? value?.economia_acumulada : null + ), skipNull: true, borderRadius: 8, backgroundColor: draw('diagonal-right-left', '#C2d5fb'), stack: '0' - }, - ], + } + ] } return ( - + ) } diff --git a/src/pages/administrative/clients/index.tsx b/src/pages/administrative/clients/index.tsx index c4c7da5..aaeb309 100644 --- a/src/pages/administrative/clients/index.tsx +++ b/src/pages/administrative/clients/index.tsx @@ -1,29 +1,29 @@ +import MuiAlert, { AlertProps } from '@mui/material/Alert' import Box from '@mui/material/Box' import Modal from '@mui/material/Modal' +import Snackbar from '@mui/material/Snackbar' import TextField from '@mui/material/TextField' import Typography from '@mui/material/Typography' -import React, { useState, useEffect } from 'react' import Image from 'next/image' -import Snackbar from '@mui/material/Snackbar' -import MuiAlert, { AlertProps } from '@mui/material/Alert' +import React, { useEffect, useState } from 'react' import ClientsTable from '../../../components/administrativeTables/ClientsTable' import BasicButton from '../../../components/buttons/basicButton/BasicButton' import FaqButton1 from '../../../components/buttons/faqButton/FaqButton1' import FaqButton2 from '../../../components/buttons/faqButton/FaqButton2' import Header from '../../../components/header/Header' -import { ClientsView } from '../../../styles/layouts/clients/ClientsView' -import PageTitle from '../../../components/pageTitle/PageTitle' -import ConfirmModal from '../../../components/modal/ConfirmModal' -import { ConfirmModalView } from '../../../styles/layouts/modals/confirmModalView' -import { api } from '../../../services/api' -import { parseCookies } from 'nookies' import { GetServerSideProps } from 'next' +import { parseCookies } from 'nookies' +import ConfirmModal from '../../../components/modal/ConfirmModal' +import PageTitle from '../../../components/pageTitle/PageTitle' +import { api } from '../../../services/api' import getAPIClient from '../../../services/ssrApi' +import { ClientsView } from '../../../styles/layouts/clients/ClientsView' +import { ConfirmModalView } from '../../../styles/layouts/modals/confirmModalView' +import { FormControl, InputLabel, MenuItem, Select } from '@mui/material' import FormData from 'form-data' import { InputUploadView } from '../../../components/inputUploadImg/inputUploadView' -import { FormControl, InputLabel, MenuItem, Select } from '@mui/material' const style = { position: 'absolute' as const, @@ -70,6 +70,7 @@ export default function clients({ clients, userName }) { const [nivelAcess, setnivelAcess] = useState(2); const [openSnackSuccess, setOpenSnackSuccess] = useState(false) const [openSnackError, setOpenSnackError] = useState(false) + const [openSnackWarning, setOpenSnackWarning] = useState(false) const [openSnackSuccessDelete, setOpenSnackSuccessDelete] = useState(false) const [openSnackErrorDelete, setOpenSnackErrorDelete] = @@ -114,6 +115,9 @@ export default function clients({ clients, userName }) { formData.append('profile_picture', logo) formData.append('role', nivelAcess) + if (!name.length || !email.length || !password.length || !password_confirmation.length || !client_id.length || !logo || !nivelAcess.length) + setOpenSnackWarning(true) + api.post('/user', formData) .then((res) => { setOpenSnackSuccess(true) @@ -152,6 +156,7 @@ export default function clients({ clients, userName }) { setLogo(e.target.files[0]) } + return (
    + + + Preencha todos os campos! + + -
    - - Nivel de acesso - setnivelAcess(value.target.value)} + fullWidth + > + Administrador + Cliente - - -
    + + +
    setOpen(false)} /> { let lastDataMensal = '0' let lastDataAnual = '0' - let index=0 + let index = 0 while (index < grossMensalGraph.length) { - if (!grossMensalGraph[index].dad_estimado && grossMensalGraph[index].economia_acumulada!==null) - lastDataMensal=grossMensalGraph[index].economia_acumulada + if (!grossMensalGraph[index].dad_estimado && grossMensalGraph[index].economia_acumulada !== null) + lastDataMensal = grossMensalGraph[index].economia_acumulada index++ } setLastDataBrutaMensal(`${parseFloat(lastDataMensal).toFixed(3)}`) - index=0 + index = 0 while (index < grossAnualGraph.length) { if (!grossAnualGraph[index].dad_estimado) - lastDataAnual=grossAnualGraph[index].economia_acumulada + lastDataAnual = grossAnualGraph[index].economia_acumulada index++ } setLastDataBrutaAnual(`${parseFloat(lastDataAnual).toFixed(3)}`) @@ -108,75 +110,114 @@ export default function Dashboard({grossAnualGraph, grossAnualYears, grossMensal { - typeof window === 'undefined' || typeof window === undefined? null : - <> -
    - - - - + typeof window === 'undefined' || typeof window === undefined ? null : + <> +
    + + + + - - - - + + + + - - - + + + - - value?.mes.slice(0, 4).includes('2021')).map(value => value?.custo_unit && !!parseInt(value?.custo_unit)? value.custo_unit : null)} - data2={costIndicator?.filter((value, index) => value?.mes.slice(0, 4).includes('2022')).map(value => value?.custo_unit && !!parseInt(value?.custo_unit)? value.custo_unit : null)} - label={months} - miniature - /> - -
    - - - - Termos de uso - - -

    - Bem-vindo a Plataforma Web – SMART ENERGIA! -

    -

    - Visualize os principais indicadores, dados de economia, resumo de operações, PLD, notícias além de acompanhar o consumo de energia em intervalos mínimos de 5 minutos. -

    -

    - Conforme nosso contrato de serviços vigente, todas as informações entregues são estritamente privadas, sendo seu sigilo protegido por lei, não podendo ser compartilhadas com terceiros. -

    -

    - A divulgação não autorizada das informações adquiridas nesta plataforma (ou seu uso), de forma integral ou parcial, é proibida, não sendo permitido o compartilhamento dos acessos e senhas ou qualquer informação que tiver acesso junto a esta plataforma, sendo que o acesso a esta plataforma é restrito e individual. -

    -

    - Ressaltamos que os resultados informados são meramente indicativos. -

    - { - setCookie(undefined, 'terms', 'true') - setOpen(false) - }} /> -
    -
    -
    - + + value?.mes.slice(0, 4).includes(costIndicator[0].mes.slice(0, 4))).map(value => value?.custo_unit && !!parseInt(value?.custo_unit) ? value.custo_unit : null)} + data2={costIndicator?.filter((value, index) => value?.mes.slice(0, 4).includes(costIndicator[costIndicator.length - 1].mes.slice(0, 4))).map(value => value?.custo_unit && !!parseInt(value?.custo_unit) ? value.custo_unit : null)} + // years={[costIndicator[0].mes.slice(0, 4), costIndicator[costIndicator.length - 1].mes.slice(0, 4)]} + years={[previousYear, currentYear]} + label={months} + miniature + /> + +
    + + + + Termos de uso + + + +

    + Bem-vindo ao Smart Energy View, a Plataforma Web da SMART ENERGIA! +

    + +

    + Agora você terá a Gestão da sua Energia na palma da sua mão!!!! +

    + +

    + Visualize os principais indicadores, dados de economia, resumo de operações, PLD, notícias além de acompanhar o consumo de energia em intervalos mínimos de 5 minutos. +

    + +

    + Estamos na última fase de testes da plataforma e em breve também iremos disponibilizar os aplicativos para seu celular, nos sistemas operacionais IOS e Android. +

    + +

    + Encontrando qualquer dificuldade, eventuais inconsistências ou dúvidas, nos contate! +

    + +

    + Lembrando que conforme nosso contrato de serviços vigente, todas as informações entregues são estritamente privadas, sendo seu sigilo protegido por lei, não podendo ser compartilhadas com terceiros sendo destinadas a seu uso exclusivo. +

    + +

    + A divulgação não autorizada das informações adquiridas nesta plataforma (ou seu uso), de forma integral ou parcial, é proibida, não sendo permitido o compartilhamento dos acessos e senhas ou qualquer informação que tiver acesso junto a esta plataforma, sendo que o acesso a esta plataforma é restrito e individual. +

    + +

    + Destacamos que os resultados informados são meramente indicativos, não vinculantes a resultados e que as premissas disponibilizadas na plataforma são as mesmas utilizadas nos Energys Reports e estudos encaminhados. +

    + + +

    + Aproveite essa nova ferramenta de acompanhar sua Gestão de Energia! +

    + {/*

    + Bem-vindo a Plataforma Web – SMART ENERGIA! +

    +

    + Visualize os principais indicadores, dados de economia, resumo de operações, PLD, notícias além de acompanhar o consumo de energia em intervalos mínimos de 5 minutos. +

    +

    + Conforme nosso contrato de serviços vigente, todas as informações entregues são estritamente privadas, sendo seu sigilo protegido por lei, não podendo ser compartilhadas com terceiros. +

    +

    + A divulgação não autorizada das informações adquiridas nesta plataforma (ou seu uso), de forma integral ou parcial, é proibida, não sendo permitido o compartilhamento dos acessos e senhas ou qualquer informação que tiver acesso junto a esta plataforma, sendo que o acesso a esta plataforma é restrito e individual. +

    +

    + Ressaltamos que os resultados informados são meramente indicativos. +

    */} + { + setCookie(undefined, 'terms', 'true') + setOpen(false) + }} /> +
    +
    +
    + } ) @@ -195,9 +236,9 @@ export const getServerSideProps: GetServerSideProps = async (ctx) => { await apiClient.post('/economy/grossAnnual').then(res => { grossAnualGraph = res.data.data - }).catch(res => { - // console.log(res) }) + .then(console.log) + .catch(console.log) await apiClient.post('/economy/grossMonthly').then(res => { grossMensalGraph = res.data.data diff --git a/src/pages/economy/index.tsx b/src/pages/economy/index.tsx index 5079f7a..0c8743a 100644 --- a/src/pages/economy/index.tsx +++ b/src/pages/economy/index.tsx @@ -5,28 +5,28 @@ import Select from '@mui/material/Select'; import { GetServerSideProps } from 'next'; import Head from 'next/head'; import { parseCookies } from 'nookies'; -import React, { useContext, useEffect, useState } from 'react' +import { useContext, useEffect, useState } from 'react'; -import Header from '../../components/header/Header' +import Header from '../../components/header/Header'; import PageTitle from '../../components/pageTitle/PageTitle'; import { api } from '../../services/api'; import getAPIClient from '../../services/ssrApi'; -import { TableHeader } from '../../styles/layouts/pld/PldView' -import RenderIf from '../../utils/renderIf' +import { TableHeader } from '../../styles/layouts/pld/PldView'; +import RenderIf from '../../utils/renderIf'; -import Tabs from '@mui/material/Tabs'; import Tab from '@mui/material/Tab'; +import Tabs from '@mui/material/Tabs'; -import { MenuContext } from '../../contexts/menu/MenuContext'; -import { GrossAnualChart } from '../../components/graph/grossAnualChart/GrossAnualChart'; -import GrossMensalChart from '../../components/graph/grossMensalChart/GrossMensalChart'; +import AccumulatedEconomyTitle from '../../components/accumulatedEconomyTitle/AccumulatedEconomyTitle'; import { CativoXLivreChart } from '../../components/graph/cativoXLivreChart'; import CostIndicatorChart from '../../components/graph/costIndicatorChart'; +import { GrossAnualChart } from '../../components/graph/grossAnualChart/GrossAnualChart'; +import GrossMensalChart from '../../components/graph/grossMensalChart/GrossMensalChart'; +import { MenuContext } from '../../contexts/menu/MenuContext'; import { EconomyView } from '../../styles/layouts/economy/economy'; -import AccumulatedEconomyTitle from '../../components/accumulatedEconomyTitle/AccumulatedEconomyTitle'; -export default function economy({userName, anual, years, brutaMensal, catLiv, clients, indicatorCost}: any) { - const {economyMenu, setEconomyMenu} = useContext(MenuContext) +export default function economy({ userName, anual, years, brutaMensal, catLiv, clients, indicatorCost }: any) { + const { economyMenu, setEconomyMenu } = useContext(MenuContext) const [unity, setUnity] = useState(''); @@ -34,7 +34,7 @@ export default function economy({userName, anual, years, brutaMensal, catLiv, cl const [indicatorDataState, setIndicatorDataState] = useState(null); const currentYear = new Date().getUTCFullYear() - const previousYear = new Date().getUTCFullYear()-1 + const previousYear = new Date().getUTCFullYear() - 1 const months = [ 'Jan', @@ -54,37 +54,40 @@ export default function economy({userName, anual, years, brutaMensal, catLiv, cl const [lastDataBruta, setLastDataBruta] = useState('') useEffect(() => { let lastData = '0' - let index=0 + let index = 0 if (economyMenu) { while (index < brutaMensal.length) { if (!brutaMensal[index].dad_estimado) - lastData=brutaMensal[index].economia_acumulada + lastData = brutaMensal[index].economia_acumulada index++ } } else { while (index < anual.length) { if (!anual[index].dad_estimado) - lastData=anual[index].economia_acumulada + lastData = anual[index].economia_acumulada index++ } } setLastDataBruta(`${parseFloat(lastData).toFixed(3)}`) }, [economyMenu]) + useEffect(() => { + console.log(indicatorDataState) + }, [indicatorDataState]) async function getChartsWithUnity() { - await api.post('/economy/estimates', unity!==''?{ + await api.post('/economy/estimates', unity !== '' ? { "filters": [ - {"type" : "=", "field":"dados_cadastrais.cod_smart_unidade", "value": unity === "default" ? unity : unity} + { "type": "=", "field": "dados_cadastrais.cod_smart_unidade", "value": unity === "default" ? unity : unity } ] - }:{}).then(res => { + } : {}).then(res => { setCatLivDataState(res.data.data) }) - await api.post('/economy/MWh', unity!==''?{ + await api.post('/economy/MWh', unity !== '' ? { "filters": [ - {"type" : "=", "field":"dados_cadastrais.cod_smart_unidade", "value": unity === "default"? unity : unity} + { "type": "=", "field": "dados_cadastrais.cod_smart_unidade", "value": unity === "default" ? unity : unity } ] - }:{}).then(res => { + } : {}).then(res => { setIndicatorDataState(res.data.data) }) } @@ -94,125 +97,126 @@ export default function economy({userName, anual, years, brutaMensal, catLiv, cl }, [unity]) return ( -
    +
    Smart Energia - Economia -
    +
    - +
    setEconomyMenu(nv)} aria-label=""> - - - - + + + +
    { - economyMenu === 0 || economyMenu === 1? -

    Economia Bruta Estimada e Acumulada Anual - Valores em R$ x mil

    - : - economyMenu === 2? -

    Comparativo de Custo Estimado - Valores em R$ x mil

    - : -

    Indicador de Custo - Valores em R$/MWh

    + economyMenu === 0 || economyMenu === 1 ? +

    Economia Bruta Estimada e Acumulada Anual - Valores em R$ x mil

    + : + economyMenu === 2 ? +

    Comparativo de Custo Estimado - Valores em R$ x mil

    + : +

    Indicador de Custo - Valores em R$/MWh

    } { - economyMenu===0 || economyMenu===1? - + economyMenu === 0 || economyMenu === 1 ? + : null }
    { - typeof window === 'undefined' || typeof window === undefined? null : - <> - -
    - + +
    + -
    -
    + dataProps={anual} + label={years} barLabel bruta + /> +
    +
    - -
    - -
    -
    + +
    + +
    +
    - -
    - - Unidade - - -
    -
    - -
    -
    + +
    + + Unidade + + +
    +
    + +
    +
    - -
    - - Unidade - - -
    -
    - value?.mes.slice(0, 4).includes(previousYear)).map(value => value?.custo_unit && !!parseInt(value?.custo_unit)? value.custo_unit : null)} - data2={indicatorDataState?.filter(value => value?.mes.slice(0, 4).includes(currentYear)).map(value => value?.custo_unit && !!parseInt(value?.custo_unit)? value.custo_unit : null)} - label={months} - /> -
    -
    - + +
    + + Unidade + + +
    +
    + value?.mes.slice(0, 4).includes(previousYear)).map(value => value?.custo_unit && !!parseInt(value?.custo_unit) ? value.custo_unit : null)} + data2={indicatorDataState?.filter(value => value?.mes.slice(0, 4).includes(currentYear)).map(value => value?.custo_unit && !!parseInt(value?.custo_unit) ? value.custo_unit : null)} + years={[previousYear, currentYear]} + label={months} + /> +
    +
    + }
    @@ -245,15 +249,15 @@ 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 + "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 => { clients = res.data.data }) diff --git a/src/pages/pld/index.tsx b/src/pages/pld/index.tsx index ff07ed6..5b23015 100644 --- a/src/pages/pld/index.tsx +++ b/src/pages/pld/index.tsx @@ -76,7 +76,7 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) { function getDataByDay() { api.post('/pld/daily', { "filters": [ - {"type" : "=", "field" : "year_month_formatted", "value": month}, + {"type" : "=", "field" : "year_month_formatted", "value": month, "row": true}, {"type" : "=", "field" : "submarket", "value": select} ], "order": [{ "field": "day_calc", "direction": "asc" }] diff --git a/src/pages/telemetria/index.tsx b/src/pages/telemetria/index.tsx index 29800df..7a8e242 100644 --- a/src/pages/telemetria/index.tsx +++ b/src/pages/telemetria/index.tsx @@ -1,39 +1,37 @@ import React, { useEffect, useState } from 'react'; -import Banner from '../../components/banner/Banner'; -import { TelemetriaView, Buttons, TableHeader, ChartFilters} from '../../styles/layouts/Telemetria/TelemetriaView'; -import GradientButton from '../../components/buttons/gradientButton/GradientButton' -import Header from '../../components/header/Header'; -import MenuItem from '@mui/material/MenuItem'; -import InputLabel from '@mui/material/InputLabel'; import FormControl from '@mui/material/FormControl'; -import Select, { SelectChangeEvent } from '@mui/material/Select'; +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 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 { api } from '../../services/api'; -import Snackbar from '@mui/material/Snackbar' -import MuiAlert, { AlertProps } from '@mui/material/Alert' -import getAPIClient from '../../services/ssrApi'; import { DemRegXDemConChart } from '../../components/graph/DemRegXDemConChart'; +import getAPIClient from '../../services/ssrApi'; +import RenderIf from '../../utils/renderIf'; -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 { DesktopDatePicker } from '@mui/x-date-pickers/DesktopDatePicker'; 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 { getDemand } from '../../services/charts/telemetry/getDemand'; -import PageTitle from '../../components/pageTitle/PageTitle'; -import { format } from 'date-fns'; const Alert = React.forwardRef(function Alert( props, @@ -42,18 +40,19 @@ const Alert = React.forwardRef(function Alert( return }) -export default function Telemetria({userName, clients}: any) { - const [unity, setUnity] = useState(clients[0].codigo_scde); +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()+1); + 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 months = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'] const handleCloseSnack = ( event?: React.SyntheticEvent | Event, @@ -75,7 +74,7 @@ export default function Telemetria({userName, clients}: any) { textEncoder = new TextEncoder('windows-1252'); */ - const csv_file = new Blob([csv], {type: "text/csv;charset=utf-8"}); + const csv_file = new Blob([csv], { type: "text/csv;charset=utf-8" }); const download_link = document.createElement("a"); @@ -143,8 +142,8 @@ export default function Telemetria({userName, clients}: any) { setLoader(true) getDiscretization(unity, new Date(firstOfTheMonth), new Date(lastOfTheMonth), discretization) - .then(result => {setDiscretizedConsumptionData(result); setSend(false); setLoader(false)}) - .catch(() => {setSend(false); setOpenSnackFields(true)}) + .then(result => { setDiscretizedConsumptionData(result); setSend(false); setLoader(false) }) + .catch(() => { setSend(false); setOpenSnackFields(true) }) getDemand(unity, startDate, endDate, discretization) .then(result => { @@ -152,15 +151,15 @@ export default function Telemetria({userName, clients}: any) { 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( -
    + return ( +
    Smart Energia - Telemetria @@ -206,109 +205,231 @@ export default function Telemetria({userName, clients}: any) {
    - +
    { - typeof window === 'undefined' || typeof window === undefined? null : - - {/* + {/* */} - - - setMenu(nv)} aria-label=""> - - - - - + + + setMenu(nv)} aria-label=""> + + + + + - {/* discretization chart */} - - -
    - - Unidade - - -
    -
    - - Discretização - - -
    - { - discretization === '1_mes' ? - - Discretização - - - : + {/* 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 + + +
    } + renderInput={(params) => } />
    -
    +
    handleChangeEndDate(newValue)} - renderInput={(params) => } + 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 } -
    - { - 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/> - + +
    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}
    - {/* 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/> -
    + + 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 - } - -
    PontoNumero do diaDia formatadoHoraf_refConsumoReativafp
    {value.ponto}{parseFloat(value.dia_num)}{value.day_formatted}{value.hora}{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)}
    -
    - - - - - - - - - {/* não temos */} - - - - - - - - - { - demRegXDemCon!==null? - demRegXDemCon?.map((value, index) => { - return <> - - - - - - {/* */} - - - - - - - - }) - : - null - } - -
    PontoNumero do diaDia formatadoHoraMinutoConsumoReativadem contratadadem registradadem tolerancia
    {value.ponto}{parseFloat(value.dia_num)}{value.day_formatted}{value.hora}{value.minut}{parseFloat(value.consumo).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2})}{parseFloat(value.reativa).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2})}{value.dem_cont}{value.dem_reg}{value.dem_tolerancia}
    -
    - - - - - - - - - - - - - - - { - discretizedConsumptionData!==null? - discretizedConsumptionData?.map((value, index) => { - return <> - - - - - - - - - - - }) - : - null - } - -
    PontoNumero do diaDia formatadoHoraMinutoConsumoReativa
    {value.ponto}{parseFloat(value.dia_num)}{value.day_formatted}{value.hora}{value.minut}{parseFloat(value.consumo).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2})}{parseFloat(value.reativa).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2})}
    -
    - - - 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. -
    -

    - + + {/* 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. +
    +

    + } ) @@ -706,15 +663,15 @@ 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 + "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 diff --git a/src/services/ssrApi.ts b/src/services/ssrApi.ts index e208249..c70ba4b 100644 --- a/src/services/ssrApi.ts +++ b/src/services/ssrApi.ts @@ -1,5 +1,4 @@ -import axios, { AxiosRequestConfig } from "axios"; -import * as cookie from 'cookie'; +import axios from "axios"; import * as express from 'express'; import * as next from 'next'; import { parseCookies } from "nookies"; @@ -13,7 +12,8 @@ export default function getAPIClient(ctx?: Pick | { const { '@smartAuth-token': token } = parseCookies(ctx) const api = axios.create({ - baseURL: "https://api.energiasmart.com.br/api", + // baseURL: "https://api.energiasmart.com.br/api", + baseURL: "https://api.energiasmart.klupp.com.br/api", }); api.interceptors.request.use(config => {