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

@ -43,8 +43,6 @@ export function AuthProvider({children}: {children: React.ReactNode}) {
} }
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 === ""){
setOpenSnackError(true)
}else{
try { try {
await signIn({email, password}).then((res: any) => { if ([email, password].some(v => !v.trim())) return setOpenSnackError(true);
if (res.response.status === 422 || res.response.status === 401 || res.response.status === 500 ) {
await signIn({ email, password })
} catch (ex) {
setOpenSnackError(true) 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,31 +110,53 @@ 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
@ -138,7 +165,7 @@ export default function Home() {
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

@ -58,6 +58,8 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
const [nordeste, setNordeste] = useState([]) const [nordeste, setNordeste] = useState([])
const [pageYPosition, setPageYPosition] = useState(0); const [pageYPosition, setPageYPosition] = useState(0);
console.log(tableData?.data)
function getPageYAfterScroll() { function getPageYAfterScroll() {
setPageYPosition(window.scrollY); setPageYPosition(window.scrollY);
} }
@ -238,8 +240,8 @@ 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>
@ -248,7 +250,7 @@ export default function pld({tableData, userName, clientMonth}: pldInterface) {
<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>
@ -308,7 +310,7 @@ 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>
@ -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
.post('/auth/logout', {})
// eslint-disable-next-line @typescript-eslint/no-empty-function // eslint-disable-next-line @typescript-eslint/no-empty-function
.then(res => {}) .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) => {