add: add percentage in mensal chart

This commit is contained in:
joseCorte-exe 2022-10-20 10:33:19 -03:00
parent fb2d0ff2c9
commit 309c2b456a
6 changed files with 332 additions and 35 deletions

View File

@ -12,14 +12,21 @@ import TableSortLabel from '@mui/material/TableSortLabel';
import { visuallyHidden } from '@mui/utils'; import { visuallyHidden } from '@mui/utils';
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import Image from 'next/image'
import Snackbar from '@mui/material/Snackbar'; import Snackbar from '@mui/material/Snackbar';
import MuiAlert, { AlertProps } from '@mui/material/Alert'; import MuiAlert, { AlertProps } from '@mui/material/Alert';
import Modal from '@mui/material/Modal'; import Modal from '@mui/material/Modal';
import FormData from 'form-data'
import { InputUploadView } from '../inputUploadImg/inputUploadView'
import { FormControl, InputLabel, MenuItem, Select, TextField, Typography } from '@mui/material'
import { TableView, StyledStatus } from './TableView'; import { TableView, StyledStatus } from './TableView';
import { api } from '../../services/api'; import { api } from '../../services/api';
import FaqButton1 from '../buttons/faqButton/FaqButton1';
import FaqButton2 from '../buttons/faqButton/FaqButton2';
const style = { const style = {
position: 'absolute' as const, position: 'absolute' as const,
@ -276,6 +283,65 @@ export default function ClientTable({clients, onChange}: ClientsTableInterface)
const emptyRows = const emptyRows =
page > 0 ? Math.max(0, (1 + page) * rowsPerPage - clients.length) : 0; page > 0 ? Math.max(0, (1 + page) * rowsPerPage - clients.length) : 0;
const formData = new FormData()
const [clientEdit, setClientEdit] = useState<any>({
name: String,
email: String,
password: String,
password_confirmation: String,
client_id: Number
})
const [logo, setLogo] = useState(false)
const [imageURLS, setImageURLs] = useState([])
const [images, setImages] = useState([] as any)
const [nivelAcess, setnivelAcess] = useState<any>(2);
const [openEditUserModal, setOpenEditUserModal] = useState<any>(2);
const [selectedClient, setSelectedClient] = useState<any>(2);
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<boolean>(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 ( return (
<TableView> <TableView>
<Snackbar open={openSnackError} autoHideDuration={4000} onClose={handleCloseSnack}> <Snackbar open={openSnackError} autoHideDuration={4000} onClose={handleCloseSnack}>
@ -332,10 +398,15 @@ export default function ClientTable({clients, onChange}: ClientsTableInterface)
> >
Client - {row.client_id} Client - {row.client_id}
</TableCell> </TableCell>
<TableCell align="left">{row.name}</TableCell> <TableCell align="left" style={{cursor: 'pointer'}} onClick={() => {
setOpenEditUserModal(true)
setSelectedClient(row)
setClientEdit(row)
}}>{row.name}</TableCell>
<TableCell align="left" style={{cursor: 'pointer'}} onClick={() => { <TableCell align="left" style={{cursor: 'pointer'}} onClick={() => {
setOpen(true) setOpen(true)
getClientUnits(row.client_id) getClientUnits(row.client_id)
setSelectedClient(row)
}}>clique aqui para ver as unidades</TableCell> }}>clique aqui para ver as unidades</TableCell>
<TableCell align="left"><StyledStatus status={row.deleted_at? 'inativo' : 'ativo'}> {row.deleted_at? 'inativo' : 'ativo'}</StyledStatus></TableCell> <TableCell align="left"><StyledStatus status={row.deleted_at? 'inativo' : 'ativo'}> {row.deleted_at? 'inativo' : 'ativo'}</StyledStatus></TableCell>
</TableRow> </TableRow>
@ -363,6 +434,143 @@ export default function ClientTable({clients, onChange}: ClientsTableInterface)
onRowsPerPageChange={handleChangeRowsPerPage} onRowsPerPageChange={handleChangeRowsPerPage}
/> />
</Paper> </Paper>
<Modal
open={openEditUserModal}
onClose={() => setOpenEditUserModal(false)}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box sx={style}>
<h1>Editar Cliente - {selectedClient.name}</h1>
<Typography
sx={{ color: 'gray', fontSize: 12 }}
variant="h5"
gutterBottom
component="div"
>
Adicionar Cliente Smart Energia
</Typography>
<br />
<TextField
id="outlined-basic"
label="Nome"
sx={{ width: 350, ml: 5 }}
onChange={(value) => {
setClientEdit({
...clientEdit,
name: value.target.value
})
}}
variant="outlined"
/>
<TextField
id="outlined-basic"
label="E-mail/Usuário"
value={clientEdit.email}
sx={{ width: 350, ml: 8 }}
onChange={(value) => {
setClientEdit({
...clientEdit,
email: value.target.value.toLowerCase()
})
}}
variant="outlined"
/>
<TextField
id="outlined-basic"
label="Senha"
sx={{ width: 350, ml: 5, mt: 2 }}
onChange={(value) => {
setClientEdit({
...clientEdit,
password: value.target.value
})
}}
variant="outlined"
/>
<TextField
id="outlined-basic"
label="Confirma Senha"
sx={{ width: 350, ml: 8, mt: 2 }}
onChange={(value) => {
setClientEdit({
...clientEdit,
password_confirmation: value.target.value
})
}}
variant="outlined"
/>
<TextField
id="outlined-basic"
label="Codigo do Cliente Smart Energia"
sx={{ width: 350, ml: 5, mt: 2 }}
onChange={(value) => {
setClientEdit({
...clientEdit,
client_id: value.target.value
})
}}
variant="outlined"
/>
<InputUploadView>
<div className="imgContainer">
<article>
{imageURLS.map((imageSrc, index) => {
return <Image
src={imageSrc}
key={index}
width={30}
height={30}
className="image"
/>
})}
</article>
</div>
<div className="update">
<form action="">
<div>
<label htmlFor="arquivo">
{' '}
<p className="TitleButton"> Enviar foto de Perfil </p>{' '}
</label>
<input
type="file"
name="arquivo"
id="arquivo"
onChange={onImageChange}
/>
</div>
</form>
</div>
</InputUploadView>
<div className='select'>
<FormControl sx={{ width: 350, ml: 5, mt: 2 }}>
<InputLabel id="demo-select-small">Nivel de acesso</InputLabel>
<Select
labelId="demo-select-small"
id="demo-select-small"
value={nivelAcess}
label="Unidade"
onChange={value => setnivelAcess(value.target.value)}
fullWidth
>
<MenuItem value={1}>Administrador</MenuItem>
<MenuItem value={2}>Cliente</MenuItem>
</Select>
</FormControl>
</div>
<FaqButton1 title="Cancelar" onClick={() => setOpenEditUserModal(false)} />
<FaqButton2
title="Salvar"
onClick={() => handleUpdateClient(clientEdit, selectedClient.id)}
/>
</Box>
</Modal>
<Modal <Modal
open={open} open={open}
onClose={handleClose} onClose={handleClose}

View File

@ -1,6 +1,6 @@
import React, { useEffect, useState } from 'react' import React, { useEffect, useState } from 'react'
import { Bar, Line, Chart as ChartJs } from 'react-chartjs-2'; import { Bar, Line, Chart as ChartJs } from 'react-chartjs-2'
import { import {
Chart as ChartJS, Chart as ChartJS,
CategoryScale, CategoryScale,
@ -11,40 +11,51 @@ import {
Legend Legend
} from 'chart.js' } from 'chart.js'
import document from 'next/document'; import document from 'next/document'
import { draw, generate } from 'patternomaly' import { draw, generate } from 'patternomaly'
import { GrossMensalChartView } from './GrossMensalChartView'; import { GrossMensalChartView } from './GrossMensalChartView'
import ChartTitle from '../ChartTitle'; import ChartTitle from '../ChartTitle'
import { config } from '../config'; import { config } from '../config'
// import { data } from './LineBarChart'; // import { data } from './LineBarChart';
ChartJS.register( ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend)
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend
)
interface ChartInterface { interface ChartInterface {
title: string, title: string
subtitle: string, subtitle: string
data1: any, data1: any
data2: any, data2: any
single?: any single?: any
label: any, label: any
miniature?: boolean | undefined miniature?: boolean | undefined
} }
export default function GrossMensalChart({ title, data1, data2, label, subtitle, miniature }: ChartInterface) { export default function GrossMensalChart({
title,
data1,
data2,
label,
subtitle,
miniature
}: ChartInterface) {
function spacement(string) { 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 return spaces
} }
@ -53,13 +64,80 @@ export default function GrossMensalChart({ title, data1, data2, label, subtitle,
let lastData = '0' let lastData = '0'
let index = 0 let index = 0
while (index < data1.length) { 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++ index++
setLastData(`economia acumulada: R$ ${parseFloat(lastData).toLocaleString('pt-br', {minimumFractionDigits: 2})}`) setLastData(
`economia acumulada: R$ ${parseFloat(lastData).toLocaleString('pt-br', {
minimumFractionDigits: 2
})}`
)
} }
}, [data1]) }, [data1])
const options: any = config(miniature) const options: any = {
responsive: true,
scales: {
x: {
stacked: false,
grid: {
display: false
},
ticks: {
font: {
size: !miniature ? window.innerWidth / 90 : window.innerWidth / 125
}
}
},
y: {
stacked: false,
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 = { const data: any = {
labels: label, labels: label,
@ -67,7 +145,9 @@ export default function GrossMensalChart({ title, data1, data2, label, subtitle,
{ {
type: 'bar', type: 'bar',
label: 'Consolidado', 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, skipNull: true,
borderRadius: 8, borderRadius: 8,
backgroundColor: '#255488', backgroundColor: '#255488',
@ -76,21 +156,21 @@ export default function GrossMensalChart({ title, data1, data2, label, subtitle,
{ {
type: 'bar', type: 'bar',
label: 'Estimado', 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, skipNull: true,
borderRadius: 8, borderRadius: 8,
backgroundColor: draw('diagonal-right-left', '#C2d5fb'), backgroundColor: draw('diagonal-right-left', '#C2d5fb'),
stack: '0' stack: '0'
}, }
], ]
} }
return ( return (
<GrossMensalChartView> <GrossMensalChartView>
<ChartTitle title={title} subtitle={subtitle} /> <ChartTitle title={title} subtitle={subtitle} />
<ChartJs <ChartJs options={options} data={data} type={'bar'} height={'156'} />
options={options}
data={data} type={'bar'} height={'156'}/>
</GrossMensalChartView> </GrossMensalChartView>
) )
} }

View File

@ -152,6 +152,12 @@ export default function clients({ clients, userName }) {
setLogo(e.target.files[0]) setLogo(e.target.files[0])
} }
console.table(clients.map(client => {
if (Number.parseInt(client.client_id) === 59641651) return client
return
}))
console.table(clients[417])
return ( return (
<div style={{ display: 'flex', flexDirection: 'column', width: '100%' }}> <div style={{ display: 'flex', flexDirection: 'column', width: '100%' }}>
<Snackbar <Snackbar

View File

@ -87,6 +87,8 @@ export default function Dashboard({grossAnualGraph, grossAnualYears, grossMensal
setLastDataBrutaAnual(`${parseFloat(lastDataAnual).toFixed(3)}`) setLastDataBrutaAnual(`${parseFloat(lastDataAnual).toFixed(3)}`)
}, []) }, [])
console.log(grossAnualGraph)
return ( return (
<DashboardView> <DashboardView>
<Head> <Head>
@ -195,9 +197,9 @@ 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
}).catch(res => {
// console.log(res)
}) })
.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

@ -91,6 +91,7 @@ export default function economy({userName, anual, years, brutaMensal, catLiv, cl
useEffect(() => { useEffect(() => {
getChartsWithUnity() getChartsWithUnity()
console.log(brutaMensal)
}, [unity]) }, [unity])
return ( return (

View File

@ -76,7 +76,7 @@ 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}, {"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" }]