add notification integration

This commit is contained in:
joseCorte-exe 2022-06-15 10:34:15 -03:00
parent 1d4c374d10
commit 95d33f1ccd
6 changed files with 185 additions and 107 deletions

View File

@ -171,7 +171,14 @@ function EnhancedTableHead(props: EnhancedTableProps) {
); );
} }
export default function ClientTable() { interface NotificationData {
title: string,
body: string,
users: string
deleted_at: Date,
}
export default function ClientTable({notifications}: any) {
const [order, setOrder] = useState<Order>('asc'); const [order, setOrder] = useState<Order>('asc');
const [orderBy, setOrderBy] = useState<keyof Data | string>('status'); const [orderBy, setOrderBy] = useState<keyof Data | string>('status');
const [selected, setSelected] = useState<readonly string[]>([]); const [selected, setSelected] = useState<readonly string[]>([]);
@ -190,7 +197,7 @@ export default function ClientTable() {
const handleSelectAllClick = (event: React.ChangeEvent<HTMLInputElement>) => { const handleSelectAllClick = (event: React.ChangeEvent<HTMLInputElement>) => {
if (event.target.checked) { if (event.target.checked) {
const newSelecteds = rows.map((n) => n.notification); const newSelecteds = notifications.map((n) => n.id.toString());
setSelected(newSelecteds); setSelected(newSelecteds);
return; return;
} }
@ -229,8 +236,7 @@ export default function ClientTable() {
const isSelected = (name: string) => selected.indexOf(name) !== -1; const isSelected = (name: string) => selected.indexOf(name) !== -1;
// Avoid a layout jump when reaching the last page with empty rows. // Avoid a layout jump when reaching the last page with empty rows.
const emptyRows = const emptyRows = page > 0 ? Math.max(0, (1 + page) * rowsPerPage - notifications.length) : 0;
page > 0 ? Math.max(0, (1 + page) * rowsPerPage - rows.length) : 0;
return ( return (
<ClientTableView> <ClientTableView>
@ -247,23 +253,23 @@ export default function ClientTable() {
orderBy={orderBy} orderBy={orderBy}
onSelectAllClick={handleSelectAllClick} onSelectAllClick={handleSelectAllClick}
onRequestSort={handleRequestSort} onRequestSort={handleRequestSort}
rowCount={rows.length} rowCount={notifications.length}
/> />
<TableBody> <TableBody>
{stableSort(rows, getComparator(order, orderBy)) {stableSort(notifications, getComparator(order, orderBy))
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage) .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map((row, index) => { .map((row, index) => {
const isItemSelected = isSelected(row.notification.toString()); const isItemSelected = isSelected(row.id.toString());
const labelId = `enhanced-table-checkbox-${index}`; const labelId = `enhanced-table-checkbox-${index}`;
return ( return (
<TableRow <TableRow
hover hover
onClick={(event) => handleClick(event, row.notification.toString())} onClick={(event) => handleClick(event, row.id.toString())}
role="checkbox" role="checkbox"
aria-checked={isItemSelected} aria-checked={isItemSelected}
tabIndex={-1} tabIndex={-1}
key={row.notification} key={index}
selected={isItemSelected} selected={isItemSelected}
> >
<TableCell padding="checkbox"> <TableCell padding="checkbox">
@ -281,10 +287,10 @@ export default function ClientTable() {
scope="row" scope="row"
padding="none" padding="none"
> >
{row.notification} {row.title}
</TableCell> </TableCell>
<TableCell align="left">{row.client}</TableCell> <TableCell align="left">{'copel'}</TableCell>
<TableCell align="left"><StyledStatus status={row.status==='enviada'? 'ativo' : row.status==='falhou'? 'inativo' : 'pendente'}>{row.status}</StyledStatus></TableCell> <TableCell align="left"><StyledStatus status={row.deleted_at===null? 'ativo' : 'inativo'}>{row.deleted_at===null? 'ativo' : 'inativo'}</StyledStatus></TableCell>
</TableRow> </TableRow>
); );
})} })}
@ -303,7 +309,7 @@ export default function ClientTable() {
<TablePagination <TablePagination
rowsPerPageOptions={[5, 10, 25]} rowsPerPageOptions={[5, 10, 25]}
component="div" component="div"
count={rows.length} count={notifications.length}
rowsPerPage={rowsPerPage} rowsPerPage={rowsPerPage}
page={page} page={page}
onPageChange={handleChangePage} onPageChange={handleChangePage}

View File

@ -4,7 +4,7 @@ import Router from 'next/router'
import { setCookie } from "nookies"; import { setCookie } from "nookies";
import { signInRequest } from "../services/auth"; import { signInRequest } from "../services/auth";
import api from "../services/api"; import { api } from "../services/api";
type UserType = { type UserType = {
name: string; name: string;
@ -40,6 +40,8 @@ export function AuthProvider({children}: {children: React.ReactNode}) {
maxAge: 60 * 60 * 1, // 1 hour maxAge: 60 * 60 * 1, // 1 hour
}) })
// setCookie(undefined, 'user-role', user.role)
api.defaults.headers['Authorization'] = `Bearer ${token}` api.defaults.headers['Authorization'] = `Bearer ${token}`
setUser(user) setUser(user)

View File

@ -1,29 +1,32 @@
import CheckBoxIcon from '@mui/icons-material/CheckBox'; import CheckBoxIcon from '@mui/icons-material/CheckBox';
import CheckBoxOutlineBlankIcon from '@mui/icons-material/CheckBoxOutlineBlank'; import CheckBoxOutlineBlankIcon from '@mui/icons-material/CheckBoxOutlineBlank';
import RadioButtonCheckedIcon from '@mui/icons-material/RadioButtonChecked';
import RadioButtonUncheckedIcon from '@mui/icons-material/RadioButtonUnchecked';
import Autocomplete from '@mui/material/Autocomplete'; import Autocomplete from '@mui/material/Autocomplete';
import Box from '@mui/material/Box'; import Box from '@mui/material/Box';
import Checkbox from '@mui/material/Checkbox'; import Checkbox from '@mui/material/Checkbox';
import FormControl from '@mui/material/FormControl'; import FormControl from '@mui/material/FormControl';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import Modal from '@mui/material/Modal'; import Modal from '@mui/material/Modal';
import Select, { SelectChangeEvent } from '@mui/material/Select';
import TextField from '@mui/material/TextField'; import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography'; import Typography from '@mui/material/Typography';
import Head from 'next/head' import Head from 'next/head'
import React from 'react' import React, { useState } from 'react'
import NotificationsTable from '../../../components/administrativeTables/NotificationsTable' import NotificationsTable from '../../../components/administrativeTables/NotificationsTable'
import BasicButton from '../../../components/buttons/basicButton/BasicButton';
import FaqButton1 from '../../../components/buttons/faqButton/FaqButton1'; import FaqButton1 from '../../../components/buttons/faqButton/FaqButton1';
import FaqButton2 from '../../../components/buttons/faqButton/FaqButton2'; import FaqButton2 from '../../../components/buttons/faqButton/FaqButton2';
import Header from '../../../components/header/Header' import Header from '../../../components/header/Header'
import PageTitle from '../../../components/pageTitle/PageTitle' import PageTitle from '../../../components/pageTitle/PageTitle'
import api from '../../../services/api'; import { api } from '../../../services/api';
import { FaqView } from '../../../styles/layouts/commonQuestions/FaqView' import { FaqView } from '../../../styles/layouts/commonQuestions/FaqView'
import { NotificationView } from './notificationView'
import Radio from '@mui/material/Radio';
import RadioGroup from '@mui/material/RadioGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import getAPIClient from '../../../services/ssrApi';
import { GetServerSideProps } from 'next';
import { parseCookies } from 'nookies';
import Notifications from '../../notifications';
import Snackbar from '@mui/material/Snackbar/Snackbar';
import Alert from '@mui/material/Alert/Alert';
const style = { const style = {
position: 'absolute' as const, position: 'absolute' as const,
@ -42,12 +45,37 @@ const style = {
const icon = <CheckBoxOutlineBlankIcon fontSize="small" />; const icon = <CheckBoxOutlineBlankIcon fontSize="small" />;
const checkedIcon = <CheckBoxIcon fontSize="small" />; const checkedIcon = <CheckBoxIcon fontSize="small" />;
export default function commonQuestions() { interface NotificationInterface {
title: string,
body: string,
users: object[]
}
export default function notification({clients, notifications}) {
const [notification, setNotification] = useState<NotificationInterface>({
title: '',
body: '',
users: []
})
const [open, setOpen] = useState<boolean>(false);
const [openSnackSuccess, setOpenSnackSuccess] = useState<boolean>(false);
const [openSnackError, setOpenSnackError] = useState<boolean>(false);
const [radiusValue, setRadiusValue] = useState<string>('all');
const [open, setOpen] = React.useState(false);
const handleOpen = () => setOpen(true); const handleOpen = () => setOpen(true);
const handleClose = () => setOpen(false); const handleClose = () => setOpen(false);
async function handleRegisterNewNotification({title, body, users}: NotificationInterface) {
await api.post('/notification', {
title,
body,
users
}).then(res => setOpenSnackSuccess(true)).catch(res => setOpenSnackError(true))
}
return ( return (
<FaqView> <FaqView>
<Head> <Head>
@ -61,79 +89,131 @@ export default function commonQuestions() {
</div> </div>
<Modal <Modal
open={open} open={open}
onClose={handleClose} onClose={handleClose}
aria-labelledby="modal-modal-title" aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description" aria-describedby="modal-modal-description"
> >
<Box sx={style}> <Box sx={style}>
<h1>Disparar Notificações</h1> <h1>Disparar Notificações</h1>
<Typography sx={{color:'gray', fontSize:12}}variant="h5" gutterBottom component="div"> <Typography sx={{color:'gray', fontSize:12}}variant="h5" gutterBottom component="div">
Pode ser que todas as notificaçõs demorem alguns minutos para estarem disponíveis</Typography> Pode ser que todas as notificaçõs demorem alguns minutos para estarem disponíveis</Typography>
<br /> <br />
<TextField id="outlined-basic" label="Título" sx={{width:700, ml:8}} variant="outlined" /> <br /><br /> <TextField id="outlined-basic" label="Título" sx={{width:700, ml:8}} onChange={(value) => {
setNotification({
...notification,
title: value.target.value
})
}} variant="outlined" /> <br /><br />
<TextField id="outlined-basic" label="Corpo/Conteúdo da notificação" sx={{width:700, ml:8}} onChange={(value) => {
setNotification({
...notification,
body: value.target.value
})
}} variant="outlined" /> <br /><br />
<Autocomplete
multiple
id="checkboxes-tags-demo"
options={top100Films}
disableCloseOnSelect
getOptionLabel={(option) => option.title}
renderOption={(props, option, { selected }) => (
<li {...props}>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
style={{ marginRight: 8 }}
checked={selected}
/>
{option.title}
</li>
)}
sx={{ml:8}}
style={{ width: 700 }}
renderInput={(params) => (
<TextField {...params} label="Corpo/Conteúdo da notificação" placeholder="Corpo/Conteúdo da notificação" />
)}
/>
<div> <div>
<Checkbox sx={{ml:7}} <FormControl>
icon={<RadioButtonUncheckedIcon />} <RadioGroup
checkedIcon={<RadioButtonCheckedIcon />} aria-labelledby="demo-radio-buttons-group-label"
/> defaultValue="female"
<Typography sx={{color:'#1976D2', fontSize:12, ml:12, mt:-3.7}} > name="radio-buttons-group"
Disparar para todos os clientes</Typography> >
<Checkbox sx={{ml:7}} <FormControlLabel value="all" control={<Radio />} checked={radiusValue==='all'? true : false}onChange={(value: React.ChangeEvent<HTMLInputElement>) => {
icon={<RadioButtonUncheckedIcon />} setRadiusValue(value.target.value)
checkedIcon={<RadioButtonCheckedIcon />} }} label="Disparar para todos os clientes" />
/> <FormControlLabel value="some" control={<Radio />} checked={radiusValue==='some'? true : false} onChange={(value: React.ChangeEvent<HTMLInputElement>) => {
<Typography sx={{color:'#1976D2', fontSize:12, ml:12, mt:-3.7}} > setRadiusValue(value.target.value)
Disparar somente para alguns clientes</Typography> }} label="Disparar somente para alguns clientes" />
</RadioGroup>
</FormControl>
</div> </div>
<FaqButton1 title='Cancelar' onClick={function (): void { {
throw new Error('Function not implemented.'); radiusValue === 'some'?
} } /> <Autocomplete
<FaqButton2 title='Salvar' onClick={function (): void { multiple
throw new Error('Function not implemented.'); id="checkboxes-tags-demo"
} } /> options={clients}
disableCloseOnSelect
onChange={(event: any, newValue: any) => {
setNotification({...notification, users: newValue.map((el) => {return {"user_id": el.id}})});
}}
getOptionLabel={(option) => option.name}
renderOption={(props, option, { selected }) => (
<li {...props}>
<Checkbox
icon={icon}
checkedIcon={checkedIcon}
style={{ marginRight: 8 }}
checked={selected}
value={option.name}
/>
{option.name}
</li>
)}
sx={{ml:8}}
style={{ width: 700 }}
renderInput={(params) => (
<TextField {...params} label="Clientes" placeholder="Selecionar clientes"/>
)}
/> :
null
}
<FaqButton1 title='Cancelar' onClick={() => {console.log()}} />
<FaqButton2 title='Salvar' onClick={() => {
handleRegisterNewNotification(notification)
}} />
</Box> </Box>
</Modal> </Modal>
<NotificationsTable /> <NotificationsTable notifications={notifications}/>
<Snackbar open={openSnackSuccess} autoHideDuration={6000} onClose={handleClose}>
<Alert onClose={handleClose} severity="success" sx={{ width: '100%' }}>
This is a success message!
</Alert>
</Snackbar>
<Snackbar open={openSnackError} autoHideDuration={6000} onClose={handleClose}>
<Alert onClose={handleClose} severity="error" sx={{ width: '100%' }}>
This is a success message!
</Alert>
</Snackbar>
</FaqView> </FaqView>
) )
} }
const top100Films = [ export const getServerSideProps: GetServerSideProps = async (ctx) => {
{ title: 'The Shawshank Redemption', year: 1994 }, const apiClient = getAPIClient(ctx)
{ title: 'The Godfather', year: 1972 }, const { ['@smartAuth-token']: token } = parseCookies(ctx)
{ title: 'The Godfather: Part II', year: 1974 },
{ title: 'The Dark Knight', year: 2008 }, let clients = [];
{ title: '12 Angry Men', year: 1957 }, let notifications = [];
{ title: "Schindler's List", year: 1993 },
{ title: 'Pulp Fiction', year: 1994 }, await apiClient.get('/user').then(res => {
{ clients = res.data
title: 'The Lord of the Rings: The Return of the King', }).catch(res => {
year: 2003, console.log(res)
}, })
];
await apiClient.get('/notification').then(res => {
notifications = res.data
}).catch(res => {
console.log(res)
})
if (!token) {
return {
redirect: {
destination: '/',
permanent: false
}
}
}
return {
props: {
clients,
notifications
}
}
}

View File

@ -3,7 +3,7 @@ import styled from 'styled-components'
export const NotificationView = styled.nav` export const NotificationView = styled.nav`
display: flex; display: flex;
align-items: center; align-items: center;
flex-direction: column; flex-direction: column;

View File

@ -1,4 +1,4 @@
import api from "./api"; import { api } from "./api";
export const TOKEN_KEY = "@smartAuth-token"; export const TOKEN_KEY = "@smartAuth-token";
@ -15,7 +15,8 @@ type UserObjectType = {
name: string; name: string;
email: string; email: string;
client_id: number client_id: number
id: number id: number,
role: number
} }
export async function signInRequest(data: SignInRequestData) { export async function signInRequest(data: SignInRequestData) {
@ -30,7 +31,8 @@ export async function signInRequest(data: SignInRequestData) {
name: res.data.user.name, name: res.data.user.name,
email: res.data.user.email, email: res.data.user.email,
client_id: res.data.user.client_id, client_id: res.data.user.client_id,
id: res.data.user.id id: res.data.user.id,
role: res.data.user.roles.role_id
} }
token = res.data.token token = res.data.token
}).catch(res => { }).catch(res => {
@ -38,13 +40,8 @@ export async function signInRequest(data: SignInRequestData) {
}) })
return { return {
token: token, token,
user: { user
name: user.name,
email: user.email,
client_id: user.client_id,
id: user.id
}
} }
} }
@ -57,18 +54,14 @@ export default async function recoverUserInformation(id) {
name: res.data.user.name, name: res.data.user.name,
email: res.data.user.email, email: res.data.user.email,
client_id: res.data.user.client_id, client_id: res.data.user.client_id,
id: res.data.user.id id: res.data.user.id,
role: res.data.user.roles.role_id
} }
}).catch(res => { }).catch(res => {
console.log(res) console.log(res)
}) })
return { return {
user: { user
name: user?.name,
email: user?.email,
client_id: user?.client_id,
id: user?.id
}
} }
} }

View File

@ -10,16 +10,13 @@ export default function getAPIClient(ctx?: Pick<next.NextPageContext, 'req'> | {
req: express.Request; req: express.Request;
} | null | undefined) { } | null | undefined) {
const { '@smartAuth-token': token } = parseCookies() const { '@smartAuth-token': token } = parseCookies(ctx)
const api = axios.create({ const api = axios.create({
baseURL: "https://smart-energia-api.herokuapp.com/api", baseURL: "https://smart-energia-api.herokuapp.com/api",
}); });
api.interceptors.request.use(config => { api.interceptors.request.use(config => {
// console.log(config)
// config.headers = {Authorization: `Bearer ${token}`};
return config; return config;
}, },
); );