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

View File

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

View File

@ -1,29 +1,32 @@
import CheckBoxIcon from '@mui/icons-material/CheckBox';
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 Box from '@mui/material/Box';
import Checkbox from '@mui/material/Checkbox';
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 Select, { SelectChangeEvent } from '@mui/material/Select';
import TextField from '@mui/material/TextField';
import Typography from '@mui/material/Typography';
import Head from 'next/head'
import React from 'react'
import React, { useState } from 'react'
import NotificationsTable from '../../../components/administrativeTables/NotificationsTable'
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 PageTitle from '../../../components/pageTitle/PageTitle'
import api from '../../../services/api';
import { api } from '../../../services/api';
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 = {
position: 'absolute' as const,
@ -42,12 +45,37 @@ const style = {
const icon = <CheckBoxOutlineBlankIcon 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 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 (
<FaqView>
<Head>
@ -61,79 +89,131 @@ export default function commonQuestions() {
</div>
<Modal
open={open}
onClose={handleClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
open={open}
onClose={handleClose}
aria-labelledby="modal-modal-title"
aria-describedby="modal-modal-description"
>
<Box sx={style}>
<h1>Disparar Notificações</h1>
<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>
<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>
<Checkbox sx={{ml:7}}
icon={<RadioButtonUncheckedIcon />}
checkedIcon={<RadioButtonCheckedIcon />}
/>
<Typography sx={{color:'#1976D2', fontSize:12, ml:12, mt:-3.7}} >
Disparar para todos os clientes</Typography>
<Checkbox sx={{ml:7}}
icon={<RadioButtonUncheckedIcon />}
checkedIcon={<RadioButtonCheckedIcon />}
/>
<Typography sx={{color:'#1976D2', fontSize:12, ml:12, mt:-3.7}} >
Disparar somente para alguns clientes</Typography>
<FormControl>
<RadioGroup
aria-labelledby="demo-radio-buttons-group-label"
defaultValue="female"
name="radio-buttons-group"
>
<FormControlLabel value="all" control={<Radio />} checked={radiusValue==='all'? true : false}onChange={(value: React.ChangeEvent<HTMLInputElement>) => {
setRadiusValue(value.target.value)
}} label="Disparar para todos os clientes" />
<FormControlLabel value="some" control={<Radio />} checked={radiusValue==='some'? true : false} onChange={(value: React.ChangeEvent<HTMLInputElement>) => {
setRadiusValue(value.target.value)
}} label="Disparar somente para alguns clientes" />
</RadioGroup>
</FormControl>
</div>
<FaqButton1 title='Cancelar' onClick={function (): void {
throw new Error('Function not implemented.');
} } />
<FaqButton2 title='Salvar' onClick={function (): void {
throw new Error('Function not implemented.');
} } />
{
radiusValue === 'some'?
<Autocomplete
multiple
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>
</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>
)
}
const top100Films = [
{ title: 'The Shawshank Redemption', year: 1994 },
{ title: 'The Godfather', year: 1972 },
{ title: 'The Godfather: Part II', year: 1974 },
{ title: 'The Dark Knight', year: 2008 },
{ title: '12 Angry Men', year: 1957 },
{ title: "Schindler's List", year: 1993 },
{ title: 'Pulp Fiction', year: 1994 },
{
title: 'The Lord of the Rings: The Return of the King',
year: 2003,
},
];
export const getServerSideProps: GetServerSideProps = async (ctx) => {
const apiClient = getAPIClient(ctx)
const { ['@smartAuth-token']: token } = parseCookies(ctx)
let clients = [];
let notifications = [];
await apiClient.get('/user').then(res => {
clients = res.data
}).catch(res => {
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`
display: flex;
display: flex;
align-items: center;
flex-direction: column;

View File

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

View File

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