Correções em algumas páginas de acordo o retorno da api

This commit is contained in:
marcio1002 2024-01-29 15:04:59 -03:00
parent 5c984bb60e
commit c19f3651c5
9 changed files with 263 additions and 227 deletions

View File

@ -58,9 +58,7 @@ export default function Sidebar() {
}, [router.pathname]) }, [router.pathname])
useEffect(() => { useEffect(() => {
api.post('/notify').then(res => { api.post('/notify').then(({ data: { data: notifyCount } }) => setNotificationsCount(notifyCount))
setNotificationsCount(res.data)
})
}, []) }, [])
return ( return (

View File

@ -42,9 +42,7 @@ export function AuthProvider({children}: {children: React.ReactNode}) {
logout() logout()
} }
async function signIn({email, password}: SignInData) { async function signIn({ email, password }: SignInData) {
signOut()
const { token, user, exception }: any = await signInRequest({ const { token, user, exception }: any = await signInRequest({
email, email,
password password

View File

@ -237,8 +237,6 @@ export const getServerSideProps: GetServerSideProps = async (ctx) => {
await apiClient.post('/economy/grossAnnual').then(res => { await apiClient.post('/economy/grossAnnual').then(res => {
grossAnualGraph = res.data.data grossAnualGraph = res.data.data
}) })
.then(console.log)
.catch(console.log)
await apiClient.post('/economy/grossMonthly').then(res => { await apiClient.post('/economy/grossMonthly').then(res => {
grossMensalGraph = res.data.data grossMensalGraph = res.data.data

View File

@ -1,103 +1,108 @@
import FormControl from '@mui/material/FormControl'; import FormControl from '@mui/material/FormControl'
import IconButton from '@mui/material/IconButton'; import IconButton from '@mui/material/IconButton'
import InputAdornment from '@mui/material/InputAdornment'; import InputAdornment from '@mui/material/InputAdornment'
import InputLabel from '@mui/material/InputLabel'; import InputLabel from '@mui/material/InputLabel'
import OutlinedInput from '@mui/material/OutlinedInput'; import OutlinedInput from '@mui/material/OutlinedInput'
import TextField from '@mui/material/TextField'; import TextField from '@mui/material/TextField'
import Head from 'next/head'; import Head from 'next/head'
import Image from 'next/image'; import Image from 'next/image'
import Link from 'next/link'; import Link from 'next/link'
import { useRouter } from 'next/router' import { useRouter } from 'next/router'
import { useContext, useState, useEffect, useCallback, useRef, forwardRef } from 'react' import {
import { AiOutlineEye, AiOutlineEyeInvisible } from 'react-icons/ai'; useContext,
import RenderIf from '../utils/renderIf'; useState,
import Snackbar from '@mui/material/Snackbar'; useEffect,
useCallback,
useRef,
forwardRef
} from 'react'
import { AiOutlineEye, AiOutlineEyeInvisible } from 'react-icons/ai'
import RenderIf from '../utils/renderIf'
import Snackbar from '@mui/material/Snackbar'
import LoginButton from '../components/buttons/loginButton/LoginButton'; import LoginButton from '../components/buttons/loginButton/LoginButton'
import { AuthContext } from '../contexts/AuthContext'; import { AuthContext } from '../contexts/AuthContext'
import { api } from '../services/api'; import { api } from '../services/api'
import { LoginContainer, LoginView } from '../styles/layouts/login/LoginView'; import { LoginContainer, LoginView } from '../styles/layouts/login/LoginView'
import Dashboard from './dashboard'; import Dashboard from './dashboard'
import MuiAlert, { AlertProps } from '@mui/material/Alert'; import MuiAlert, { AlertProps } from '@mui/material/Alert'
import { GetServerSideProps } from 'next'; import { GetServerSideProps } from 'next'
import { parseCookies } from 'nookies'; import { parseCookies } from 'nookies'
import { AxiosError } from 'axios'
const Alert = forwardRef<HTMLDivElement, AlertProps>(function Alert( const Alert = forwardRef<HTMLDivElement, AlertProps>(function Alert(
props, props,
ref, ref
) { ) {
return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />; return <MuiAlert elevation={6} ref={ref} variant="filled" {...props} />
}); })
export default function Home() { export default function Home() {
const [openSnackSuccess, setOpenSnackSuccess] = useState<boolean>(false); const [openSnackSuccess, setOpenSnackSuccess] = useState<boolean>(false)
const [openSnackError, setOpenSnackError] = useState<boolean>(false); const [openSnackError, setOpenSnackError] = useState<boolean>(false)
const field = useRef(null) const field = useRef(null)
const [state, setstate] = useState(false); const [state, setstate] = useState(false)
const [focus, setFocus] = useState('email'); const [focus, setFocus] = useState('email')
const [values, setValues] = useState({ const [values, setValues] = useState({
password: null, password: null,
showPassword: false, showPassword: false
}); })
const [email, setEmail] = useState<string>("") const [email, setEmail] = useState<string>('')
const [password, setPassword] = useState<string>() const [password, setPassword] = useState<string>()
const router = useRouter() const router = useRouter()
const rota = router.pathname const rota = router.pathname
const handleChange = (prop) => (event) => { const handleChange = (prop) => (event) => {
setValues({ ...values, [prop]: event.target.value }); setValues({ ...values, [prop]: event.target.value })
setPassword(event.target.value); setPassword(event.target.value)
}; }
const handleClickShowPassword = () => { const handleClickShowPassword = () => {
setValues({ setValues({
...values, ...values,
showPassword: !values.showPassword, showPassword: !values.showPassword
}); })
}; }
const handleMouseDownPassword = (event) => { const handleMouseDownPassword = (event) => {
event.preventDefault(); event.preventDefault()
}; }
const { signIn } = useContext(AuthContext) const { signIn } = useContext(AuthContext)
async function handleSignIn() { async function handleSignIn() {
if (email === "" || password === ""){ try {
if ([email, password].some(v => !v.trim())) return setOpenSnackError(true);
await signIn({ email, password })
} catch (ex) {
setOpenSnackError(true) setOpenSnackError(true)
}else{
try {
await signIn({email, password}).then((res: any) => {
if (res.response.status === 422 || res.response.status === 401 || res.response.status === 500 ) {
setOpenSnackError(true)
}
})
} catch (exception) {
console.log(exception)
}
} }
} }
const handleCloseSnack = (event?: React.SyntheticEvent | Event, reason?: string) => { const handleCloseSnack = (
event?: React.SyntheticEvent | Event,
reason?: string
) => {
if (reason === 'clickaway') { if (reason === 'clickaway') {
return; return
} }
setOpenSnackError(false); setOpenSnackError(false)
setOpenSnackSuccess(false); setOpenSnackSuccess(false)
}; }
useEffect(() => { useEffect(() => {
setValues({ setValues({
password: (''), password: '',
showPassword: null, showPassword: null
}); })
setEmail("") setEmail('')
}, [rota]) }, [rota])
return ( return (
@ -105,40 +110,62 @@ export default function Home() {
<Head> <Head>
<title>Smart Energia</title> <title>Smart Energia</title>
</Head> </Head>
<Snackbar open={openSnackSuccess} autoHideDuration={4000} onClose={handleCloseSnack}> <Snackbar
<Alert onClose={handleCloseSnack} severity="success" sx={{ width: '100%' }}> open={openSnackSuccess}
autoHideDuration={4000}
onClose={handleCloseSnack}
>
<Alert
onClose={handleCloseSnack}
severity="success"
sx={{ width: '100%' }}
>
notificação cadastrada com sucesso! notificação cadastrada com sucesso!
</Alert> </Alert>
</Snackbar> </Snackbar>
<Snackbar open={openSnackError} autoHideDuration={4000} onClose={handleCloseSnack}> <Snackbar
<Alert onClose={handleCloseSnack} severity="error" sx={{ width: '100%' }}> open={openSnackError}
Prencha os Campos corretamente! autoHideDuration={4000}
onClose={handleCloseSnack}
>
<Alert
onClose={handleCloseSnack}
severity="error"
sx={{ width: '100%' }}
>
Preencha os campos corretamente!
</Alert> </Alert>
</Snackbar> </Snackbar>
<div> <div>
<Image src='/assets/marca1.png' width={500} height={340} /> <Image src="/assets/marca1.png" width={500} height={340} />
</div> </div>
<LoginContainer> <LoginContainer>
<h1>Bem-Vindo</h1> <h1>Bem-Vindo</h1>
<h2>Estratégias Inteligentes em<br /> Gestão de Energia</h2> <h2>
Estratégias Inteligentes em
<br /> Gestão de Energia
</h2>
<TextField
<TextField id="outlined-basic" id="outlined-basic"
sx={{ m: 1, width: '90%' }} label="Login" value={email} variant="outlined" onKeyDown={(e) => e.key==='Enter'? field.current.children[0].focus() : null} sx={{ m: 1, width: '90%' }}
onChange={value => { label="Login"
setEmail(value.target.value.toLowerCase()) value={email}
}}/> variant="outlined"
onKeyDown={(e) => e.key === 'Enter' && field.current.children[0].focus()}
onChange={(value) => setEmail(value.target.value.toLowerCase())}
/>
<FormControl sx={{ m: 1, width: '90%' }} variant="outlined"> <FormControl sx={{ m: 1, width: '90%' }} variant="outlined">
<InputLabel htmlFor="outlined-adornment-password" >Senha</InputLabel> <InputLabel htmlFor="outlined-adornment-password">Senha</InputLabel>
<OutlinedInput <OutlinedInput
id="outlined-adornment-password" id="outlined-adornment-password"
type={values.showPassword ? 'text' : 'password'} type={values.showPassword ? 'text' : 'password'}
value={values.password} value={values.password}
onChange={handleChange('password')} onChange={handleChange('password')}
ref={field} ref={field}
onKeyDown={(e) => e.key==='Enter'? handleSignIn() : null} onKeyDown={(e) => (e.key === 'Enter' ? handleSignIn() : null)}
endAdornment={ endAdornment={
<InputAdornment position="end"> <InputAdornment position="end">
<IconButton <IconButton
@ -147,22 +174,36 @@ export default function Home() {
onMouseDown={handleMouseDownPassword} onMouseDown={handleMouseDownPassword}
edge="end" edge="end"
> >
{values.showPassword ? <AiOutlineEye /> : <AiOutlineEyeInvisible />} {values.showPassword ? (
<AiOutlineEye />
) : (
<AiOutlineEyeInvisible />
)}
</IconButton> </IconButton>
</InputAdornment> </InputAdornment>
} }
label="Senha" label="Senha"
/> />
</FormControl> </FormControl>
<Link href='verifyEmail'>Esqueceu a senha ?</Link> <Link href="verifyEmail">Esqueceu a senha ?</Link>
<LoginButton title='ENTRAR' onClick={() => handleSignIn()}/> <LoginButton title="ENTRAR" onClick={() => handleSignIn()} />
<fieldset className="line"> <fieldset className="line">
<legend className="text">Ou</legend> <legend className="text">Ou</legend>
</fieldset> </fieldset>
<p><a href='tel:+55(41) 3012-5900' >+55(41) 3012-5900</a><br/><a href='https://www.energiasmart.com.br' target="_blank" rel="noreferrer" >www.energiasmart.com.br</a></p> <p>
<a href="tel:+55(41) 3012-5900">+55(41) 3012-5900</a>
<br />
<a
href="https://www.energiasmart.com.br"
target="_blank"
rel="noreferrer"
>
www.energiasmart.com.br
</a>
</p>
</LoginContainer> </LoginContainer>
</LoginView> </LoginView>
) )

View File

@ -37,12 +37,12 @@ interface pldInterface {
clientMonth: any clientMonth: any
} }
export default function pld({tableData, userName, clientMonth}: pldInterface) { export default function pld({ tableData, userName, clientMonth }: pldInterface) {
const { pldMenu, setPldMenu } = useContext(MenuContext) const { pldMenu, setPldMenu } = useContext(MenuContext)
const dateFormated = new Date() const dateFormated = new Date()
const year_Month = `0${dateFormated.getMonth()+1}/${dateFormated.getFullYear()}` const year_Month = `0${dateFormated.getMonth() + 1}/${dateFormated.getFullYear()}`
const [date, setDate] = useState<any>(new Date()); const [date, setDate] = useState<any>(new Date());
const [select, setSelect] = useState('SUDESTE'); const [select, setSelect] = useState('SUDESTE');
@ -56,9 +56,11 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
const [norte, setNorte] = useState([]) const [norte, setNorte] = useState([])
const [sudeste, setSudeste] = useState([]) const [sudeste, setSudeste] = useState([])
const [nordeste, setNordeste] = useState([]) const [nordeste, setNordeste] = useState([])
const [ pageYPosition, setPageYPosition ] = useState(0); const [pageYPosition, setPageYPosition] = useState(0);
function getPageYAfterScroll(){ console.log(tableData?.data)
function getPageYAfterScroll() {
setPageYPosition(window.scrollY); setPageYPosition(window.scrollY);
} }
@ -76,9 +78,9 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
function getDataByDay() { function getDataByDay() {
api.post('/pld/daily', { api.post('/pld/daily', {
"filters": [ "filters": [
{"type" : "=", "field" : "year_month_formatted", "value": month, "row": true}, { "type": "=", "field": "year_month_formatted", "value": month, "row": true },
{"type" : "=", "field" : "submarket", "value": select} { "type": "=", "field": "submarket", "value": select }
], ],
"order": [{ "field": "day_calc", "direction": "asc" }] "order": [{ "field": "day_calc", "direction": "asc" }]
}).then(res => { }).then(res => {
setDataByDay(res.data.data) setDataByDay(res.data.data)
@ -92,9 +94,9 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
"limit": 20, "limit": 20,
"offset": 0, "offset": 0,
"filters": [ "filters": [
{"type" : "=", "field" : "dia_num", "value": date.toLocaleDateString().split('/').reverse().join('-'), "row": true}, { "type": "=", "field": "dia_num", "value": date.toLocaleDateString().split('/').reverse().join('-'), "row": true },
{"type" : "=", "field" : "submercado", "value": "SUL"} { "type": "=", "field": "submercado", "value": "SUL" }
], ],
"order": [{ "field": "hour", "direction": "asc" }] "order": [{ "field": "hour", "direction": "asc" }]
}).then(res => { }).then(res => {
setSul(res.data.data) setSul(res.data.data)
@ -106,9 +108,9 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
"limit": 20, "limit": 20,
"offset": 0, "offset": 0,
"filters": [ "filters": [
{"type" : "=", "field" : "dia_num", "value": date.toLocaleDateString().split('/').reverse().join('-'), "row": true}, { "type": "=", "field": "dia_num", "value": date.toLocaleDateString().split('/').reverse().join('-'), "row": true },
{"type" : "=", "field" : "submercado", "value": "SUDESTE"} { "type": "=", "field": "submercado", "value": "SUDESTE" }
], ],
"order": [{ "field": "hour", "direction": "asc" }] "order": [{ "field": "hour", "direction": "asc" }]
}).then(res => { }).then(res => {
setSudeste(res.data.data) setSudeste(res.data.data)
@ -120,9 +122,9 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
"limit": 20, "limit": 20,
"offset": 0, "offset": 0,
"filters": [ "filters": [
{"type" : "=", "field" : "dia_num", "value": date.toLocaleDateString().split('/').reverse().join('-'), "row": true}, { "type": "=", "field": "dia_num", "value": date.toLocaleDateString().split('/').reverse().join('-'), "row": true },
{"type" : "=", "field" : "submercado", "value": "NORTE"} { "type": "=", "field": "submercado", "value": "NORTE" }
], ],
"order": [{ "field": "hour", "direction": "asc" }] "order": [{ "field": "hour", "direction": "asc" }]
}).then(res => { }).then(res => {
setNorte(res.data.data) setNorte(res.data.data)
@ -134,9 +136,9 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
"limit": 20, "limit": 20,
"offset": 0, "offset": 0,
"filters": [ "filters": [
{"type" : "=", "field" : "dia_num", "value": date.toLocaleDateString().split('/').reverse().join('-'), "row": true}, { "type": "=", "field": "dia_num", "value": date.toLocaleDateString().split('/').reverse().join('-'), "row": true },
{"type" : "=", "field" : "submercado", "value": "NORDESTE"} { "type": "=", "field": "submercado", "value": "NORDESTE" }
], ],
"order": [{ "field": "hour", "direction": "asc" }] "order": [{ "field": "hour", "direction": "asc" }]
}).then(res => { }).then(res => {
setNordeste(res.data.data) setNordeste(res.data.data)
@ -150,14 +152,14 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
return '' return ''
else if (value >= tableData.result[0][`${region}_max`]) else if (value >= tableData.result[0][`${region}_max`])
return '' return ''
else if (tableData.result[0][`${region}_max`] - value > tableData.result[0][`${region}_max`]/2) else if (tableData.result[0][`${region}_max`] - value > tableData.result[0][`${region}_max`] / 2)
return '' return ''
else if (tableData.result[1][`${region}_min`] - value <= tableData.result[1][`${region}_min`]) else if (tableData.result[1][`${region}_min`] - value <= tableData.result[1][`${region}_min`])
return '' return ''
} }
function downloadCSVFile(csv, filename) { function downloadCSVFile(csv, filename) {
const csv_file = new Blob(["\ufeff",csv], {type: "text/csv"}); const csv_file = new Blob(["\ufeff", csv], { type: "text/csv" });
const download_link = document.createElement("a"); const download_link = document.createElement("a");
@ -177,7 +179,7 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
const rows = document.querySelectorAll("table tr"); const rows = document.querySelectorAll("table tr");
// const rows = document.getElementsByClassName('tabela'); // const rows = document.getElementsByClassName('tabela');
for (let i = rows.length/2; i < rows.length; i++) { for (let i = rows.length / 2; 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++) { for (let j = 0; j < cols.length; j++) {
@ -200,31 +202,31 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
}, []) }, [])
return ( return (
<main style={{width: '100%'}}> <main style={{ width: '100%' }}>
<Head> <Head>
<title>Smart Energia - PLD</title> <title>Smart Energia - PLD</title>
</Head> </Head>
<div id='title'/> <div id='title' />
<Header name={userName}> <Header name={userName}>
<PageTitle title='PLD' subtitle='Evolução PLD - Valores em R$/MWh'/> <PageTitle title='PLD' subtitle='Evolução PLD - Valores em R$/MWh' />
</Header> </Header>
<TableHeader> <TableHeader>
<Tabs value={pldMenu} onChange={(e, nv) => setPldMenu(nv)} aria-label=""> <Tabs value={pldMenu} onChange={(e, nv) => setPldMenu(nv)} aria-label="">
<Tab label="Pld Histórico"/> <Tab label="Pld Histórico" />
<Tab label="Valores Diários"/> <Tab label="Valores Diários" />
<Tab label="Valores Horários"/> <Tab label="Valores Horários" />
</Tabs> </Tabs>
<div className='btnDownload'> <div className='btnDownload'>
<RenderIf isTrue={pldMenu === 0}> <RenderIf isTrue={pldMenu === 0}>
<BasicButton onClick={() => { <BasicButton onClick={() => {
const html = document.querySelector("table").outerHTML; const html = document.querySelector("table").outerHTML;
htmlToCSV(html, "tabela_PLD.csv"); htmlToCSV(html, "tabela_PLD.csv");
}} title='Download'/> }} title='Download' />
</RenderIf> </RenderIf>
</div> </div>
</TableHeader> </TableHeader>
<RenderIf isTrue={pldMenu===0}> <RenderIf isTrue={pldMenu === 0}>
<PldTableView> <PldTableView>
<table className='tg'> <table className='tg'>
<thead> <thead>
@ -238,17 +240,17 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
</thead> </thead>
<tbody> <tbody>
{ {
tableData.data.map(data => { tableData?.data?.map(data => (
return <> <>
<tr className={data.year_month_formatted==year_Month? 'actual' : ''}> <tr className={data.year_month_formatted == year_Month ? 'actual' : ''}>
<td className='tg-gceh'>{data.year_month_formatted}</td> <td className='tg-gceh'>{data.year_month_formatted}</td>
<td className={`tg-uulg`}>{parseFloat(data.nordeste).toLocaleString('pt-br',{currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className={`tg-uulg`}>{parseFloat(data.nordeste).toLocaleString('pt-br', { currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className={`tg-gceh`}>{parseFloat(data.norte).toLocaleString('pt-br',{currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className={`tg-gceh`}>{parseFloat(data.norte).toLocaleString('pt-br', { currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className={`tg-gceh`}>{parseFloat(data.sudeste).toLocaleString('pt-br',{currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className={`tg-gceh`}>{parseFloat(data.sudeste).toLocaleString('pt-br', { currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className={`tg-uulg`}>{parseFloat(data.sul).toLocaleString('pt-br',{currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className={`tg-uulg`}>{parseFloat(data.sul).toLocaleString('pt-br', { currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
</tr> </tr>
</> </>
}) ))
} }
</tbody> </tbody>
</table> </table>
@ -261,31 +263,31 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
if (index === 0) { if (index === 0) {
return <> return <>
<tr> <tr>
<td style={{borderTopLeftRadius: 8}} className='tg-gceh'>Máximo</td> <td style={{ borderTopLeftRadius: 8 }} className='tg-gceh'>Máximo</td>
<td className='tg-uulg'>{parseFloat(data.nordeste_max).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className='tg-uulg'>{parseFloat(data.nordeste_max).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className='tg-gceh'>{parseFloat(data.norte_max).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className='tg-gceh'>{parseFloat(data.norte_max).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className='tg-gceh'>{parseFloat(data.sudeste_max).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className='tg-gceh'>{parseFloat(data.sudeste_max).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className='tg-uulg'>{parseFloat(data.sul_max).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className='tg-uulg'>{parseFloat(data.sul_max).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
</tr> </tr>
</> </>
} else if (index===1) { } else if (index === 1) {
return <> return <>
<tr> <tr>
<td className='tg-gceh'>Mínimo</td> <td className='tg-gceh'>Mínimo</td>
<td className='tg-uulg'>{parseFloat(data.nordeste_min).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className='tg-uulg'>{parseFloat(data.nordeste_min).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className='tg-gceh'>{parseFloat(data.norte_min).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className='tg-gceh'>{parseFloat(data.norte_min).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className='tg-gceh'>{parseFloat(data.sudeste_min).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className='tg-gceh'>{parseFloat(data.sudeste_min).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className='tg-uulg'>{parseFloat(data.sul_min).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className='tg-uulg'>{parseFloat(data.sul_min).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
</tr> </tr>
</> </>
} else if (index===2) { } else if (index === 2) {
return <> return <>
<tr> <tr>
<td className='tg-gceh' style={{borderBottomColor: 'transparent'}}>Desv. Padrão</td> <td className='tg-gceh' style={{ borderBottomColor: 'transparent' }}>Desv. Padrão</td>
<td className='tg-uulg' style={{borderBottomColor: 'transparent'}}>{parseFloat(data.nordeste_desv_pad).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2})}</td> <td className='tg-uulg' style={{ borderBottomColor: 'transparent' }}>{parseFloat(data.nordeste_desv_pad).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2 })}</td>
<td className='tg-gceh' style={{borderBottomColor: 'transparent'}}>{parseFloat(data.norte_desv_pad).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2})}</td> <td className='tg-gceh' style={{ borderBottomColor: 'transparent' }}>{parseFloat(data.norte_desv_pad).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2 })}</td>
<td className='tg-gceh' style={{borderBottomColor: 'transparent'}}>{parseFloat(data.sudeste_desv_pad).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2})}</td> <td className='tg-gceh' style={{ borderBottomColor: 'transparent' }}>{parseFloat(data.sudeste_desv_pad).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2 })}</td>
<td className='tg-uulg' style={{borderBottomColor: 'transparent'}}>{parseFloat(data.sul_desv_pad).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2})}</td> <td className='tg-uulg' style={{ borderBottomColor: 'transparent' }}>{parseFloat(data.sul_desv_pad).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2 })}</td>
</tr> </tr>
</> </>
} }
@ -296,7 +298,7 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
</PldTableMinMaxView> </PldTableMinMaxView>
<PldTableView display={false}> <PldTableView display={false}>
<table className="tg tabela" style={{display: 'none'}}> <table className="tg tabela" style={{ display: 'none' }}>
<thead> <thead>
<tr className='tr'> <tr className='tr'>
<th className='tg-8oo6'>Mês</th> <th className='tg-8oo6'>Mês</th>
@ -308,14 +310,14 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
</thead> </thead>
<tbody> <tbody>
{ {
tableData.data.map(data => { tableData?.data?.map(data => {
return <> return <>
<tr className={`${data.year_month_formatted==year_Month? 'actual' : ''} tr`}> <tr className={`${data.year_month_formatted == year_Month ? 'actual' : ''} tr`}>
<td className='tg-gceh'>{data.year_month_formatted}</td> <td className='tg-gceh'>{data.year_month_formatted}</td>
<td className={`tg-uulg`}>{parseFloat(data.nordeste).toLocaleString('pt-br',{currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className={`tg-uulg`}>{parseFloat(data.nordeste).toLocaleString('pt-br', { currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className={`tg-gceh`}>{parseFloat(data.norte).toLocaleString('pt-br',{currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className={`tg-gceh`}>{parseFloat(data.norte).toLocaleString('pt-br', { currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className={`tg-gceh`}>{parseFloat(data.sudeste).toLocaleString('pt-br',{currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className={`tg-gceh`}>{parseFloat(data.sudeste).toLocaleString('pt-br', { currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className={`tg-uulg`}>{parseFloat(data.sul).toLocaleString('pt-br',{currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className={`tg-uulg`}>{parseFloat(data.sul).toLocaleString('pt-br', { currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
</tr> </tr>
</> </>
}) })
@ -325,31 +327,31 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
if (index === 0) { if (index === 0) {
return <> return <>
<tr className='tr'> <tr className='tr'>
<td style={{borderTopLeftRadius: 8}} className='tg-gceh'>Máximo</td> <td style={{ borderTopLeftRadius: 8 }} className='tg-gceh'>Máximo</td>
<td className='tg-uulg'>{parseFloat(data.nordeste_max).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className='tg-uulg'>{parseFloat(data.nordeste_max).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className='tg-gceh'>{parseFloat(data.norte_max).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className='tg-gceh'>{parseFloat(data.norte_max).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className='tg-gceh'>{parseFloat(data.sudeste_max).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className='tg-gceh'>{parseFloat(data.sudeste_max).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className='tg-uulg'>{parseFloat(data.sul_max).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className='tg-uulg'>{parseFloat(data.sul_max).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
</tr> </tr>
</> </>
} else if (index===1) { } else if (index === 1) {
return <> return <>
<tr className='tr'> <tr className='tr'>
<td className='tg-gceh'>Mínimo</td> <td className='tg-gceh'>Mínimo</td>
<td className='tg-uulg'>{parseFloat(data.nordeste_min).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className='tg-uulg'>{parseFloat(data.nordeste_min).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className='tg-gceh'>{parseFloat(data.norte_min).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className='tg-gceh'>{parseFloat(data.norte_min).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className='tg-gceh'>{parseFloat(data.sudeste_min).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className='tg-gceh'>{parseFloat(data.sudeste_min).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
<td className='tg-uulg'>{parseFloat(data.sul_min).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2})}</td> <td className='tg-uulg'>{parseFloat(data.sul_min).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2, maximumFractionDigits: 2 })}</td>
</tr> </tr>
</> </>
} else if (index===2) { } else if (index === 2) {
return <> return <>
<tr className='tr'> <tr className='tr'>
<td className='tg-gceh' style={{borderBottomColor: 'transparent'}}>Desv. Padrão</td> <td className='tg-gceh' style={{ borderBottomColor: 'transparent' }}>Desv. Padrão</td>
<td className='tg-uulg' style={{borderBottomColor: 'transparent'}}>{parseFloat(data.nordeste_desv_pad).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2})}</td> <td className='tg-uulg' style={{ borderBottomColor: 'transparent' }}>{parseFloat(data.nordeste_desv_pad).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2 })}</td>
<td className='tg-gceh' style={{borderBottomColor: 'transparent'}}>{parseFloat(data.norte_desv_pad).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2})}</td> <td className='tg-gceh' style={{ borderBottomColor: 'transparent' }}>{parseFloat(data.norte_desv_pad).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2 })}</td>
<td className='tg-gceh' style={{borderBottomColor: 'transparent'}}>{parseFloat(data.sudeste_desv_pad).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2})}</td> <td className='tg-gceh' style={{ borderBottomColor: 'transparent' }}>{parseFloat(data.sudeste_desv_pad).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2 })}</td>
<td className='tg-uulg' style={{borderBottomColor: 'transparent'}}>{parseFloat(data.sul_desv_pad).toLocaleString('pt-br',{style: 'currency', currency: 'BRL', minimumFractionDigits: 2})}</td> <td className='tg-uulg' style={{ borderBottomColor: 'transparent' }}>{parseFloat(data.sul_desv_pad).toLocaleString('pt-br', { style: 'currency', currency: 'BRL', minimumFractionDigits: 2 })}</td>
</tr> </tr>
</> </>
} }
@ -361,24 +363,24 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
</RenderIf> </RenderIf>
{/* grafico de grafico por seleção de data (mês) (diario)*/} {/* grafico de grafico por seleção de data (mês) (diario)*/}
<RenderIf isTrue={pldMenu===1}> <RenderIf isTrue={pldMenu === 1}>
<PldGraphView> <PldGraphView>
<section className='toolsbar2'> <section className='toolsbar2'>
<FormControl sx={{ <FormControl sx={{
width: '320px' width: '320px'
}}> }}>
<InputLabel id="demo-simple-select-label">Região</InputLabel> <InputLabel id="demo-simple-select-label">Região</InputLabel>
<Select <Select
value={select} value={select}
onChange={handleChange} onChange={handleChange}
displayEmpty displayEmpty
label='Região' label='Região'
> >
<MenuItem value={'NORTE'}>Norte</MenuItem> <MenuItem value={'NORTE'}>Norte</MenuItem>
<MenuItem value={'NORDESTE'}>Nordeste</MenuItem> <MenuItem value={'NORDESTE'}>Nordeste</MenuItem>
<MenuItem value={'SUL'}>Sul</MenuItem> <MenuItem value={'SUL'}>Sul</MenuItem>
<MenuItem value={'SUDESTE'}>Sudeste</MenuItem> <MenuItem value={'SUDESTE'}>Sudeste</MenuItem>
</Select> </Select>
</FormControl> </FormControl>
<FormControl sx={{ <FormControl sx={{
width: '320px', width: '320px',
@ -386,39 +388,39 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
}}> }}>
<InputLabel id="demo-simple-select-label">Mês</InputLabel> <InputLabel id="demo-simple-select-label">Mês</InputLabel>
<Select <Select
value={month} value={month}
onChange={handleChangeDay} onChange={handleChangeDay}
displayEmpty displayEmpty
placeholder='dia' placeholder='dia'
label="Age" label="Age"
> >
<MenuItem value={'0'}>Nenhum</MenuItem> <MenuItem value={'0'}>Nenhum</MenuItem>
{ {
clientMonth.sort((a, b) => { clientMonth.sort((a, b) => {
if (a.mes_ref.split('/')[0] < b.mes_ref.split('/')[0]) return 1 if (a.mes_ref.split('/')[0] < b.mes_ref.split('/')[0]) return 1
if (a.mes_ref.split('/')[0] > b.mes_ref.split('/')[0]) return -1 if (a.mes_ref.split('/')[0] > b.mes_ref.split('/')[0]) return -1
}).sort((a, b) => { }).sort((a, b) => {
if (a.mes_ref.split('/')[1] < b.mes_ref.split('/')[1]) return 1 if (a.mes_ref.split('/')[1] < b.mes_ref.split('/')[1]) return 1
if (a.mes_ref.split('/')[1] > b.mes_ref.split('/')[1]) return -1 if (a.mes_ref.split('/')[1] > b.mes_ref.split('/')[1]) return -1
}).map((data, index) => { }).map((data, index) => {
return <MenuItem key={index} value={data.mes_ref}>{data.mes_ref}</MenuItem> return <MenuItem key={index} value={data.mes_ref}>{data.mes_ref}</MenuItem>
}) })
} }
</Select> </Select>
</FormControl> </FormControl>
</section> </section>
<LineBarChart <LineBarChart
data1={dataByDay.map(value => value.mmovel)} data3={dataByDay} data1={dataByDay.map(value => value.mmovel)} data3={dataByDay}
dataset1={'Média'} dataset2={'barra1'} dataset3={'Diario'} dataset1={'Média'} dataset2={'barra1'} dataset3={'Diario'}
label={dataByDay.map((value, index) => { label={dataByDay.map((value, index) => {
return value.day_formatted return value.day_formatted
})} })}
title='' subtitle='' /> title='' subtitle='' />
</PldGraphView> </PldGraphView>
</RenderIf> </RenderIf>
{/* grafico de grafico por seleção de data INTEIRA (horario)*/} {/* grafico de grafico por seleção de data INTEIRA (horario)*/}
<RenderIf isTrue={pldMenu===2}> <RenderIf isTrue={pldMenu === 2}>
<PldGraphView> <PldGraphView>
<section className='toolsbar2'> <section className='toolsbar2'>
{/* <p>Selecione a data: </p> */} {/* <p>Selecione a data: </p> */}
@ -429,7 +431,7 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
inputFormat="dd/MM/yyyy" inputFormat="dd/MM/yyyy"
value={date} value={date}
onChange={handleChangeDate} onChange={handleChangeDate}
renderInput={(params) => <TextField {...params} style={{minWidth: '320px'}}/>} renderInput={(params) => <TextField {...params} style={{ minWidth: '320px' }} />}
/> />
</div> </div>
</LocalizationProvider> </LocalizationProvider>
@ -441,7 +443,7 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
/> />
</PldGraphView> </PldGraphView>
</RenderIf> </RenderIf>
{pageYPosition > 300 && <a href="#title" style={{position: 'fixed', right: '50px', bottom: '100px'}}> {pageYPosition > 300 && <a href="#title" style={{ position: 'fixed', right: '50px', bottom: '100px' }}>
<Fab aria-label="add"> <Fab aria-label="add">
<NavigationIcon /> <NavigationIcon />
</Fab> </Fab>
@ -455,11 +457,11 @@ export const getServerSideProps: GetServerSideProps = async (ctx) => {
const { ['@smartAuth-token']: token } = parseCookies(ctx) const { ['@smartAuth-token']: token } = parseCookies(ctx)
const { ['user-name']: userName } = parseCookies(ctx) const { ['user-name']: userName } = parseCookies(ctx)
let tableData = []; let tableData = { data: [], result: [] };
let clientMonth = []; let clientMonth = [];
await apiClient.post('/pld/list').then(res => { await apiClient.post('/pld/list').then(res => {
tableData = res.data tableData = res.data.data
}) })
await apiClient.post('/pld', { await apiClient.post('/pld', {

View File

@ -30,7 +30,7 @@ export default function ResumoOperacao({
clientMonth clientMonth
}: any) { }: any) {
const [month, setMonth] = useState('') const [month, setMonth] = useState('')
const [unidade, setUnidade] = useState(clients[0].cod_smart_unidade) const [unidade, setUnidade] = useState(clients?.[0]?.cod_smart_unidade ?? 0)
const [tableDataState, setTableDataState] = useState<any>([]) const [tableDataState, setTableDataState] = useState<any>([])
const { ['user-id']: id } = parseCookies() const { ['user-id']: id } = parseCookies()

View File

@ -61,7 +61,7 @@ const months = [
] ]
export default function Telemetria({ userName, clients }: any) { export default function Telemetria({ userName, clients }: any) {
const [unity, setUnity] = useState(clients[0]?.codigo_scde) const [unity, setUnity] = useState(clients?.[0]?.codigo_scde ?? 0)
const [startDate, setStartDate] = useState(new Date()) const [startDate, setStartDate] = useState(new Date())
const [endDate, setEndDate] = useState(new Date()) const [endDate, setEndDate] = useState(new Date())
const [month, setMonth] = useState(new Date().getMonth()) const [month, setMonth] = useState(new Date().getMonth())
@ -915,7 +915,6 @@ export const getServerSideProps: GetServerSideProps = async (ctx) => {
distinct: true distinct: true
}) })
.then((res) => { .then((res) => {
console.log(res.data)
clients = res.data.data clients = res.data.data
}) })

View File

@ -1,23 +1,23 @@
import { api } from "./api"; import { api } from './api'
export const TOKEN_KEY = "@smartAuth-token"; export const TOKEN_KEY = '@smartAuth-token'
interface SignInRequestData { interface SignInRequestData {
email: string, email: string
password: string password: string
} }
type UserObjectType = { type UserObjectType = {
name: string; name: string
email: string; email: string
client_id: number; client_id: number
id: number; id: number
role: number; role: number
profile_picture?: string profile_picture?: string
} }
export async function signInRequest(data: SignInRequestData) { export async function signInRequest(data: SignInRequestData) {
let user: UserObjectType, token: string, exception: any = null let user: UserObjectType, token: string
await api await api
.post('/auth/login', { .post('/auth/login', {
@ -36,9 +36,6 @@ export async function signInRequest(data: SignInRequestData) {
profile_picture: res.data.user.profile_picture profile_picture: res.data.user.profile_picture
} }
}) })
.catch((res) => {
exception = res
})
return { return {
token, token,
@ -49,15 +46,14 @@ export async function signInRequest(data: SignInRequestData) {
id: user?.id, id: user?.id,
role: user?.role, role: user?.role,
profile_picture: user?.profile_picture profile_picture: user?.profile_picture
}, }
exception
} }
} }
export default async function recoverUserInformation(id) { export default async function recoverUserInformation(id) {
let user: UserObjectType let user: UserObjectType
await api.get(`/user/${id}`).then(res => { await api.get(`/user/${id}`).then((res) => {
user = { user = {
name: res.data.user.name, name: res.data.user.name,
email: res.data.user.email, email: res.data.user.email,
@ -80,7 +76,8 @@ export default async function recoverUserInformation(id) {
} }
export async function logout() { export async function logout() {
await api.post('/auth/logout', {}) await api
// eslint-disable-next-line @typescript-eslint/no-empty-function .post('/auth/logout', {})
.then(res => {}) // eslint-disable-next-line @typescript-eslint/no-empty-function
.then((res) => {})
} }

View File

@ -18,9 +18,12 @@ export default function getAPIClient(
const { '@smartAuth-token': token } = parseCookies(ctx) const { '@smartAuth-token': token } = parseCookies(ctx)
const api = axios.create({ 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' // baseURL: 'https://api.energiasmart.klupp.com.br/api'
// baseURL: 'http://api-smart.test/api' baseURL:
process.env.NODE_ENV === 'production'
? 'https://api.energiasmart.com.br/api'
: 'http://api-smart.test/api'
}) })
api.interceptors.request.use((config) => { api.interceptors.request.use((config) => {