From 786c95d774c02db582e95aa1030eaaf36cc56b3b Mon Sep 17 00:00:00 2001 From: Luis Felipe Risch <lfr20@inf.ufpr.br> Date: Tue, 6 Apr 2021 11:44:01 -0300 Subject: [PATCH] Optmizing code --- src/Admin/Pages/Pages/SubPages/Activity.js | 22 +- .../Pages/Pages/SubPages/AproveTeacher.js | 1510 ++++++++--------- src/Admin/Pages/Pages/SubPages/Collections.js | 10 +- .../Pages/SubPages/CommunityQuestions.js | 16 +- .../Pages/SubPages/EducationalObjects.js | 440 ++--- .../Pages/Pages/SubPages/Institutions.js | 2 +- src/Admin/Pages/Pages/SubPages/Languages.js | 780 ++++----- .../Pages/Pages/SubPages/NoteVariables.js | 621 +++---- src/Admin/Pages/Pages/SubPages/Permissions.js | 839 +++++---- src/Admin/Pages/Pages/SubPages/Questions.js | 904 +++++----- src/Admin/Pages/Pages/SubPages/Rating.js | 776 ++++----- src/Admin/Pages/Pages/SubPages/Users.js | 1069 ++++++------ 12 files changed, 3115 insertions(+), 3874 deletions(-) diff --git a/src/Admin/Pages/Pages/SubPages/Activity.js b/src/Admin/Pages/Pages/SubPages/Activity.js index e9eb9577..2c0a137f 100644 --- a/src/Admin/Pages/Pages/SubPages/Activity.js +++ b/src/Admin/Pages/Pages/SubPages/Activity.js @@ -124,29 +124,11 @@ const Activity = () => { .toString(); }; - //getting data from server - useEffect(() => { - getRequest( - Url("activities", "", `${currPage}`, "DESC"), - (data, header) => { - const arrData = [...data]; - setItems(arrData.concat(ADD_ONE_LENGHT)); - setIsLoaded(true); - setError(false); - }, - (error) => { - HandleSnack("Erro ao carregar os dados", true, "warning", "#FA8072"); - setIsLoaded(true); - setError(true); - } - ) - }, []); - const buildUrl = (privacyOpt) => { if (privacyOpt) - return Url("/activities", `"privacy" : "${privacyOpt}"`, currPage, "DESC") + return Url("activities", `"privacy" : "${privacyOpt}"`, currPage, "DESC") - return Url("/activities", "", currPage, "DESC") + return Url("activities", "", currPage, "DESC") } useEffect(() => { diff --git a/src/Admin/Pages/Pages/SubPages/AproveTeacher.js b/src/Admin/Pages/Pages/SubPages/AproveTeacher.js index df9cbfff..f6517d1e 100644 --- a/src/Admin/Pages/Pages/SubPages/AproveTeacher.js +++ b/src/Admin/Pages/Pages/SubPages/AproveTeacher.js @@ -25,8 +25,8 @@ import { Url } from "../../../Filters"; import { Store } from "../../../../Store"; import LoadingSpinner from "../../../../Components/LoadingSpinner"; import { - getRequest, - postRequest, + getRequest, + postRequest, } from "../../../../Components/HelperFunctions/getAxiosConfig"; //imports from material ui import { withStyles } from "@material-ui/core/styles"; @@ -53,853 +53,721 @@ import { apiDomain } from '../../../../env'; import noAvatar from "../../../../img/default_profile.png"; import EmailRoundedIcon from '@material-ui/icons/EmailRounded'; -let currPage = 0; -let currStateFilter = "requested"; -let currNameFilter = ""; -let currEmailFilter = ""; - const StyledTableCell = withStyles((theme) => ({ - head: { - backgroundColor: theme.palette.common.black, - color: theme.palette.common.white, - }, - body: { - fontSize: 14, - }, + head: { + backgroundColor: theme.palette.common.black, + color: theme.palette.common.white, + }, + body: { + fontSize: 14, + }, }))(TableCell); const StyledTableRow = withStyles((theme) => ({ - root: { - "&:nth-of-type(odd)": { - backgroundColor: theme.palette.action.hover, - }, + root: { + "&:nth-of-type(odd)": { + backgroundColor: theme.palette.action.hover, }, + }, }))(TableRow); const AproveTeacher = () => { - const { state } = useContext(Store); - const WINDOW_WIDTH = window.innerWidth; - - const ADD_ONE_LENGHT = [""]; - const TOP_LABELS = [ - "ESTADO DO PEDIDO", - "ID", - "NOME", - "EMAIL", - "PEDIDO EM(MM/DD/YYYY)", - "VISUALIZAR", - "AÇÕES", - ]; //Labels from Table - - const [error, setError] = useState(null); //Necessary to consult the API, catch errors - const [isLoaded, setIsLoaded] = useState(false); //Necessary to consult the API, wait until complete - const [items, setItems] = useState([]); //Necessary to consult the API, data - - const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false); //controlls the state of loadind more data - const [isUpdating, setIsUpdating] = useState(false); //controlls the state of updating data - - const [showFilter, setShowFilter] = useState(false); - - const [option, setOption] = useState("requested"); - const [name, setName] = useState(""); - const [email, setEmail] = useState(""); - - const [snackInfo, setSnackInfo] = useState({ - message: "", - icon: "", - open: false, - color: "", + const { state } = useContext(Store); + const WINDOW_WIDTH = window.innerWidth; + + const ADD_ONE_LENGHT = [""]; + const TOP_LABELS = [ + "ESTADO DO PEDIDO", + "ID", + "NOME", + "EMAIL", + "PEDIDO EM(MM/DD/YYYY)", + "VISUALIZAR", + "AÇÕES", + ]; //Labels from Table + + const [error, setError] = useState(null); //Necessary to consult the API, catch errors + const [isLoaded, setIsLoaded] = useState(false); //Necessary to consult the API, wait until complete + const [items, setItems] = useState([]); //Necessary to consult the API, data + + const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false); //controlls the state of loadind more data + const [isUpdating, setIsUpdating] = useState(false); //controlls the state of updating data + const [currPage, setCurrPage] = useState(0) + const [showFilter, setShowFilter] = useState(false); + + const [option, setOption] = useState("requested"); + const [name, setName] = useState(""); + const [nameValue, setNameValue] = useState("") + const [email, setEmail] = useState(""); + const [emailValue, setEmailValue] = useState("") + + const [snackInfo, setSnackInfo] = useState({ + message: "", + icon: "", + open: false, + color: "", + }); + + const StateOptions = [ + { name: "requested", value: "Pendente" }, + { name: "accepted", value: "Aceito" }, + { name: "rejected", value: "Rejeitado" }, + ]; + + //handle snack info + const HandleSnack = (message, state, icon, color) => { + setSnackInfo({ + message: message, + icon: icon, + open: state, + color: color, }); - - const StateOptions = [ - { id: "requested", name: "Pendente" }, - { id: "accepted", name: "Aceito" }, - { id: "rejected", name: "Rejeitado" }, - ]; - - //handle snack info - const HandleSnack = (message, state, icon, color) => { - setSnackInfo({ - message: message, - icon: icon, - open: state, - color: color, - }); - }; - - const CheckUserPermission = () => { - let canUserEdit = false; - - if (state.userIsLoggedIn) { - const roles = [...state.currentUser.roles]; - for (let i = 0; i < roles.length; i++) - if (roles[i].name === "admin" || roles[i].name === "editor") - canUserEdit = true; - } else { - canUserEdit = false; - } - - return canUserEdit; - }; - - //handle load more items - const LoadMoreItens = async (api) => { - setIsLoadingMoreItems(true); - getRequest( - api, - (data, header) => { - const arrData = [...data]; - if (arrData.length === 0) { - HandleSnack( - "Não há mais dados para serem carregados", - true, - "warning", - "#FFC125" - ); - } else { - const arrItems = [...items]; - arrItems.pop(); //Deleting the last position, that was used to display the button of load more items - const arrResult = arrItems.concat(arrData); - setItems(arrResult.concat(ADD_ONE_LENGHT)); - } - setIsLoadingMoreItems(false); - }, - (error) => { - HandleSnack("Erro ao carregar os dados", true, "warning", "#FA8072"); - setIsLoadingMoreItems(false); - } + }; + + const CheckUserPermission = () => { + let canUserEdit = false; + + if (state.userIsLoggedIn) { + const roles = [...state.currentUser.roles]; + for (let i = 0; i < roles.length; i++) + if (roles[i].name === "admin" || roles[i].name === "editor") + canUserEdit = true; + } else { + canUserEdit = false; + } + + return canUserEdit; + }; + + const handleChange = (e, type) => { + const value = e.target.value; + setOption(value); + }; + + const NameHandler = (e) => { + setNameValue(e.target.value) + }; + + const EmailHandler = (e) => { + setEmailValue(e.target.value) + }; + + const ComplaintStatus = (status) => { + switch (status) { + case "accepted": + return ( + <Paper + style={{ + textAlign: "center", + padding: "0.5em", + backgroundColor: "#228B22", + fontWeight: "500", + color: "#FFFAFA", + }} + > + ACEITO + </Paper> ); - }; - - // handle update list data - const UpdateHandler = async (api) => { - setIsUpdating(true); - getRequest( - api, - (data, header) => { - HandleSnack( - "A lista de dados foi atualizada", - true, - "success", - "#228B22" - ); - const arrData = [...data]; - setItems(arrData.concat(ADD_ONE_LENGHT)); - setIsUpdating(false); - }, - (error) => { - HandleSnack("Erro ao carregar os dados", true, "warning", "#FA8072"); - setIsUpdating(false); - } + case "requested": + return ( + <Paper + style={{ + textAlign: "center", + padding: "0.5em", + backgroundColor: "#FF8C00", + fontWeight: "500", + color: "#FFFAFA", + }} + > + PENDENTE + </Paper> ); - }; - - const handleChange = (e, type) => { - const value = e.target.value; - setOption(value); - }; - - const ApplyFilter = (id, type) => { - currStateFilter = id; - currPage = 0; - getRequest( - Url( - "users", - `"submitter_request":"${currStateFilter}","name":"${currNameFilter}","email":"${email}"`, - `${currPage}`, - "DESC" - ), - (data, header) => { - const arrData = [...data]; - setItems(arrData.concat(ADD_ONE_LENGHT)); - HandleSnack("Filtro aplicado com sucesso", true, "success", "#228B22"); - setIsLoaded(true); - }, - (error) => { - HandleSnack("Erro ao carregar os dados", true, "warning", "#FA8072"); - setIsLoaded(true); - } + case "rejected": + return ( + <Paper + style={{ + textAlign: "center", + padding: "0.5em", + backgroundColor: "#FA8072", + fontWeight: "500", + color: "#FFFAFA", + }} + > + Rejeitado + </Paper> ); - }; - - const NameHandler = (e) => { - currPage = 0; - currNameFilter = e.target.value; - setName(currNameFilter); - getRequest( - Url( - "users", - `"submitter_request":"${currStateFilter}","name":"${currNameFilter}","email":"${email}"`, - `${currPage}`, - "DESC" - ), - (data, header) => { - const arrData = [...data]; - setItems(arrData.concat(ADD_ONE_LENGHT)); - HandleSnack("Filtro aplicado com sucesso", true, "success", "#228B22"); - setIsLoaded(true); - }, - (error) => { - HandleSnack("Erro ao carregar os dados", true, "warning", "#FA8072"); - setIsLoaded(true); - } - ); - }; - - const EmailHandler = (e) => { - currPage = 0; - currEmailFilter = e.target.value; - setEmail(currEmailFilter); - getRequest( - Url( - "users", - `"submitter_request":"${currStateFilter}","name":"${currNameFilter}","email":"${currEmailFilter}"`, - `${currPage}`, - "DESC" - ), - (data, header) => { - const arrData = [...data]; - setItems(arrData.concat(ADD_ONE_LENGHT)); - HandleSnack("Filtro aplicado com sucesso", true, "success", "#228B22"); - setIsLoaded(true); - }, - (error) => { - HandleSnack("Erro ao carregar os dados", true, "warning", "#FA8072"); - setIsLoaded(true); - } + default: + return ( + <Paper + style={{ + textAlign: "center", + padding: "0.5em", + backgroundColor: "#797D7F ", + fontWeight: "500", + color: "#FFFAFA", + }} + > + Não requisitado + </Paper> ); + } + }; + + const DisplayDate = (date) => { + const convertedData = moment.utc(date); + return moment(convertedData) + .format("LLL") + .toString(); + }; + + const handleAprove = (userId, userName) => { + const url = `/users/${userId}/add_teacher`; + const body = { + approves: true, }; - - const ComplaintStatus = (status) => { - switch (status) { - case "accepted": - return ( - <Paper - style={{ - textAlign: "center", - padding: "0.5em", - backgroundColor: "#228B22", - fontWeight: "500", - color: "#FFFAFA", - }} - > - ACEITO - </Paper> - ); - case "requested": - return ( - <Paper - style={{ - textAlign: "center", - padding: "0.5em", - backgroundColor: "#FF8C00", - fontWeight: "500", - color: "#FFFAFA", - }} - > - PENDENTE - </Paper> - ); - case "rejected": - return ( - <Paper - style={{ - textAlign: "center", - padding: "0.5em", - backgroundColor: "#FA8072", - fontWeight: "500", - color: "#FFFAFA", - }} - > - Rejeitado - </Paper> - ); - default: - return ( - <Paper - style={{ - textAlign: "center", - padding: "0.5em", - backgroundColor: "#797D7F ", - fontWeight: "500", - color: "#FFFAFA", - }} - > - Não requisitado - </Paper> - ); + postRequest( + url, + body, + (data) => { + if (data.errors) HandleSnack("Erro!", true, "warning", "#FA8072"); + else { + HandleSnack( + `${userName} aceito como professor!`, + true, + "success", + "#228B22" + ); + setCurrPage(0) } + }, + (error) => { + HandleSnack("Erro!", true, "warning", "#FA8072"); + } + ); + }; + + const handleReject = (userId, userName) => { + const url = `/users/${userId}/add_teacher`; + const body = { + approves: false, }; - - const DisplayDate = (date) => { - const convertedData = moment.utc(date); - return moment(convertedData) - .format("LLL") - .toString(); - }; - - const handleAprove = (userId, userName) => { - const url = `/users/${userId}/add_teacher`; - const body = { - approves: true, - }; - postRequest( - url, - body, - (data) => { - if (data.errors) HandleSnack("Erro!", true, "warning", "#FA8072"); - else { - HandleSnack( - `${userName} aceito como professor!`, - true, - "success", - "#228B22" - ); - currPage = 0; - UpdateHandler( - Url( - "users", - `"submitter_request":"${currStateFilter}","name":"${currNameFilter}","email":"${currEmailFilter}"`, - `${currPage}`, - "DESC" - ) - ); - } - }, - (error) => { - HandleSnack("Erro!", true, "warning", "#FA8072"); - } - ); - }; - - const handleReject = (userId, userName) => { - const url = `/users/${userId}/add_teacher`; - const body = { - approves: false, - }; - postRequest( - url, - body, - (data) => { - if (data.errors) HandleSnack("Erro!", true, "warning", "#FA8072"); - else { - HandleSnack( - `${userName} rejeitado como professor!`, - true, - "success", - "#228B22" - ); - currPage = 0; - UpdateHandler( - Url( - "users", - `"submitter_request":"${currStateFilter}","name":"${currNameFilter}","email":"${currEmailFilter}"`, - `${currPage}`, - "DESC" - ) - ); - } - }, - (error) => { - HandleSnack("Erro!", true, "warning", "#FA8072"); + postRequest( + url, + body, + (data) => { + if (data.errors) HandleSnack("Erro!", true, "warning", "#FA8072"); + else { + HandleSnack( + `${userName} rejeitado como professor!`, + true, + "success", + "#228B22" + ); + setCurrPage(0) + } + }, + (error) => { + HandleSnack("Erro!", true, "warning", "#FA8072"); + } + ); + }; + + const buildUrl = (email, submitter_request, name) => { + if (email && submitter_request && name) + return Url("users", `"submitter_request" : "${submitter_request}", "email" : "${email}", "name" : "${name}"`, currPage, "DESC") + + else if (email && name) + return Url("users", `"email" : "${email}", "name" : "${name}"`, currPage, "DESC") + else if (email && submitter_request) + return Url("users", `"email" : "${email}", "submitter_request" : "${submitter_request}"`, currPage, "DESC") + else if (name && submitter_request) + return Url("users", `"name" : "${name}", "submitter_request" : "${submitter_request}"`, currPage, "DESC") + + else if (email) + return Url("users", `"email" : "${email}"`, currPage, "DESC") + else if (submitter_request) + return Url("users", `"submitter_request" : "${submitter_request}"`, currPage, "DESC") + else if (name) + return Url("users", `"name" : ${name}`, currPage, "DESC") + else + return Url("users", "", currPage, "DESC") + } + + useEffect(() => { + if (currPage === 0) + setIsLoaded(false) + else + setIsLoadingMoreItems(true) + getRequest( + buildUrl(email, option, name), + (data, header) => { + const arrData = [...data] + if (arrData.length === 0) { + HandleSnack('Não há mais dados para serem carregados', true, 'warning', '#FFC125') + } else { + const arrItems = [...items] + if (currPage === 0) { + setItems(arrData.concat(ADD_ONE_LENGHT)) + } + else { + arrItems.pop(); //Deleting the last position, that was used to display the button of load more items + const arrResult = arrItems.concat(arrData) + setItems(arrResult.concat(ADD_ONE_LENGHT)) + } + } + setIsLoaded(true) + setIsLoadingMoreItems(false) + }, + (error) => { + HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') + setIsLoadingMoreItems(false) + setIsLoaded(true) + setError(true) + } + ) + }, [currPage, option, email, name]) + + useEffect(() => { + setOption("requested") + setName("") + setNameValue("") + setEmail("") + setEmailValue("") + }, [showFilter]) + + if (error) { + return <div>Error: {error.message}</div>; + } else if (!isLoaded) { + return <LoadingSpinner text="Carregando..." />; + } else if (CheckUserPermission()) { + if (WINDOW_WIDTH <= 1130) { + return ( + <> + <SnackBar + severity={snackInfo.icon} + text={snackInfo.message} + snackbarOpen={snackInfo.open} + color={snackInfo.color} + handleClose={() => + setSnackInfo({ + message: "", + icon: "", + open: false, + color: "", + }) } - ); - }; + /> - //getting data from server - useEffect(() => { - getRequest( - Url( - "users", - `"submitter_request":"${currStateFilter}","name":"${currNameFilter}","email":"${currEmailFilter}"`, - `${currPage}`, - "DESC" - ), - (data, header) => { - const arrData = [...data]; - setItems(arrData.concat(ADD_ONE_LENGHT)); - setIsLoaded(true); - setError(false); - }, - (error) => { - HandleSnack("Erro ao carregar os dados", true, "warning", "#FA8072"); - setIsLoaded(true); - setError(true); - } - ); - }, []); - - if (error) { - return <div>Error: {error.message}</div>; - } else if (!isLoaded) { - return <LoadingSpinner text="Carregando..." />; - } else if (CheckUserPermission()) { - if (WINDOW_WIDTH <= 1075) { - return ( - <> - <SnackBar - severity={snackInfo.icon} - text={snackInfo.message} - snackbarOpen={snackInfo.open} - color={snackInfo.color} - handleClose={() => - setSnackInfo({ - message: "", - icon: "", - open: false, - color: "", - }) - } - /> - - <Paper style={{ padding: "1em" }}> - <Grid container spacing={3} direction="row" alignItems="center"> - <Grid item xs={12}> - <Typography variant="h4"> - Lista de pedidos para professores + <Paper style={{ padding: "1em" }}> + <Grid container spacing={3} direction="row" alignItems="center"> + <Grid item xs={12}> + <Typography variant="h4"> + Lista de pedidos para professores </Typography> - </Grid> - - <Grid item xs={12}> - <Grid container justify="flex-start" spacing={3}> - <Grid item> - <Button - variant="contained" - color="secondary" - disabled={isUpdating} - onClick={() => { - currPage = 0; - UpdateHandler( - Url( - "users", - `"submitter_request":"${currStateFilter}","name":"${currNameFilter}","email":"${currEmailFilter}"`, - `${currPage}`, - "DESC" - ) - ); - }} - startIcon={<UpdateRoundedIcon />} - > - {isUpdating ? ( - <CircularProgress size={24} /> - ) : ( - "Atualizar" - )} - </Button> - </Grid> - <Grid item> - <Button - variant="contained" - color="secondary" - onClick={() => { - setShowFilter(!showFilter); - }} - startIcon={<FilterListRoundedIcon />} - > - Filtrar + </Grid> + + <Grid item xs={12}> + <Grid container justify="flex-start" spacing={3}> + <Grid item> + <Button + variant="contained" + color="secondary" + disabled={isUpdating} + onClick={() => { + setCurrPage(0) + }} + startIcon={<UpdateRoundedIcon />} + > + {isUpdating ? ( + <CircularProgress size={24} /> + ) : ( + "Atualizar" + )} + </Button> + </Grid> + <Grid item> + <Button + variant="contained" + color="secondary" + onClick={() => { + setShowFilter(!showFilter); + }} + startIcon={<FilterListRoundedIcon />} + > + Filtrar </Button> - </Grid> - </Grid> - </Grid> - </Grid> - - {showFilter ? ( - <Grid - container - direction="row" - justify="space-between" - alignItems="center" - alignContent="flex-end" - spacing={3} - xs={12} + </Grid> + </Grid> + </Grid> + </Grid> + + {showFilter ? ( + <Grid + container + direction="row" + justify="space-between" + alignItems="center" + alignContent="flex-end" + spacing={3} + xs={12} + > + <Grid item> + <TextField + select + label="Estado" + value={option ? option : ""} + onChange={handleChange} + helperText="Por favor, selecione uma das opções" + > + {StateOptions.map((option, index) => ( + <MenuItem + key={option.value} + value={option.name} + name={option.value} + > + {option.value} + </MenuItem> + ))} + </TextField> + </Grid> + <Grid item> + <TextField + label="Nome" + onChange={NameHandler} + value={nameValue} + onBlur={(event) => { setName(event.target.value) }} + helperText="Retire o foco do campo de texto ao terminar de digitar" + /> + </Grid> + <Grid item> + <TextField + label="Email" + onChange={EmailHandler} + value={emailValue} + onBlur={(event) => { setEmail(event.target.value) }} + helperText="Retire o foco do campo de texto ao terminar de digitar" + /> + </Grid> + </Grid> + ) : null} + </Paper> + + <div style={{ height: "2em" }}></div> + + {items.map((row, index) => + index === items.length - 1 ? ( + <StyledDivButton> + <Button + key={index} + color="primary" + variant="text" + // disabled={isLoadingMoreItems} + startIcon={<AddRoundedIcon />} + disabled={isLoadingMoreItems} + onClick={() => { + setCurrPage(currPage + 1) + }} + > + {isLoadingMoreItems ? ( + <CircularProgress size={24} /> + ) : ( + "Carregar mais itens" + )} + </Button> + </StyledDivButton> + ) : ( + <> + <MobileList + key={index} + title={row.name} + subtitle={row.id} + backColor={"#00bcd4"} + avatar={ + <img + src={row.avatar ? apiDomain + row.avatar : noAvatar} + alt="user avatar" + style={{ + height: "100%", + width: "100%", + borderRadius: "50%", + }} + /> + } + href={`/admin/user/${row.id}`} + reset={() => { + + }} + data={[ + { + title: "Email", + subtitle: row.email ? + <Link to={`/admin/sendEmail/${row.email}`} style={{ textDecoration: 'none' }}> + <Button + variant='text' + color='primary' + startIcon={<EmailRoundedIcon />} > - <Grid item> - <TextField - select - label="Estado" - value={option ? option : ""} - onChange={handleChange} - helperText="Por favor, selecione uma das opções" - > - {StateOptions.map((option, index) => ( - <MenuItem - key={option.id} - value={option.name} - name={option.id} - onClick={() => - ApplyFilter(option.id, "submitter_request") - } - > - {option.name} - </MenuItem> - ))} - </TextField> - </Grid> - <Grid item> - <TextField label="Nome" onChange={NameHandler} value={name} /> - </Grid> - <Grid item> - <TextField - label="Email" - onChange={EmailHandler} - value={email} - /> - </Grid> - </Grid> - ) : null} - </Paper> - - <div style={{ height: "2em" }}></div> - - {items.map((row, index) => - index === items.length - 1 ? ( - <StyledDivButton> - <Button - key={index} - color="primary" - variant="text" - // disabled={isLoadingMoreItems} - startIcon={<AddRoundedIcon />} - disabled={isLoadingMoreItems} - onClick={() => { - currPage++; - LoadMoreItens( - Url( - "users", - `"submitter_request":"${currStateFilter}","name":"${currNameFilter}","email":"${currEmailFilter}"`, - `${currPage}`, - "DESC" - ) - ); - }} - > - {isLoadingMoreItems ? ( - <CircularProgress size={24} /> - ) : ( - "Carregar mais itens" - )} - </Button> - </StyledDivButton> - ) : ( - <> - <MobileList - key={index} - title={row.name} - subtitle={row.id} - backColor={"#00bcd4"} - avatar={ - <img - src={row.avatar ? apiDomain + row.avatar : noAvatar} - alt="user avatar" - style={{ - height: "100%", - width: "100%", - borderRadius: "50%", - }} - /> - } - href={`/admin/user/${row.id}`} - reset={() => { - currPage = 0; - currNameFilter = ""; - currEmailFilter = ""; - }} - data={[ - { - title: "Email", - subtitle: row.email ? - <Link to={`/admin/sendEmail/${row.email}`} style={{ textDecoration: 'none' }}> - <Button - variant='text' - color='primary' - startIcon={<EmailRoundedIcon />} - > - {row.email} - </Button> - </Link> : null - - }, - { - title: "Pedido em", - subtitle: DisplayDate(row.created_at), - }, - { - title: "Situação do pedido", - subtitle: ComplaintStatus(row.submitter_request), - }, - { - title: "Ações rápidas", - subtitle: <> - <Button - variant="contained" - color="secondary" - style={{ width: "100%" }} - disabled={ - row.submitter_request === "requested" ? false : true - } - startIcon={ - <CloseRoundedIcon style={{ fill: "#FFFAFA" }} /> - } - onClick={() => { - handleReject(row.id, row.name); - }} - > - Recusar + {row.email} + </Button> + </Link> : null + + }, + { + title: "Pedido em", + subtitle: DisplayDate(row.created_at), + }, + { + title: "Situação do pedido", + subtitle: ComplaintStatus(row.submitter_request), + }, + { + title: "Ações rápidas", + subtitle: <> + <Button + variant="contained" + color="secondary" + style={{ width: "100%" }} + disabled={ + row.submitter_request === "requested" ? false : true + } + startIcon={ + <CloseRoundedIcon style={{ fill: "#FFFAFA" }} /> + } + onClick={() => { + handleReject(row.id, row.name); + }} + > + Recusar </Button> - <div style={{ height: "0.5em" }} /> - <Button - variant="contained" - color="primary" - style={{ width: "100%" }} - disabled={ - row.submitter_request === "requested" ? false : true - } - startIcon={ - <CheckRoundedIcon style={{ fill: "#FFFAFA" }} /> - } - onClick={() => { - handleAprove(row.id, row.name); - }} - > - Aceitar + <div style={{ height: "0.5em" }} /> + <Button + variant="contained" + color="primary" + style={{ width: "100%" }} + disabled={ + row.submitter_request === "requested" ? false : true + } + startIcon={ + <CheckRoundedIcon style={{ fill: "#FFFAFA" }} /> + } + onClick={() => { + handleAprove(row.id, row.name); + }} + > + Aceitar </Button> - </> - } - ]} - /> - <div style={{ height: "0.5em" }} /> - </> - ) - )} + </> + } + ]} + /> + <div style={{ height: "0.5em" }} /> </> - ); - } else { - return ( - <> - <SnackBar - severity={snackInfo.icon} - text={snackInfo.message} - snackbarOpen={snackInfo.open} - color={snackInfo.color} - handleClose={() => - setSnackInfo({ - message: "", - icon: "", - open: false, - color: "", - }) - } - /> - - <Paper style={{ padding: "1em" }}> - <Grid container spacing={3} direction="row" alignItems="center"> - <Grid item xs={6}> - <Typography variant="h4"> - Lista de pedidos para professores + ) + )} + </> + ); + } else { + return ( + <> + <SnackBar + severity={snackInfo.icon} + text={snackInfo.message} + snackbarOpen={snackInfo.open} + color={snackInfo.color} + handleClose={() => + setSnackInfo({ + message: "", + icon: "", + open: false, + color: "", + }) + } + /> + + <Paper style={{ padding: "1em" }}> + <Grid container spacing={3} direction="row" alignItems="center"> + <Grid item xs={6}> + <Typography variant="h4"> + Lista de pedidos para professores </Typography> - </Grid> - - <Grid item xs={6}> - <Grid container justify="flex-end" spacing={3}> - <Grid item> - <Button - variant="contained" - color="secondary" - disabled={isUpdating} - onClick={() => { - currPage = 0; - UpdateHandler( - Url( - "users", - `"submitter_request":"${currStateFilter}","name":"${currNameFilter}","email":"${currEmailFilter}"`, - `${currPage}`, - "DESC" - ) - ); - }} - startIcon={<UpdateRoundedIcon />} - > - {isUpdating ? ( - <CircularProgress size={24} /> - ) : ( - "Atualizar" - )} - </Button> - </Grid> - <Grid item> - <Button - variant="contained" - color="secondary" - onClick={() => { - setShowFilter(!showFilter); - }} - startIcon={<FilterListRoundedIcon />} - > - Filtrar + </Grid> + + <Grid item xs={6}> + <Grid container justify="flex-end" spacing={3}> + <Grid item> + <Button + variant="contained" + color="secondary" + disabled={isUpdating} + onClick={() => { + setCurrPage(0) + }} + startIcon={<UpdateRoundedIcon />} + > + {isUpdating ? ( + <CircularProgress size={24} /> + ) : ( + "Atualizar" + )} + </Button> + </Grid> + <Grid item> + <Button + variant="contained" + color="secondary" + onClick={() => { + setShowFilter(!showFilter); + }} + startIcon={<FilterListRoundedIcon />} + > + Filtrar </Button> - </Grid> - </Grid> - </Grid> - </Grid> - - {showFilter ? ( - <Grid - container - direction="row" - justify="space-between" - alignItems="center" - alignContent="flex-end" - spacing={3} - xs={12} - > - <Grid item> - <TextField - select - label="Estado" - value={option ? option : ""} - onChange={handleChange} - helperText="Por favor, selecione uma das opções" - > - {StateOptions.map((option, index) => ( - <MenuItem - key={option.id} - value={option.name} - name={option.id} - onClick={() => - ApplyFilter(option.id, "submitter_request") - } - > - {option.name} - </MenuItem> - ))} - </TextField> - </Grid> - <Grid item> - <TextField label="Nome" onChange={NameHandler} value={name} /> - </Grid> - <Grid item> - <TextField - label="Email" - onChange={EmailHandler} - value={email} - /> - </Grid> - </Grid> - ) : null} - </Paper> - - <div style={{ height: "2em" }}></div> - - <Grid xs={12} container> - <TableData top={TOP_LABELS}> - <TableBody> - {items.map((row, index) => - index === items.length - 1 ? ( - <StyledTableRow key={index}> - {/* Button to load more data */} - <StyledTableCell> - <Button - color="primary" - variant="text" - // disabled={isLoadingMoreItems} - startIcon={<AddRoundedIcon />} - disabled={isLoadingMoreItems} - onClick={() => { - currPage++; - LoadMoreItens( - Url( - "users", - `"submitter_request":"${currStateFilter}","name":"${currNameFilter}","email":"${currEmailFilter}"`, - `${currPage}`, - "DESC" - ) - ); - }} - > - {isLoadingMoreItems ? ( - <CircularProgress size={24} /> - ) : ( - "Carregar mais itens" - )} - </Button> - </StyledTableCell> - </StyledTableRow> - ) : ( - <StyledTableRow - key={index} - style={{ flex: 1, width: "100%" }} - > - <StyledTableCell component="th" scope="row"> - {ComplaintStatus(row.submitter_request)} - </StyledTableCell> - <StyledTableCell align="right">{row.id}</StyledTableCell> - <StyledTableCell align="right"> - {row.name} - </StyledTableCell> - <StyledTableCell align="right"> - {row.email} - </StyledTableCell> - <StyledTableCell align="right"> - {DisplayDate(row.created_at)} - </StyledTableCell> - <StyledTableCell align="right"> - <Link to={`/admin/user/${row.id}`}> - <IconButton - onClick={() => { - currPage = 0; - currNameFilter = ""; - currEmailFilter = ""; - }} - > - <VisibilityIcon style={{ fill: "#00bcd4" }} /> - </IconButton> - </Link> - </StyledTableCell> - <StyledTableCell align="right"> - <Button - variant="contained" - color="secondary" - style={{ width: "100%" }} - disabled={ - row.submitter_request === "requested" ? false : true - } - startIcon={ - <CloseRoundedIcon style={{ fill: "#FFFAFA" }} /> - } - onClick={() => { - handleReject(row.id, row.name); - }} - > - Recusar + </Grid> + </Grid> + </Grid> + </Grid> + + {showFilter ? ( + <Grid + container + direction="row" + justify="space-between" + alignItems="center" + alignContent="flex-end" + spacing={3} + xs={12} + > + <Grid item> + <TextField + select + label="Estado" + value={option ? option : ""} + onChange={handleChange} + helperText="Por favor, selecione uma das opções" + > + {StateOptions.map((option, index) => ( + <MenuItem + key={option.value} + value={option.name} + name={option.value} + > + {option.value} + </MenuItem> + ))} + </TextField> + </Grid> + <Grid item> + <TextField label="Nome" onChange={NameHandler} value={name} /> + </Grid> + <Grid item> + <TextField + label="Email" + onChange={EmailHandler} + value={email} + /> + </Grid> + </Grid> + ) : null} + </Paper> + + <div style={{ height: "2em" }}></div> + + <Grid xs={12} container> + <TableData top={TOP_LABELS}> + <TableBody> + {items.map((row, index) => + index === items.length - 1 ? ( + <StyledTableRow key={index}> + {/* Button to load more data */} + <StyledTableCell> + <Button + color="primary" + variant="text" + // disabled={isLoadingMoreItems} + startIcon={<AddRoundedIcon />} + disabled={isLoadingMoreItems} + onClick={() => { + setCurrPage(currPage + 1) + }} + > + {isLoadingMoreItems ? ( + <CircularProgress size={24} /> + ) : ( + "Carregar mais itens" + )} + </Button> + </StyledTableCell> + </StyledTableRow> + ) : ( + <StyledTableRow + key={index} + style={{ flex: 1, width: "100%" }} + > + <StyledTableCell component="th" scope="row"> + {ComplaintStatus(row.submitter_request)} + </StyledTableCell> + <StyledTableCell align="right">{row.id}</StyledTableCell> + <StyledTableCell align="right"> + {row.name} + </StyledTableCell> + <StyledTableCell align="right"> + {row.email} + </StyledTableCell> + <StyledTableCell align="right"> + {DisplayDate(row.created_at)} + </StyledTableCell> + <StyledTableCell align="right"> + <Link to={`/admin/user/${row.id}`}> + <IconButton> + <VisibilityIcon style={{ fill: "#00bcd4" }} /> + </IconButton> + </Link> + </StyledTableCell> + <StyledTableCell align="right"> + <Button + variant="contained" + color="secondary" + style={{ width: "100%" }} + disabled={ + row.submitter_request === "requested" ? false : true + } + startIcon={ + <CloseRoundedIcon style={{ fill: "#FFFAFA" }} /> + } + onClick={() => { + handleReject(row.id, row.name); + }} + > + Recusar </Button> - <div style={{ height: "0.5em" }} /> - <Button - variant="contained" - color="primary" - style={{ width: "100%" }} - disabled={ - row.submitter_request === "requested" ? false : true - } - startIcon={ - <CheckRoundedIcon style={{ fill: "#FFFAFA" }} /> - } - onClick={() => { - handleAprove(row.id, row.name); - }} - > - Aceitar + <div style={{ height: "0.5em" }} /> + <Button + variant="contained" + color="primary" + style={{ width: "100%" }} + disabled={ + row.submitter_request === "requested" ? false : true + } + startIcon={ + <CheckRoundedIcon style={{ fill: "#FFFAFA" }} /> + } + onClick={() => { + handleAprove(row.id, row.name); + }} + > + Aceitar </Button> - </StyledTableCell> - </StyledTableRow> - ) - )} - </TableBody> - </TableData> - </Grid> - </> - ); - } - } else return <Unauthorized />; + </StyledTableCell> + </StyledTableRow> + ) + )} + </TableBody> + </TableData> + </Grid> + </> + ); + } + } else return <Unauthorized />; }; export default AproveTeacher; diff --git a/src/Admin/Pages/Pages/SubPages/Collections.js b/src/Admin/Pages/Pages/SubPages/Collections.js index 130e24b6..14731dcf 100644 --- a/src/Admin/Pages/Pages/SubPages/Collections.js +++ b/src/Admin/Pages/Pages/SubPages/Collections.js @@ -97,7 +97,7 @@ const Collections = () => { const [openAlertDialog, setOpenAlertDialog] = useState(false); const [deleteItem, setDeleteItem] = useState({}); //Delete Item const [isLoadingToDelete, setIsLoadingToDelete] = useState(null); - const [option, setOption] = useState("Todos os usuários"); //labels of the text field 'to' + const [option, setOption] = useState(); //labels of the text field 'to' const [snackInfo, setSnackInfo] = useState({ message: "", @@ -179,13 +179,13 @@ const Collections = () => { const buildUrl = (privacyOpt, name) => { if (privacyOpt && name) - return Url("/collections", `"privacy" : "${privacyOpt}", "name" : "${name}"`, currPage, "DESC") + return Url("collections", `"privacy" : "${privacyOpt}", "name" : "${name}"`, currPage, "DESC") else if (privacyOpt) - return Url("/collections", `"privacy" : "${privacyOpt}"`, currPage, "DESC") + return Url("collections", `"privacy" : "${privacyOpt}"`, currPage, "DESC") else if (name) - return Url("/collections", `"name" : "${name}"`, currPage, "DESC") + return Url("collections", `"name" : "${name}"`, currPage, "DESC") else - return Url("/collections", "", currPage, "DESC") + return Url("collections", "", currPage, "DESC") } useEffect(() => { diff --git a/src/Admin/Pages/Pages/SubPages/CommunityQuestions.js b/src/Admin/Pages/Pages/SubPages/CommunityQuestions.js index 451e7330..e7a59b94 100644 --- a/src/Admin/Pages/Pages/SubPages/CommunityQuestions.js +++ b/src/Admin/Pages/Pages/SubPages/CommunityQuestions.js @@ -156,23 +156,23 @@ const CommunityQuestion = () => { const buildUrl = (message, email, name) => { if (message && email && name) - return Url("/contacts", `"message" : "${message}", "email" : "${email}", "name" : "${name}"`, currPage, "DESC") + return Url("contacts", `"message" : "${message}", "email" : "${email}", "name" : "${name}"`, currPage, "DESC") else if (message && name) - return Url("/contacts", `"message" : "${message}", "name" : "${name}"`, currPage, "DESC") + return Url("contacts", `"message" : "${message}", "name" : "${name}"`, currPage, "DESC") else if (message && email) - return Url("/contacts", `"message" : "${message}", "email" : "${email}"`, currPage, "DESC") + return Url("contacts", `"message" : "${message}", "email" : "${email}"`, currPage, "DESC") else if (name && email) - return Url("/contacts", `"name" : "${name}", "email" : "${email}"`, currPage, "DESC") + return Url("contacts", `"name" : "${name}", "email" : "${email}"`, currPage, "DESC") else if (message) - return Url("/contacts", `"message" : "${message}"`, currPage, "DESC") + return Url("contacts", `"message" : "${message}"`, currPage, "DESC") else if (email) - return Url("/contacts", `"email" : "${email}"`, currPage, "DESC") + return Url("contacts", `"email" : "${email}"`, currPage, "DESC") else if (name) - return Url("/contacts", `"name" : "${name}"`, currPage, "DESC") + return Url("contacts", `"name" : "${name}"`, currPage, "DESC") else - return Url("/contacts", "", currPage, "DESC") + return Url("contacts", "", currPage, "DESC") } useEffect(() => { diff --git a/src/Admin/Pages/Pages/SubPages/EducationalObjects.js b/src/Admin/Pages/Pages/SubPages/EducationalObjects.js index a4219eea..b2046260 100644 --- a/src/Admin/Pages/Pages/SubPages/EducationalObjects.js +++ b/src/Admin/Pages/Pages/SubPages/EducationalObjects.js @@ -52,8 +52,6 @@ import styled from 'styled-components' import MenuBookRoundedIcon from "@material-ui/icons/MenuBookRounded"; import MobileList from "../../../Components/Components/MobileComponents/SimpleList" -let currPage = 0; - const StyledTableCell = withStyles((theme) => ({ head: { backgroundColor: theme.palette.common.black, @@ -90,17 +88,17 @@ const EducationalObjects = () => { const classes = useStyles(); const WINDOW_WIDTH = window.innerWidth - const addOndeLenght = [""]; + const ADD_ONE_LENGHT = [""]; const [error, setError] = useState(null); //Necessary to consult the API, catch errors const [isLoaded, setIsLoaded] = useState(false); //Necessary to consult the API, wait until complete const [items, setItems] = useState([]); //Necessary to consult the API, data - + const [currPage, setCurrPage] = useState(0) const [deleteItem, setDeleteItem] = useState({}); //Delete Item const [isLoadingToDelete, setIsLoadingToDelete] = useState(null); const [isUpdating, setIsUpdating] = useState(false); const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false); - + const [showFilter, setShowFilter] = useState(false) const [openAlertDialog, setOpenAlertDialog] = useState(false); const [snackInfo, setSnackInfo] = useState({ @@ -110,87 +108,25 @@ const EducationalObjects = () => { color: "", }); - // **************** About the PopOver Menu **************** - const [anchorEl, setAnchorEl] = React.useState(null); - const [showAuthorField, setShowAuthorField] = useState(false); //show the text field of filter by Author - const [showDescriptionField, setShowDescriptionField] = useState(false); //show the text field of the filter by description - const [showStandadSearch, setShowStandarSearchField] = useState(false); const [search, setSeacrh] = useState(""); + const [valueSearch, setValueSearch] = useState("") const [author, setAuthor] = useState(""); - const [description, setDescription] = useState(null); - - const AuthorHandler = () => { - setAuthor("") - setShowAuthorField(!showAuthorField); - let url; - if (description) - url = Url("learning_objects", `"name" : "${search}", "author" : "", "description" : "${description}"`, currPage, "DESC") - else - url = Url("learning_objects", `"name" : "${search}", "author" : ""`, currPage, "DESC") - Filter(url); - }; - - const DescHandler = () => { - setDescription(null) - setShowDescriptionField(!showDescriptionField); - let url; - url = Url("learning_objects", `"name" : "${search}", "author" : "${author}"`, currPage, "DESC") - Filter(url); - }; - - const StandartHandler = () => { - setSeacrh("") - setShowStandarSearchField(!showStandadSearch); - let url; - if (description) - url = Url("learning_objects", `"name" : "", "author" : "${author}", "description" : "${description}"`, currPage, "DESC") - else - url = Url("learning_objects", `"name" : "", "author" : "${author}"`, currPage, "DESC") - Filter(url); - }; - - const handleClick = (event) => { - setAnchorEl(event.currentTarget); - }; - - const handleClose = () => { - setAnchorEl(null); - }; - - const open = Boolean(anchorEl); - const id = open ? "simple-popover" : undefined; + const [valueAuthor, setValueAuthor] = useState("") + const [description, setDescription] = useState(""); + const [valueDescription, setValueDescription] = useState("") - const OnChangeSearchHandler = (e) => { - setSeacrh(e.target.value); - let url; - if (description) - url = Url("learning_objects", `"name" : "${search}", "author" : "${author}", "description" : "${description}"`, currPage, "DESC") - else - url = Url("learning_objects", `"name" : "${search}", "author" : "${author}"`, currPage, "DESC") - Filter(url); + const AuthorHandler = (event) => { + setValueAuthor(event.target.value) }; - const onChangeAuthorHandler = (e) => { - setAuthor(e.target.value); - let url; - if (description) - url = Url("learning_objects", `"name" : "${search}", "author" : "${author}", "description" : "${description}"`, currPage, "DESC") - else - url = Url("learning_objects", `"name" : "${search}", "author" : "${author}"`, currPage, "DESC") - Filter(url); + const DescHandler = (event) => { + setValueDescription(event.target.value) }; - const onChangeDescriptionHandler = (e) => { - setDescription(e.target.value); - let url; - if (description) - url = Url("learning_objects", `"name" : "${search}", "author" : "${author}", "description" : "${description}"`, currPage, "DESC") - else - url = Url("learning_objects", `"name" : "${search}", "author" : "${author}"`, currPage, "DESC") - Filter(url); + const StandartHandler = (event) => { + setValueSearch(event.target.value) }; - // **************** About the PopOverMenu **************** //Controlls the state of the Alert Dialog const HandleStateAlertDialog = (i) => { @@ -214,41 +150,6 @@ const EducationalObjects = () => { setIsLoadingToDelete(i); }; - //Filters the search - const Filter = (api) => { - getRequest( - api, - (data, header) => { - const arrData = [...data]; - setItems(arrData.concat(addOndeLenght)); - }, - (error) => { - setError(true); - } - ) - }; - - //This function updates List every time the content of the api changes - const UpdtateListData = (api) => { - getRequest( - api, - (data, header) => { - setItems([...data.concat(addOndeLenght)]); - HandleSnack( - "A lista de dados foi atualizada", - true, - "success", - "#228B22" - ); - setIsUpdating(false); - }, - (error) => { - HandleSnack("Ocorreu algum erro", true, "warning", "#FA8072"); - setIsUpdating(false); - } - ) - }; - //Called when user want to delete one institution async function DeleteHandler() { const id = deleteItem.id; @@ -265,8 +166,7 @@ const EducationalObjects = () => { "success", "#228B22" ); - currPage = 0; - UpdtateListData(Url("institutions", "", `${currPage}`, "DESC")); + setCurrPage(0) HandleStateCircularProgress(null); } }, @@ -277,34 +177,6 @@ const EducationalObjects = () => { ) } - const LoadMoreItens = async (api) => { - setIsLoadingMoreItems(true); - getRequest( - api, - (data, header) => { - const arrData = [...data]; - if (arrData.length === 0) { - HandleSnack( - "Não há mais dados para serem carregados", - true, - "warning", - "#FFC125" - ); - } else { - const arrItems = [...items]; - arrItems.pop(); //Deleting the last position, that was used to display the button of load more items - const arrResult = arrItems.concat(arrData); - setItems(arrResult.concat(addOndeLenght)); - } - setIsLoadingMoreItems(false); - }, - (error) => { - HandleSnack("Erro ao carregar os dados", true, "warning", "#FA8072"); - setIsLoadingMoreItems(false); - } - ) - }; - const DisplayDate = (date) => { const convertedData = moment.utc(date); return moment(convertedData) @@ -312,19 +184,70 @@ const EducationalObjects = () => { .toString(); }; + const buildUrl = (author, description, name) => { + if (author && description && name) + return Url("learning_objects", `"author" : "${author}", "description" : "${description}", "name" : "${name}"`, currPage, "DESC") + + else if (author && name) + return Url("learning_objects", `"author" : "${author}", "name" : "${name}"`, currPage, "DESC") + else if (author && description) + return Url("learning_objects", `"author" : "${author}", "description" : "${description}"`, currPage, "DESC") + else if (name && description) + return Url("learning_objects", `"name" : "${name}", "description" : "${description}"`, currPage, "DESC") + + else if (author) + return Url("learning_objects", `"author" : "${author}"`, currPage, "DESC") + else if (description) + return Url("learning_objects", `"description" : "${description}"`, currPage, "DESC") + else if (name) + return Url("learning_objects", `"name" : "${name}"`, currPage, "DESC") + else + return Url("learning_objects", "", currPage, "DESC") + } + useEffect(() => { + if (currPage === 0) + setIsLoaded(false) + else + setIsLoadingMoreItems(true) getRequest( - Url("learning_objects", `"name" : "${search}", "author" : "${author}"`, `${currPage}`, "DESC"), + buildUrl(author, description, search), (data, header) => { - setIsLoaded(true); - setItems(data.concat(addOndeLenght)); + const arrData = [...data] + if (arrData.length === 0) { + HandleSnack('Não há mais dados para serem carregados', true, 'warning', '#FFC125') + } else { + const arrItems = [...items] + if (currPage === 0) { + setItems(arrData.concat(ADD_ONE_LENGHT)) + } + else { + arrItems.pop(); //Deleting the last position, that was used to display the button of load more items + const arrResult = arrItems.concat(arrData) + setItems(arrResult.concat(ADD_ONE_LENGHT)) + } + } + setIsLoaded(true) + setIsLoadingMoreItems(false) }, (error) => { - setError(true); - + HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') + setIsLoadingMoreItems(false) + setIsLoaded(true) + setError(true) } ) - }, []); + }, [currPage, search, description, author]) + + useEffect(() => { + setCurrPage(0) + setSeacrh("") + setValueSearch("") + setDescription("") + setValueDescription("") + setAuthor("") + setValueAuthor("") + }, [showFilter]) if (error) { return <div>Error: {error.message}</div>; @@ -343,44 +266,28 @@ const EducationalObjects = () => { "DELETAR", ]; - //Buttons from PopOverMenu - const flatButtonsFromPopOverMenu = [ - { - label: "Pesquisa padrão", - onClick: StandartHandler, - color: showStandadSearch ? "primary" : "default", - }, - { - label: "Autor", - onClick: AuthorHandler, - color: showAuthorField ? "primary" : "default", - }, - { - label: "Descrição", - onClick: DescHandler, - color: showDescriptionField ? "primary" : "default", - }, - ]; - //Field of the Filter const TextFieldOfTheFilter = [ { label: "Pesquisar", - show: showStandadSearch, - onChange: (event) => OnChangeSearchHandler(event), - hide: StandartHandler, + value: valueSearch, + onChange: (event) => StandartHandler(event), + onBlur: (event) => setSeacrh(event.target.value), + helperText: "Ao terminar de digitar no campo, retire o foco do campo de texto" }, { label: "Autor", - show: showAuthorField, - onChange: (event) => onChangeAuthorHandler(event), - hide: AuthorHandler, + value: valueAuthor, + onChange: (event) => AuthorHandler(event), + onBlur: (event) => setAuthor(event.target.value), + helperText: "Ao terminar de digitar no campo, retire o foco do campo de texto" }, { label: "Descrição", - show: showDescriptionField, - onChange: (event) => onChangeDescriptionHandler(event), - hide: DescHandler, + value: valueDescription, + onChange: (event) => DescHandler(event), + onBlur: (event) => setDescription(event.target.value), + helperText: "Ao terminar de digitar no campo, retire o foco do campo de texto" }, ]; if (WINDOW_WIDTH <= 1058) { @@ -410,18 +317,17 @@ const EducationalObjects = () => { </Grid> <Grid item - xs={12} - + xs={12} + > <Grid container justify="flex-start" spacing={3}> <Grid item> <Button - aria-describedby={id} variant="contained" color="secondary" className={classes.button} - onClick={(event) => { - handleClick(event) + onClick={() => { + setShowFilter(!showFilter) }} startIcon={ <FilterListRoundedIcon style={{ fill: "white" }} /> @@ -429,30 +335,6 @@ const EducationalObjects = () => { > Filtrar </Button> - <Popover - id={id} - open={open} - anchorEl={anchorEl} - onClose={handleClose} - anchorOrigin={{ - vertical: "bottom", - horizontal: "center", - }} - transformOrigin={{ - vertical: "top", - horizontal: "center", - }} - > - {flatButtonsFromPopOverMenu.map((flat, index) => ( - <Button - key={index} - onClick={flat.onClick} - color={flat.color} - > - {flat.label} - </Button> - ))} - </Popover> </Grid> <Grid item> @@ -463,12 +345,7 @@ const EducationalObjects = () => { startIcon={<UpdateRoundedIcon />} disabled={isUpdating} onClick={() => { - currPage = 0; - setIsUpdating(true); - if (description) - UpdtateListData(Url("learning_objects", `"name" : "${search}", "author" : "${author}", "description" : "${description}"`, currPage, "DESC")) - else - UpdtateListData(Url("learning_objects", `"name" : "${search}", "author" : "${author}"`, currPage, "DESC")) + setCurrPage(0) }} > {isUpdating ? <CircularProgress size={24} /> : "Atualizar"} @@ -477,31 +354,26 @@ const EducationalObjects = () => { </Grid> </Grid> </Grid> - <Grid item xs={12}> - <Grid container justify="space-between" spacing={3}> - {TextFieldOfTheFilter.map((field, index) => ( - <Grid item key={index}> - {field.show ? ( - <div> - <TextField - id={index} - label={field.label} - type="search" - onChange={field.onChange} - /> - <IconButton - size="small" - color="primary" - onClick={field.hide} - > - <CancelRoundedIcon /> - </IconButton> - </div> - ) : null} - </Grid> - ))} + { + showFilter && + <Grid item xs={12}> + <Grid container justify="space-between" spacing={3}> + {TextFieldOfTheFilter.map((field, index) => ( + <Grid item key={field.label}> + <TextField + id={index} + label={field.label} + type="search" + onChange={field.onChange} + onBlur={field.onBlur} + value={field.value} + helperText={field.helperText} + /> + </Grid> + ))} + </Grid> </Grid> - </Grid> + } </Paper> {/************** End of the header **************/} @@ -519,11 +391,7 @@ const EducationalObjects = () => { startIcon={<AddRoundedIcon />} disabled={isLoadingMoreItems} onClick={() => { - currPage++ - if (description) - LoadMoreItens(Url("learning_objects", `"name" : "${search}", "author" : "${author}", "description" : "${description}"`, currPage, "DESC")) - else - LoadMoreItens(Url("learning_objects", `"name" : "${search}", "author" : "${author}"`, currPage, "DESC")) + setCurrPage(currPage + 1) }} > {isLoadingMoreItems ? ( @@ -543,7 +411,7 @@ const EducationalObjects = () => { avatar={<MenuBookRoundedIcon />} href={`/admin/learningObject/${row.id}`} reset={() => { - currPage = 0; + }} data={ [ @@ -606,43 +474,18 @@ const EducationalObjects = () => { <Grid container justify="flex-end" spacing={3}> <Grid item> <Button - aria-describedby={id} variant="contained" color="secondary" className={classes.button} onClick={(event) => { - handleClick(event) + setShowFilter(!showFilter) }} startIcon={ <FilterListRoundedIcon style={{ fill: "white" }} /> } > Filtrar - </Button> - <Popover - id={id} - open={open} - anchorEl={anchorEl} - onClose={handleClose} - anchorOrigin={{ - vertical: "bottom", - horizontal: "center", - }} - transformOrigin={{ - vertical: "top", - horizontal: "center", - }} - > - {flatButtonsFromPopOverMenu.map((flat, index) => ( - <Button - key={index} - onClick={flat.onClick} - color={flat.color} - > - {flat.label} - </Button> - ))} - </Popover> + </Button> </Grid> <Grid item> @@ -653,12 +496,7 @@ const EducationalObjects = () => { startIcon={<UpdateRoundedIcon />} disabled={isUpdating} onClick={() => { - currPage = 0; - setIsUpdating(true); - if (description) - UpdtateListData(Url("learning_objects", `"name" : "${search}", "author" : "${author}", "description" : "${description}"`, currPage, "DESC")) - else - UpdtateListData(Url("learning_objects", `"name" : "${search}", "author" : "${author}"`, currPage, "DESC")) + setCurrPage(0) }} > {isUpdating ? <CircularProgress size={24} /> : "Atualizar"} @@ -667,31 +505,26 @@ const EducationalObjects = () => { </Grid> </Grid> </Grid> - <Grid item xs={12}> - <Grid container justify="space-between" spacing={3}> - {TextFieldOfTheFilter.map((field, index) => ( - <Grid item key={index}> - {field.show ? ( - <div> - <TextField - id={index} - label={field.label} - type="search" - onChange={field.onChange} - /> - <IconButton - size="small" - color="primary" - onClick={field.hide} - > - <CancelRoundedIcon /> - </IconButton> - </div> - ) : null} - </Grid> - ))} + { + showFilter && + <Grid item xs={12}> + <Grid container justify="space-between" spacing={3}> + {TextFieldOfTheFilter.map((field, index) => ( + <Grid item key={field.label}> + <TextField + id={index} + label={field.label} + type="search" + onChange={field.onChange} + onBlur={field.onBlur} + value={field.value} + helperText={field.helperText} + /> + </Grid> + ))} + </Grid> </Grid> - </Grid> + } </Paper> {/************** End of the header **************/} @@ -713,11 +546,7 @@ const EducationalObjects = () => { isLoadingMoreItems } onClick={() => { - currPage++ - if (description) - LoadMoreItens(Url("learning_objects", `"name" : "${search}", "author" : "${author}", "description" : "${description}"`, currPage, "DESC")) - else - LoadMoreItens(Url("learning_objects", `"name" : "${search}", "author" : "${author}"`, currPage, "DESC")) + setCurrPage(currPage + 1) }} > {isLoadingMoreItems ? ( @@ -747,10 +576,7 @@ const EducationalObjects = () => { </StyledTableCell> <StyledTableCell align="right"> <Link to={`/admin/learningObject/${row.id}`}> - <IconButton onClick={() => { - currPage = 0 - - }}> + <IconButton> <VisibilityIcon style={{ fill: "#00bcd4" }} /> </IconButton> </Link> diff --git a/src/Admin/Pages/Pages/SubPages/Institutions.js b/src/Admin/Pages/Pages/SubPages/Institutions.js index 66376f57..d751db6f 100644 --- a/src/Admin/Pages/Pages/SubPages/Institutions.js +++ b/src/Admin/Pages/Pages/SubPages/Institutions.js @@ -184,7 +184,7 @@ const Institutions = () => { } const buildUrl = () => { - return Url("/institutions", `"name" : "${search}", "description" : "${description}", "city" : "${city}", "country" : "${country}"`, currPage, "DESC") + return Url("institutions", `"name" : "${search}", "description" : "${description}", "city" : "${city}", "country" : "${country}"`, currPage, "DESC") } useEffect(() => { diff --git a/src/Admin/Pages/Pages/SubPages/Languages.js b/src/Admin/Pages/Pages/SubPages/Languages.js index 00693f02..5c6c454c 100644 --- a/src/Admin/Pages/Pages/SubPages/Languages.js +++ b/src/Admin/Pages/Pages/SubPages/Languages.js @@ -43,451 +43,381 @@ import styled from "styled-components" import LanguageRoundedIcon from "@material-ui/icons/LanguageRounded"; import MobileList from "../../../Components/Components/MobileComponents/SimpleList" -let currPage = 0; -let transformListToAsc = false; - const StyledTableCell = withStyles((theme) => ({ - head: { - backgroundColor: theme.palette.common.black, - color: theme.palette.common.white, - }, - body: { - fontSize: 14, - }, + head: { + backgroundColor: theme.palette.common.black, + color: theme.palette.common.white, + }, + body: { + fontSize: 14, + }, }))(TableCell); const StyledTableRow = withStyles((theme) => ({ - root: { - '&:nth-of-type(odd)': { - backgroundColor: theme.palette.action.hover, - }, + root: { + '&:nth-of-type(odd)': { + backgroundColor: theme.palette.action.hover, }, + }, }))(TableRow); const Languages = () => { - const ADD_ONE_LENGHT = [""]; - const TOP_LABELS = ['ID', 'NOME', 'CODE', 'EDITAR', 'DELETAR'] //Labels from Table - const WINDOW_WIDTH = window.innerWidth - - const [error, setError] = useState(null); //Necessary to consult the API, catch errors - const [isLoaded, setIsLoaded] = useState(false); //Necessary to consult the API, wait until complete - const [items, setItems] = useState([]); //Necessary to consult the API, data - - const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false) //controlls the state of loadind more data - const [isUpdating, setIsUpdating] = useState(false); //controlls the state of updating data - const [openAlertDialog, setOpenAlertDialog] = useState(false); //controlls the state od alert dialog - - const [deleteItem, setDeleteItem] = useState({}); //Delete Item - const [isLoadingToDelete, setIsLoadingToDelete] = useState(null); - - const [snackInfo, setSnackInfo] = useState({ - message: '', - icon: '', - open: false, - color: '', + const ADD_ONE_LENGHT = [""]; + const TOP_LABELS = ['ID', 'NOME', 'CODE', 'EDITAR', 'DELETAR'] //Labels from Table + const WINDOW_WIDTH = window.innerWidth + + const [error, setError] = useState(null); //Necessary to consult the API, catch errors + const [isLoaded, setIsLoaded] = useState(false); //Necessary to consult the API, wait until complete + const [items, setItems] = useState([]); //Necessary to consult the API, data + + const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false) //controlls the state of loadind more data + const [isUpdating, setIsUpdating] = useState(false); //controlls the state of updating data + const [openAlertDialog, setOpenAlertDialog] = useState(false); //controlls the state od alert dialog + const [currPage, setCurrPage] = useState(0) + + const [deleteItem, setDeleteItem] = useState({}); //Delete Item + const [isLoadingToDelete, setIsLoadingToDelete] = useState(null); + + const [snackInfo, setSnackInfo] = useState({ + message: '', + icon: '', + open: false, + color: '', + }) + + //handle snack info + const HandleSnack = (message, state, icon, color) => { + setSnackInfo({ + message: message, + icon: icon, + open: state, + color: color }) - - //handle snack info - const HandleSnack = (message, state, icon, color) => { - setSnackInfo({ - message: message, - icon: icon, - open: state, - color: color - }) - } - - //handle load more items - const LoadMoreItens = async (api) => { - setIsLoadingMoreItems(true) - getRequest( - api, - (data, header) => { - const arrData = [...data] - if (arrData.length === 0) { - HandleSnack('Não há mais dados para serem carregados', true, 'warning', '#FFC125') - } else { - const arrItems = [...items] - arrItems.pop(); //Deleting the last position, that was used to display the button of load more items - const arrResult = arrItems.concat(arrData) - setItems(arrResult.concat(ADD_ONE_LENGHT)) - } - setIsLoadingMoreItems(false) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - setIsLoadingMoreItems(false) - } - ) - } - - // handle update list data - const UpdateHandler = async (api) => { - setIsUpdating(true) - getRequest( - api, - (data, header) => { - HandleSnack('A lista de dados foi atualizada', true, 'success', '#228B22') - const arrData = [...data] - setItems(arrData.concat(ADD_ONE_LENGHT)) - setIsUpdating(false) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - setIsUpdating(false) - } - ) - } - - //handle Delete - async function DeleteHandler() { - const id = deleteItem.id; - HandleStateAlertDialog(null); - deleteRequest( - DeleteFilter("languages", id), - (data) => { - if (data.errors) - HandleSnack("Ocorreu algum erro", true, "warning", "#FA8072"); - else { - HandleSnack( - "A língua foi deletada com sucesso", - true, - "success", - "#228B22" - ); - currPage = 0; - transformListToAsc = false - UpdateHandler(Url("languages", "", `${currPage}`, "DESC")); - HandleStateCircularProgress(null); - } - }, - (error) => { - HandleSnack("Ocorreu algum erro", true, "warning", "#FA8072"); - HandleStateCircularProgress(null); - } - ) - } - - const HandleStateCircularProgress = (i) => { - setIsLoadingToDelete(i); - }; - - const HandleStateAlertDialog = (i) => { - const obj = { ...items[i] }; - setDeleteItem(obj); - setOpenAlertDialog(!openAlertDialog); - }; - - const InvertList = async () => { - transformListToAsc = !transformListToAsc - currPage = 0 - if (transformListToAsc) { - getRequest( - Url('languages', '', `${currPage}`, 'ASC'), - (data, header) => { - const arrData = [...data] - setItems(arrData.concat(ADD_ONE_LENGHT)) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - } - ) + } + + //handle Delete + async function DeleteHandler() { + const id = deleteItem.id; + HandleStateAlertDialog(null); + deleteRequest( + DeleteFilter("languages", id), + (data) => { + if (data.errors) + HandleSnack("Ocorreu algum erro", true, "warning", "#FA8072"); + else { + HandleSnack( + "A língua foi deletada com sucesso", + true, + "success", + "#228B22" + ); + setCurrPage(0) + HandleStateCircularProgress(null); + } + }, + (error) => { + HandleSnack("Ocorreu algum erro", true, "warning", "#FA8072"); + HandleStateCircularProgress(null); + } + ) + } + + const HandleStateCircularProgress = (i) => { + setIsLoadingToDelete(i); + }; + + const HandleStateAlertDialog = (i) => { + const obj = { ...items[i] }; + setDeleteItem(obj); + setOpenAlertDialog(!openAlertDialog); + }; + + //getting data from server + useEffect(() => { + if (currPage === 0) + setIsLoaded(false) + else + setIsLoadingMoreItems(true) + getRequest( + Url("languages", "", currPage, "DESC"), + (data, header) => { + const arrData = [...data] + if (arrData.length === 0) { + HandleSnack('Não há mais dados para serem carregados', true, 'warning', '#FFC125') } else { - getRequest( - Url('languages', '', `${currPage}`, 'DESC'), - (data, header) => { - const arrData = [...data] - setItems(arrData.concat(ADD_ONE_LENGHT)) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - } - ) + const arrItems = [...items] + if (currPage === 0) { + setItems(arrData.concat(ADD_ONE_LENGHT)) + } + else { + arrItems.pop(); //Deleting the last position, that was used to display the button of load more items + const arrResult = arrItems.concat(arrData) + setItems(arrResult.concat(ADD_ONE_LENGHT)) + } } - } - - //getting data from server - useEffect(() => { - getRequest( - Url('languages', '', `${currPage}`, 'DESC'), - (data, header) => { - setIsLoaded(true); - setItems(data.concat(ADD_ONE_LENGHT)); - }, - (error) => { - setError(true); - } - ) - }, []); - - - if (error) { - return <div>Error: {error.message}</div>; - } else if (!isLoaded) { - return <LoadingSpinner text="Carregando..." /> - } else { - if (WINDOW_WIDTH <= 755) { - return ( - <> - <SnackBar - severity={snackInfo.icon} - text={snackInfo.message} - snackbarOpen={snackInfo.open} - color={snackInfo.color} - handleClose={() => setSnackInfo({ - message: '', - icon: '', - open: false, - color: '' - })} - /> - - <Paper style={{ padding: '1em' }}> - <Grid container spacing={3} direction="row" alignItems="center"> - <Grid item xs={12}> - <Typography variant="h4"> - Linguagens + setIsLoaded(true) + setIsLoadingMoreItems(false) + }, + (error) => { + HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') + setIsLoadingMoreItems(false) + setIsLoaded(true) + setError(true) + } + ) + }, [currPage]) + + + if (error) { + return <div>Error: {error.message}</div>; + } else if (!isLoaded) { + return <LoadingSpinner text="Carregando..." /> + } else { + if (WINDOW_WIDTH <= 800) { + return ( + <> + <SnackBar + severity={snackInfo.icon} + text={snackInfo.message} + snackbarOpen={snackInfo.open} + color={snackInfo.color} + handleClose={() => setSnackInfo({ + message: '', + icon: '', + open: false, + color: '' + })} + /> + + <Paper style={{ padding: '1em' }}> + <Grid container spacing={3} direction="row" alignItems="center"> + <Grid item xs={12}> + <Typography variant="h4"> + Linguagens </Typography> - </Grid> - <Grid - item - xs={12} - > - <Grid container justify="flex-start" spacing={3}> - <Grid item> - <Button - variant="contained" - color="secondary" - disabled={isUpdating} - onClick={() => { - currPage = 0 - transformListToAsc = false - UpdateHandler(Url('languages', '', `${currPage}`, 'DESC')) - }} - startIcon={<UpdateRoundedIcon />} - > - { - isUpdating ? <CircularProgress size={24} /> : 'Atualizar' - } - </Button> - </Grid> - <Grid item> - - <Link style={{ textDecoration: 'none' }} to={'/admin/languageCreate'}> - <Button - variant="contained" - color="secondary" - startIcon={<AddRoundedIcon />} - > - Novo + </Grid> + <Grid + item + xs={12} + > + <Grid container justify="flex-start" spacing={3}> + <Grid item> + <Button + variant="contained" + color="secondary" + disabled={isUpdating} + onClick={() => { + setCurrPage(0) + }} + startIcon={<UpdateRoundedIcon />} + > + { + isUpdating ? <CircularProgress size={24} /> : 'Atualizar' + } + </Button> + </Grid> + <Grid item> + + <Link style={{ textDecoration: 'none' }} to={'/admin/languageCreate'}> + <Button + variant="contained" + color="secondary" + startIcon={<AddRoundedIcon />} + > + Novo </Button> - </Link> - </Grid> - </Grid> - </Grid> - </Grid> - </Paper> - - <div style={{ height: '2em' }}></div> - - {items.map((row, index) => - index === items.length - 1 ? ( - <StyledDivButton> - <Button - key={index} - color="primary" - variant="text" - // disabled={isLoadingMoreItems} - startIcon={<AddRoundedIcon />} - disabled={isLoadingMoreItems} - onClick={() => { - currPage++ - if (transformListToAsc) { - LoadMoreItens(Url('languages', '', `${currPage}`, 'ASC')) - } else { - LoadMoreItens(Url('languages', '', `${currPage}`, 'DESC')) - } - }} - > - {isLoadingMoreItems ? ( - <CircularProgress size={24} /> - ) : ( - "Carregar mais itens" - )} - </Button> - </StyledDivButton> - ) : ( - <> - <MobileList - key={index} - title={row.name} - subtitle={row.id} - backColor={"#e81f4f"} - avatar={<LanguageRoundedIcon />} - href={`/admin/languageEdit/${row.id}`} - reset={() => { - currPage = 0; - transformListToAsc = false - }} - data={ - [ - { - title: "Code", - subtitle: row.code - - }, - ] - } - /> - <div style={{ height: "0.5em" }} /> - </> - ) + </Link> + </Grid> + </Grid> + </Grid> + </Grid> + </Paper> + + <div style={{ height: '2em' }}></div> + + {items.map((row, index) => + index === items.length - 1 ? ( + <StyledDivButton key="Load"> + <Button + color="primary" + variant="text" + // disabled={isLoadingMoreItems} + startIcon={<AddRoundedIcon />} + disabled={isLoadingMoreItems} + onClick={() => { + setCurrPage(currPage + 1) + }} + > + {isLoadingMoreItems ? ( + <CircularProgress size={24} /> + ) : ( + "Carregar mais itens" )} - </> - ); - } - else { - return ( + </Button> + </StyledDivButton> + ) : ( <> - <SnackBar - severity={snackInfo.icon} - text={snackInfo.message} - snackbarOpen={snackInfo.open} - color={snackInfo.color} - handleClose={() => setSnackInfo({ - message: '', - icon: '', - open: false, - color: '' - })} - /> - - <Paper style={{ padding: '1em' }}> - <Grid container spacing={3} direction="row" alignItems="center"> - <Grid item xs={6}> - <Typography variant="h4"> - Linguagens + <MobileList + key={row.created_at} + title={row.name} + subtitle={row.id} + backColor={"#e81f4f"} + avatar={<LanguageRoundedIcon />} + href={`/admin/languageEdit/${row.id}`} + reset={() => { + + }} + data={ + [ + { + title: "Code", + subtitle: row.code + + }, + ] + } + /> + <div style={{ height: "0.5em" }} /> + </> + ) + )} + </> + ); + } + else { + return ( + <> + <SnackBar + severity={snackInfo.icon} + text={snackInfo.message} + snackbarOpen={snackInfo.open} + color={snackInfo.color} + handleClose={() => setSnackInfo({ + message: '', + icon: '', + open: false, + color: '' + })} + /> + + <Paper style={{ padding: '1em' }}> + <Grid container spacing={3} direction="row" alignItems="center"> + <Grid item xs={6}> + <Typography variant="h4"> + Linguagens </Typography> - </Grid> - <Grid - item - xs={6} - > - <Grid container justify="flex-end" spacing={3}> - <Grid item> - <Button - variant="contained" - color="secondary" - disabled={isUpdating} - onClick={() => { - currPage = 0 - transformListToAsc = false - UpdateHandler(Url('languages', '', `${currPage}`, 'DESC')) - }} - startIcon={<UpdateRoundedIcon />} - > - { - isUpdating ? <CircularProgress size={24} /> : 'Atualizar' - } - </Button> - </Grid> - <Grid item> - - <Link style={{ textDecoration: 'none' }} to={'/admin/languageCreate'}> - <Button - variant="contained" - color="secondary" - startIcon={<AddRoundedIcon />} - > - Novo - </Button> - </Link> - </Grid> - </Grid> - </Grid> - </Grid> - </Paper> - - <div style={{ height: '2em' }}></div> - - <TableData - top={TOP_LABELS} - onIconPressed={InvertList} + </Grid> + <Grid + item + xs={6} + > + <Grid container justify="flex-end" spacing={3}> + <Grid item> + <Button + variant="contained" + color="secondary" + disabled={isUpdating} + onClick={() => { + setCurrPage(0) + }} + startIcon={<UpdateRoundedIcon />} > - <TableBody> - {items.map((row, index) => ( - index === items.length - 1 ? - <StyledTableRow key={index}> - {/* Button to load more data */} - <StyledTableCell> - <Button - color='primary' - variant='text' - // disabled={isLoadingMoreItems} - startIcon={<AddRoundedIcon />} - disabled={isLoadingMoreItems} - onClick={() => { - currPage++ - if (transformListToAsc) { - LoadMoreItens(Url('languages', '', `${currPage}`, 'ASC')) - } else { - LoadMoreItens(Url('languages', '', `${currPage}`, 'DESC')) - } - }} - > - { - isLoadingMoreItems ? <CircularProgress size={24} /> : 'Carregar mais itens' - } + { + isUpdating ? <CircularProgress size={24} /> : 'Atualizar' + } + </Button> + </Grid> + <Grid item> + + <Link style={{ textDecoration: 'none' }} to={'/admin/languageCreate'}> + <Button + variant="contained" + color="secondary" + startIcon={<AddRoundedIcon />} + > + Novo </Button> - </StyledTableCell> - </StyledTableRow> - - : - - <StyledTableRow key={index}> - <StyledTableCell component="th" scope="row">{row.id}</StyledTableCell> - <StyledTableCell align="right">{row.name}</StyledTableCell> - <StyledTableCell align="right">{row.code}</StyledTableCell> - <StyledTableCell align="right"> - <Link to={`/admin/languageEdit/${row.id}`}> - <IconButton onClick={() => { currPage = 0; transformListToAsc = false }}> - <EditRoundedIcon style={{ fill: '#00bcd4' }} /> - </IconButton> - </Link> - </StyledTableCell> - <StyledTableCell align="right"> - {isLoadingToDelete === index ? ( - <CircularProgress size={24} color="primary" /> - ) : ( - <IconButton - onClick={() => { - HandleStateAlertDialog(index); - HandleStateCircularProgress(index); - }} - > - <DeleteRoundedIcon style={{ fill: "#FF0000" }} /> - </IconButton> - )} - </StyledTableCell> - </StyledTableRow> - ))} - </TableBody> - </TableData> - - {/* This alert will be displayed if the user click to delete an institution */} - <AlertDialog - open={openAlertDialog} - OnDelete={DeleteHandler} - deleteItem={deleteItem} - HandleClose={() => { - setOpenAlertDialog(false); - HandleStateCircularProgress(null); + </Link> + </Grid> + </Grid> + </Grid> + </Grid> + </Paper> + + <div style={{ height: '2em' }}></div> + + <TableData + top={TOP_LABELS} + > + <TableBody> + {items.map((row, index) => ( + index === items.length - 1 ? + <StyledTableRow key="Load more"> + {/* Button to load more data */} + <StyledTableCell> + <Button + color='primary' + variant='text' + // disabled={isLoadingMoreItems} + startIcon={<AddRoundedIcon />} + disabled={isLoadingMoreItems} + onClick={() => { + setCurrPage(currPage + 1) }} - /> - </> - ); - } + > + { + isLoadingMoreItems ? <CircularProgress size={24} /> : 'Carregar mais itens' + } + </Button> + </StyledTableCell> + </StyledTableRow> + + : + + <StyledTableRow key={row.created_at}> + <StyledTableCell component="th" scope="row">{row.id}</StyledTableCell> + <StyledTableCell align="right">{row.name}</StyledTableCell> + <StyledTableCell align="right">{row.code}</StyledTableCell> + <StyledTableCell align="right"> + <Link to={`/admin/languageEdit/${row.id}`}> + <IconButton> + <EditRoundedIcon style={{ fill: '#00bcd4' }} /> + </IconButton> + </Link> + </StyledTableCell> + <StyledTableCell align="right"> + {isLoadingToDelete === index ? ( + <CircularProgress size={24} color="primary" /> + ) : ( + <IconButton + onClick={() => { + HandleStateAlertDialog(index); + HandleStateCircularProgress(index); + }} + > + <DeleteRoundedIcon style={{ fill: "#FF0000" }} /> + </IconButton> + )} + </StyledTableCell> + </StyledTableRow> + ))} + </TableBody> + </TableData> + + {/* This alert will be displayed if the user click to delete an institution */} + <AlertDialog + open={openAlertDialog} + OnDelete={DeleteHandler} + deleteItem={deleteItem} + HandleClose={() => { + setOpenAlertDialog(false); + HandleStateCircularProgress(null); + }} + /> + </> + ); } + } } export default Languages; diff --git a/src/Admin/Pages/Pages/SubPages/NoteVariables.js b/src/Admin/Pages/Pages/SubPages/NoteVariables.js index 16c39487..b3d2e8bf 100644 --- a/src/Admin/Pages/Pages/SubPages/NoteVariables.js +++ b/src/Admin/Pages/Pages/SubPages/NoteVariables.js @@ -44,377 +44,310 @@ import styled from "styled-components" import MobileList from "../../../Components/Components/MobileComponents/SimpleList" import TrendingUpRoundedIcon from "@material-ui/icons/TrendingUpRounded"; -let currPage = 0; //var that controlls the current page that we are -let transformListToAsc = false; - const StyledTableCell = withStyles((theme) => ({ - head: { - backgroundColor: theme.palette.common.black, - color: theme.palette.common.white, - }, - body: { - fontSize: 14, - }, + head: { + backgroundColor: theme.palette.common.black, + color: theme.palette.common.white, + }, + body: { + fontSize: 14, + }, }))(TableCell); const StyledTableRow = withStyles((theme) => ({ - root: { - '&:nth-of-type(odd)': { - backgroundColor: theme.palette.action.hover, - }, + root: { + '&:nth-of-type(odd)': { + backgroundColor: theme.palette.action.hover, }, + }, }))(TableRow); const NoteVariables = () => { - const WINDOW_WIDTH = window.innerWidth - const AddOneLenght = ['']; - const [error, setError] = useState(null); //Necessary to consult the API, catch errors - const [isLoaded, setIsLoaded] = useState(false); //Necessary to consult the API, wait until complete - const [items, setItems] = useState([]); //Necessary to consult the API, data - const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false) - const [isUpdating, setIsUpdating] = useState(false) + const WINDOW_WIDTH = window.innerWidth + const ADD_ONE_LENGHT = [""]; + const [error, setError] = useState(null); //Necessary to consult the API, catch errors + const [isLoaded, setIsLoaded] = useState(false); //Necessary to consult the API, wait until complete + const [currPage, setCurrPage] = useState(0) + const [items, setItems] = useState([]); //Necessary to consult the API, data + const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false) + const [isUpdating, setIsUpdating] = useState(false) - const [snackInfo, setSnackInfo] = useState({ - message: '', - icon: '', - open: false, - color: '', - }) - - // Handle snack infos - const HandleSnack = (message, state, icon, color) => { - setSnackInfo({ - message: message, - icon: icon, - open: state, - color: color - }) - } + const [snackInfo, setSnackInfo] = useState({ + message: '', + icon: '', + open: false, + color: '', + }) - const LoadMoreItens = async (api) => { - setIsLoadingMoreItems(true) - getRequest( - api, - (data, header) => { - const arrData = [...data] - if (arrData.length === 0) { - HandleSnack('Não há mais dados para serem carregados', true, 'warning', '#FFC125') - } else { - const arrItems = [...items] - arrItems.pop(); //Deleting the last position, that was used to display the button of load more items - const arrResult = arrItems.concat(arrData) - setItems(arrResult.concat(AddOneLenght)) - } - setIsLoadingMoreItems(false) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - setIsLoadingMoreItems(false) - } - ) - } + // Handle snack infos + const HandleSnack = (message, state, icon, color) => { + setSnackInfo({ + message: message, + icon: icon, + open: state, + color: color + }) + } - const InvertList = async () => { - transformListToAsc = !transformListToAsc - currPage = 0 - if (transformListToAsc) { - getRequest( - Url('scores', '', `${currPage}`, 'ASC'), - (data, header) => { - const arrData = [...data] - setItems(arrData.concat(AddOneLenght)) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - } - ) + useEffect(() => { + if (currPage === 0) + setIsLoaded(false) + else + setIsLoadingMoreItems(true) + getRequest( + Url("scores", "", currPage, "DESC"), + (data, header) => { + const arrData = [...data] + if (arrData.length === 0) { + HandleSnack('Não há mais dados para serem carregados', true, 'warning', '#FFC125') } else { - getRequest( - Url('scores', '', `${currPage}`, 'DESC'), - (data, header) => { - const arrData = [...data] - setItems(arrData.concat(AddOneLenght)) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - } - ) + const arrItems = [...items] + if (currPage === 0) { + setItems(arrData.concat(ADD_ONE_LENGHT)) + } + else { + arrItems.pop(); //Deleting the last position, that was used to display the button of load more items + const arrResult = arrItems.concat(arrData) + setItems(arrResult.concat(ADD_ONE_LENGHT)) + } } - } - - const UpdateHandler = async (api) => { - setIsUpdating(true) - getRequest( - api, - (data, header) => { - HandleSnack('A lista de dados foi atualizada', true, 'success', '#228B22') - const arrData = [...data] - setItems(arrData.concat(AddOneLenght)) - setIsUpdating(false) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - setIsUpdating(false) - } - ) - } + setIsLoaded(true) + setIsLoadingMoreItems(false) + }, + (error) => { + HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') + setIsLoadingMoreItems(false) + setIsLoaded(true) + setError(true) + } + ) + }, [currPage]) - useEffect(() => { - getRequest( - Url('scores', '', '0', 'DESC'), - (data, header) => { - setIsLoaded(true); - setItems(data.concat(AddOneLenght)); - }, - (error) => { - setError(true); - } - ) - }, []); + if (error) { + return <div>Error: {error.message}</div>; + } else if (!isLoaded) { + return <LoadingSpinner text="Carregando..." /> + } else { + //Words in the top part of the table + const topTable = ['ID', 'NOME', 'CÓDIGO', 'PESO', 'ATIVO', 'SCORE TYPE', 'VISUALIZAR']; - if (error) { - return <div>Error: {error.message}</div>; - } else if (!isLoaded) { - return <LoadingSpinner text="Carregando..." /> - } else { - - //Words in the top part of the table - const topTable = ['ID', 'NOME', 'CÓDIGO', 'PESO', 'ATIVO', 'SCORE TYPE', 'VISUALIZAR']; - - if (WINDOW_WIDTH <= 961) { - return ( - <div> - <SnackBar - severity={snackInfo.icon} - text={snackInfo.message} - snackbarOpen={snackInfo.open} - color={snackInfo.color} - handleClose={() => setSnackInfo({ - message: '', - icon: '', - open: false, - color: '' - })} - /> - <Paper style={{ padding: '1em' }}> - <Grid container spacing={3} direction="row" alignItems="center"> - <Grid item xs={12}> - <Typography variant="h4"> - Variáveis de nota + if (WINDOW_WIDTH <= 961) { + return ( + <div> + <SnackBar + severity={snackInfo.icon} + text={snackInfo.message} + snackbarOpen={snackInfo.open} + color={snackInfo.color} + handleClose={() => setSnackInfo({ + message: '', + icon: '', + open: false, + color: '' + })} + /> + <Paper style={{ padding: '1em' }}> + <Grid container spacing={3} direction="row" alignItems="center"> + <Grid item xs={12}> + <Typography variant="h4"> + Variáveis de nota </Typography> - </Grid> - <Grid - item - xs={12} - > - <Grid container justify="flex-start" spacing={3}> - <Grid item> - <Button - variant="contained" - color="secondary" - disabled={isUpdating} - onClick={() => { - currPage = 0 - transformListToAsc = false - UpdateHandler(Url('scores', '', `${currPage}`, 'DESC')) - }} - startIcon={<UpdateRoundedIcon />} - > - { - isUpdating ? <CircularProgress size={24} /> : 'Atualizar' - } - </Button> - </Grid> - </Grid> - </Grid> - </Grid> - </Paper> + </Grid> + <Grid + item + xs={12} + > + <Grid container justify="flex-start" spacing={3}> + <Grid item> + <Button + variant="contained" + color="secondary" + disabled={isUpdating} + onClick={() => { + setCurrPage(0) + }} + startIcon={<UpdateRoundedIcon />} + > + { + isUpdating ? <CircularProgress size={24} /> : 'Atualizar' + } + </Button> + </Grid> + </Grid> + </Grid> + </Grid> + </Paper> - <div style={{ height: '2em' }}></div> + <div style={{ height: '2em' }}></div> - {items.map((row, index) => - index === items.length - 1 ? ( - <StyledDivButton> - <Button - key={index} - color="primary" - variant="text" - // disabled={isLoadingMoreItems} - startIcon={<AddRoundedIcon />} - disabled={isLoadingMoreItems} - onClick={() => { - currPage++ - if (transformListToAsc) { - LoadMoreItens(Url('scores', '', `${currPage}`, 'ASC')) - } else { - LoadMoreItens(Url('scores', '', `${currPage}`, 'DESC')) - } - }} - > - {isLoadingMoreItems ? ( - <CircularProgress size={24} /> - ) : ( - "Carregar mais itens" - )} - </Button> - </StyledDivButton> - ) : ( - <> - <MobileList - key={index} - title={row.name} - subtitle={row.id} - backColor={"#e81f4f"} - avatar={<TrendingUpRoundedIcon />} - href={`/admin/noteVar/${row.id}`} - reset={() => { - currPage = 0; - }} - data={ - [ - { - title: "Código", - subtitle: row.code + {items.map((row, index) => + index === items.length - 1 ? ( + <StyledDivButton key="Load"> + <Button + color="primary" + variant="text" + // disabled={isLoadingMoreItems} + startIcon={<AddRoundedIcon />} + disabled={isLoadingMoreItems} + onClick={() => { + setCurrPage(currPage + 1) + }} + > + {isLoadingMoreItems ? ( + <CircularProgress size={24} /> + ) : ( + "Carregar mais itens" + )} + </Button> + </StyledDivButton> + ) : ( + <> + <MobileList + key={row.created_at} + title={row.name} + subtitle={row.id} + backColor={"#e81f4f"} + avatar={<TrendingUpRoundedIcon />} + href={`/admin/noteVar/${row.id}`} + reset={() => { + }} + data={ + [ + { + title: "Código", + subtitle: row.code - }, - { - title: "Score Type", - subtitle: row.score_type + }, + { + title: "Score Type", + subtitle: row.score_type - }, - { - title: "Ativo", - subtitle: row.active ? <CheckRoundedIcon style={{ fill: '#3CB371' }} /> : <BlockRoundedIcon style={{ fill: '#FA8072' }} /> - }, - ] - } - /> - <div style={{ height: "0.5em" }} /> - </> - ) - )} - </div> - ) - } - else { - return ( - <div> - <SnackBar - severity={snackInfo.icon} - text={snackInfo.message} - snackbarOpen={snackInfo.open} - color={snackInfo.color} - handleClose={() => setSnackInfo({ - message: '', - icon: '', - open: false, - color: '' - })} - /> - <Paper style={{ padding: '1em' }}> - <Grid container spacing={3} direction="row" alignItems="center"> - <Grid item xs={6}> - <Typography variant="h4"> - Variáveis de nota + }, + { + title: "Ativo", + subtitle: row.active ? <CheckRoundedIcon style={{ fill: '#3CB371' }} /> : <BlockRoundedIcon style={{ fill: '#FA8072' }} /> + }, + ] + } + /> + <div style={{ height: "0.5em" }} /> + </> + ) + )} + </div> + ) + } + else { + return ( + <div> + <SnackBar + severity={snackInfo.icon} + text={snackInfo.message} + snackbarOpen={snackInfo.open} + color={snackInfo.color} + handleClose={() => setSnackInfo({ + message: '', + icon: '', + open: false, + color: '' + })} + /> + <Paper style={{ padding: '1em' }}> + <Grid container spacing={3} direction="row" alignItems="center"> + <Grid item xs={6}> + <Typography variant="h4"> + Variáveis de nota </Typography> - </Grid> - <Grid - item - xs={6} - > - <Grid container justify="flex-end" spacing={3}> - <Grid item> - <Button - variant="contained" - color="secondary" - disabled={isUpdating} - onClick={() => { - currPage = 0 - transformListToAsc = false - UpdateHandler(Url('scores', '', `${currPage}`, 'DESC')) - }} - startIcon={<UpdateRoundedIcon />} - > - { - isUpdating ? <CircularProgress size={24}/> : 'Atualizar' - } - </Button> - </Grid> - </Grid> - </Grid> - </Grid> - </Paper> + </Grid> + <Grid + item + xs={6} + > + <Grid container justify="flex-end" spacing={3}> + <Grid item> + <Button + variant="contained" + color="secondary" + disabled={isUpdating} + onClick={() => { + setCurrPage(0) + }} + startIcon={<UpdateRoundedIcon />} + > + { + isUpdating ? <CircularProgress size={24} /> : 'Atualizar' + } + </Button> + </Grid> + </Grid> + </Grid> + </Grid> + </Paper> - <div style={{ height: '2em' }}></div> + <div style={{ height: '2em' }}></div> - <TableData - top={topTable} - onIconPressed={InvertList} - > - <TableBody> - {items.map((row, index) => ( - index === items.length - 1 ? - <StyledTableRow key={index}> - {/* Button to load more data */} - <StyledTableCell> - <Button - color='primary' - variant='text' - disabled={isLoadingMoreItems} - startIcon={<AddRoundedIcon />} - onClick={() => { - currPage++ - if (transformListToAsc) { - LoadMoreItens(Url('scores', '', `${currPage}`, 'ASC')) - } else { - LoadMoreItens(Url('scores', '', `${currPage}`, 'DESC')) - } - }} - > - { - isLoadingMoreItems ? <CircularProgress /> : 'Carregar mais itens' - } - </Button> - </StyledTableCell> - </StyledTableRow> + <TableData + top={topTable} + > + <TableBody> + {items.map((row, index) => ( + index === items.length - 1 ? + <StyledTableRow key="Load more"> + {/* Button to load more data */} + <StyledTableCell> + <Button + color='primary' + variant='text' + disabled={isLoadingMoreItems} + startIcon={<AddRoundedIcon />} + onClick={() => { + setCurrPage(currPage + 1) + }} + > + { + isLoadingMoreItems ? <CircularProgress /> : 'Carregar mais itens' + } + </Button> + </StyledTableCell> + </StyledTableRow> - : + : - <StyledTableRow key={index}> - <StyledTableCell component="th" scope="row">{row.id}</StyledTableCell> - <StyledTableCell align="right">{row.name}</StyledTableCell> - <StyledTableCell align="right">{row.code}</StyledTableCell> - <StyledTableCell align="right">{row.weight}</StyledTableCell> - <StyledTableCell align="right"> - { - row.active ? <CheckRoundedIcon style={{ fill: '#3CB371' }} /> : <BlockRoundedIcon style={{ fill: '#FA8072' }} /> - } - </StyledTableCell> - <StyledTableCell align="right"> - { - row['score_type'].map((item) => ( - <Typography key={item} style={{ fontSize: 14 }}> - {item} - </Typography> - )) - } - </StyledTableCell> - <StyledTableCell align="right"> - <Link to={`/admin/noteVar/${row.id}`}> - <IconButton onClick={() => { currPage = 0; transformListToAsc = false }}> - <VisibilityIcon style={{ fill: '#00bcd4' }} /> - </IconButton> - </Link> - </StyledTableCell> - </StyledTableRow> - ))} - </TableBody> - </TableData> - </div> - ) - } + <StyledTableRow key={row.created_at}> + <StyledTableCell component="th" scope="row">{row.id}</StyledTableCell> + <StyledTableCell align="right">{row.name}</StyledTableCell> + <StyledTableCell align="right">{row.code}</StyledTableCell> + <StyledTableCell align="right">{row.weight}</StyledTableCell> + <StyledTableCell align="right"> + { + row.active ? <CheckRoundedIcon style={{ fill: '#3CB371' }} /> : <BlockRoundedIcon style={{ fill: '#FA8072' }} /> + } + </StyledTableCell> + <StyledTableCell align="right"> + { + row['score_type'].map((item) => ( + <Typography key={item} style={{ fontSize: 14 }}> + {item} + </Typography> + )) + } + </StyledTableCell> + <StyledTableCell align="right"> + <Link to={`/admin/noteVar/${row.id}`}> + <IconButton> + <VisibilityIcon style={{ fill: '#00bcd4' }} /> + </IconButton> + </Link> + </StyledTableCell> + </StyledTableRow> + ))} + </TableBody> + </TableData> + </div> + ) } + } } diff --git a/src/Admin/Pages/Pages/SubPages/Permissions.js b/src/Admin/Pages/Pages/SubPages/Permissions.js index 456ba0b3..6873c1b5 100644 --- a/src/Admin/Pages/Pages/SubPages/Permissions.js +++ b/src/Admin/Pages/Pages/SubPages/Permissions.js @@ -42,483 +42,408 @@ import styled from "styled-components" import AccountCircleRoundedIcon from "@material-ui/icons/AccountCircleRounded" import MobileList from "../../../Components/Components/MobileComponents/SimpleList" -let currPage = 0; -let transformListToAsc = false; - const StyledTableCell = withStyles((theme) => ({ - head: { - backgroundColor: theme.palette.common.black, - color: theme.palette.common.white, - }, - body: { - fontSize: 14, - }, + head: { + backgroundColor: theme.palette.common.black, + color: theme.palette.common.white, + }, + body: { + fontSize: 14, + }, }))(TableCell); const StyledTableRow = withStyles((theme) => ({ - root: { - '&:nth-of-type(odd)': { - backgroundColor: theme.palette.action.hover, - }, + root: { + '&:nth-of-type(odd)': { + backgroundColor: theme.palette.action.hover, }, + }, }))(TableRow); const UserPermissions = () => { - const ADD_ONE_LENGHT = [""]; - const TOP_LABELS = ['ID', 'NOME', 'DESCRIÇÃO', 'AÇÕES'] //Labels from Table - const WINDOW_WIDTH = window.innerWidth - - const [error, setError] = useState(null); //Necessary to consult the API, catch errors - const [isLoaded, setIsLoaded] = useState(false); //Necessary to consult the API, wait until complete - const [items, setItems] = useState([]); //Necessary to consult the API, data - - const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false) //controlls the state of loadind more data - const [isUpdating, setIsUpdating] = useState(false); //controlls the state of updating data - const [openAlertDialog, setOpenAlertDialog] = useState(false); //controlls the state od alert dialog - - const [deleteItem, setDeleteItem] = useState({}); //Delete Item - const [isLoadingToDelete, setIsLoadingToDelete] = useState(null); - - const [snackInfo, setSnackInfo] = useState({ - message: '', - icon: '', - open: false, - color: '', + const ADD_ONE_LENGHT = [""]; + const TOP_LABELS = ['ID', 'NOME', 'DESCRIÇÃO', 'AÇÕES'] //Labels from Table + const WINDOW_WIDTH = window.innerWidth + + const [error, setError] = useState(null); //Necessary to consult the API, catch errors + const [isLoaded, setIsLoaded] = useState(false); //Necessary to consult the API, wait until complete + const [items, setItems] = useState([]); //Necessary to consult the API, data + const [currPage, setCurrPage] = useState(0) + const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false) //controlls the state of loadind more data + const [isUpdating, setIsUpdating] = useState(false); //controlls the state of updating data + const [openAlertDialog, setOpenAlertDialog] = useState(false); //controlls the state od alert dialog + + const [deleteItem, setDeleteItem] = useState({}); //Delete Item + const [isLoadingToDelete, setIsLoadingToDelete] = useState(null); + + const [snackInfo, setSnackInfo] = useState({ + message: '', + icon: '', + open: false, + color: '', + }) + + //handle snack info + const HandleSnack = (message, state, icon, color) => { + setSnackInfo({ + message: message, + icon: icon, + open: state, + color: color }) - - //handle snack info - const HandleSnack = (message, state, icon, color) => { - setSnackInfo({ - message: message, - icon: icon, - open: state, - color: color - }) - } - - //handle load more items - const LoadMoreItens = async (api) => { - setIsLoadingMoreItems(true) - getRequest( - api, - (data, header) => { - const arrData = [...data] - if (arrData.length === 0) { - HandleSnack('Não há mais dados para serem carregados', true, 'warning', '#FFC125') - } else { - const arrItems = [...items] - arrItems.pop(); //Deleting the last position, that was used to display the button of load more items - const arrResult = arrItems.concat(arrData) - setItems(arrResult.concat(ADD_ONE_LENGHT)) - } - setIsLoadingMoreItems(false) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - setIsLoadingMoreItems(false) - } - ) - } - - // handle update list data - const UpdateHandler = async (api) => { - setIsUpdating(true) - getRequest( - api, - (data, header) => { - HandleSnack('A lista de dados foi atualizada', true, 'success', '#228B22') - const arrData = [...data] - setItems(arrData.concat(ADD_ONE_LENGHT)) - setIsUpdating(false) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - setIsUpdating(false) - } - ) - } - - //handle Delete - async function DeleteHandler() { - const id = deleteItem.id; - HandleStateAlertDialog(null); - deleteRequest( - DeleteFilter("roles", id), - (data) => { - if (data.errors) - HandleSnack("Ocorreu algum erro", true, "warning", "#FA8072"); - else { - HandleSnack( - "A língua foi deletada com sucesso", - true, - "success", - "#228B22" - ); - currPage = 0; - transformListToAsc = false - UpdateHandler(Url("roles", "", `${currPage}`, "DESC")); - HandleStateCircularProgress(null); - } - }, - (error) => { - HandleSnack("Ocorreu algum erro", true, "warning", "#FA8072"); - HandleStateCircularProgress(null); - } - ) - } - - const HandleStateCircularProgress = (i) => { - setIsLoadingToDelete(i); - }; - - const HandleStateAlertDialog = (i) => { - const obj = { ...items[i] }; - setDeleteItem(obj); - setOpenAlertDialog(!openAlertDialog); - }; - - const InvertList = async () => { - transformListToAsc = !transformListToAsc - currPage = 0 - if (transformListToAsc) { - getRequest( - Url('roles', '', `${currPage}`, 'ASC'), - (data, header) => { - const arrData = [...data] - setItems(arrData.concat(ADD_ONE_LENGHT)) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - } - ) + } + + //handle Delete + async function DeleteHandler() { + const id = deleteItem.id; + HandleStateAlertDialog(null); + deleteRequest( + DeleteFilter("roles", id), + (data) => { + if (data.errors) + HandleSnack("Ocorreu algum erro", true, "warning", "#FA8072"); + else { + HandleSnack( + "A língua foi deletada com sucesso", + true, + "success", + "#228B22" + ); + setCurrPage(0) + HandleStateCircularProgress(null); + } + }, + (error) => { + HandleSnack("Ocorreu algum erro", true, "warning", "#FA8072"); + HandleStateCircularProgress(null); + } + ) + } + + const HandleStateCircularProgress = (i) => { + setIsLoadingToDelete(i); + }; + + const HandleStateAlertDialog = (i) => { + const obj = { ...items[i] }; + setDeleteItem(obj); + setOpenAlertDialog(!openAlertDialog); + }; + + useEffect(() => { + if (currPage === 0) + setIsLoaded(false) + else + setIsLoadingMoreItems(true) + getRequest( + Url("roles", "", currPage, "DESC"), + (data, header) => { + const arrData = [...data] + if (arrData.length === 0) { + HandleSnack('Não há mais dados para serem carregados', true, 'warning', '#FFC125') } else { - getRequest( - Url('roles', '', `${currPage}`, 'DESC'), - (data, header) => { - const arrData = [...data] - setItems(arrData.concat(ADD_ONE_LENGHT)) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - } - ) + const arrItems = [...items] + if (currPage === 0) { + setItems(arrData.concat(ADD_ONE_LENGHT)) + } + else { + arrItems.pop(); //Deleting the last position, that was used to display the button of load more items + const arrResult = arrItems.concat(arrData) + setItems(arrResult.concat(ADD_ONE_LENGHT)) + } } - } - - //getting data from server - useEffect(() => { - getRequest( - Url('roles', '', `${currPage}`, 'DESC'), - (data, header) => { - setIsLoaded(true); - setItems(data.concat(ADD_ONE_LENGHT)); - }, - (error) => { - setError(true); - } - ) - }, []); - - - if (error) { - return <div>Error: {error.message}</div>; - } else if (!isLoaded) { - return <LoadingSpinner text="Carregando..." /> - } else { - if (WINDOW_WIDTH <= 760) { - return ( - <> - <SnackBar - severity={snackInfo.icon} - text={snackInfo.message} - snackbarOpen={snackInfo.open} - color={snackInfo.color} - handleClose={() => setSnackInfo({ - message: '', - icon: '', - open: false, - color: '' - })} - /> - <AlertDialog - open={openAlertDialog} - OnDelete={DeleteHandler} - deleteItem={deleteItem} - HandleClose={() => { - setOpenAlertDialog(false); - HandleStateCircularProgress(null); - }} - /> - <Paper style={{ padding: '1em' }}> - <Grid container spacing={3} direction="row" alignItems="center"> - <Grid item xs={12}> - <Typography variant="h4"> - Lista de permissões de usuário + setIsLoaded(true) + setIsLoadingMoreItems(false) + }, + (error) => { + HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') + setIsLoadingMoreItems(false) + setIsLoaded(true) + setError(true) + } + ) + }, [currPage]) + + + if (error) { + return <div>Error: {error.message}</div>; + } else if (!isLoaded) { + return <LoadingSpinner text="Carregando..." /> + } else { + if (WINDOW_WIDTH <= 800) { + return ( + <> + <SnackBar + severity={snackInfo.icon} + text={snackInfo.message} + snackbarOpen={snackInfo.open} + color={snackInfo.color} + handleClose={() => setSnackInfo({ + message: '', + icon: '', + open: false, + color: '' + })} + /> + <AlertDialog + open={openAlertDialog} + OnDelete={DeleteHandler} + deleteItem={deleteItem} + HandleClose={() => { + setOpenAlertDialog(false); + HandleStateCircularProgress(null); + }} + /> + <Paper style={{ padding: '1em' }}> + <Grid container spacing={3} direction="row" alignItems="center"> + <Grid item xs={12}> + <Typography variant="h4"> + Lista de permissões de usuário </Typography> - </Grid> - <Grid - item - xs={12} - > - <Grid container justify="flex-start" spacing={3}> - <Grid item> - <Button - variant="contained" - color="secondary" - disabled={isUpdating} - onClick={() => { - currPage = 0 - transformListToAsc = false - UpdateHandler(Url('roles', '', `${currPage}`, 'DESC')) - }} - startIcon={<UpdateRoundedIcon />} - > - { - isUpdating ? <CircularProgress size={24} /> : 'Atualizar' - } - </Button> - </Grid> - <Grid item> - <Link style={{ textDecoration: 'none' }} to={'/admin/CreateRole'}> - <Button - variant="contained" - color="secondary" - startIcon={<AddRoundedIcon />} - onClick={() => { currPage = 0 }} - > - Novo + </Grid> + <Grid + item + xs={12} + > + <Grid container justify="flex-start" spacing={3}> + <Grid item> + <Button + variant="contained" + color="secondary" + disabled={isUpdating} + onClick={() => { + setCurrPage(0) + }} + startIcon={<UpdateRoundedIcon />} + > + { + isUpdating ? <CircularProgress size={24} /> : 'Atualizar' + } + </Button> + </Grid> + <Grid item> + <Link style={{ textDecoration: 'none' }} to={'/admin/CreateRole'}> + <Button + variant="contained" + color="secondary" + startIcon={<AddRoundedIcon />} + > + Novo </Button> - </Link> - </Grid> - </Grid> - </Grid> - </Grid> - </Paper> - - <div style={{ height: '2em' }}></div> - - {items.map((row, index) => - index === items.length - 1 ? ( - <StyledDivButton> - <Button - key={index} - color="primary" - variant="text" - // disabled={isLoadingMoreItems} - startIcon={<AddRoundedIcon />} - disabled={isLoadingMoreItems} - onClick={() => { - currPage++ - if (transformListToAsc) { - LoadMoreItens(Url('roles', '', `${currPage}`, 'ASC')) - } else { - LoadMoreItens(Url('roles', '', `${currPage}`, 'DESC')) - } - }} - > - {isLoadingMoreItems ? ( - <CircularProgress size={24} /> - ) : ( - "Carregar mais itens" - )} - </Button> - </StyledDivButton> - ) : ( - <> - <MobileList - key={index} - title={row.name} - subtitle={row.id} - backColor={"#ff7f00"} - avatar={<AccountCircleRoundedIcon />} - href={`/admin/EditPermissions/${row.id}`} - reset={() => { - currPage = 0; - }} - data={ - [ - { - title: "Descrição", - subtitle: row.description - - }, - { - title: "Ações", - subtitle: <Button - variant="contained" - color="secondary" - onClick={() => { - HandleStateAlertDialog(index) - HandleStateCircularProgress(index) - }} - startIcon={<DeleteRoundedIcon />} - > - Deletar - </Button> - }, - ] - } - /> - <div style={{ height: "0.5em" }} /> - </> - ) + </Link> + </Grid> + </Grid> + </Grid> + </Grid> + </Paper> + + <div style={{ height: '2em' }}></div> + + {items.map((row, index) => + index === items.length - 1 ? ( + <StyledDivButton key="Load"> + <Button + color="primary" + variant="text" + // disabled={isLoadingMoreItems} + startIcon={<AddRoundedIcon />} + disabled={isLoadingMoreItems} + onClick={() => { + setCurrPage(currPage + 1) + }} + > + {isLoadingMoreItems ? ( + <CircularProgress size={24} /> + ) : ( + "Carregar mais itens" )} - </> - ); - } - else { - return ( + </Button> + </StyledDivButton> + ) : ( <> - <SnackBar - severity={snackInfo.icon} - text={snackInfo.message} - snackbarOpen={snackInfo.open} - color={snackInfo.color} - handleClose={() => setSnackInfo({ - message: '', - icon: '', - open: false, - color: '' - })} - /> - - <Paper style={{ padding: '1em' }}> - <Grid container spacing={3} direction="row" alignItems="center"> - <Grid item xs={6}> - <Typography variant="h4"> - Lista de permissões de usuário + <MobileList + key={row.created_at} + title={row.name} + subtitle={row.id} + backColor={"#ff7f00"} + avatar={<AccountCircleRoundedIcon />} + href={`/admin/EditPermissions/${row.id}`} + reset={() => { + }} + data={ + [ + { + title: "Descrição", + subtitle: row.description + + }, + { + title: "Ações", + subtitle: <Button + variant="contained" + color="secondary" + onClick={() => { + HandleStateAlertDialog(index) + HandleStateCircularProgress(index) + }} + startIcon={<DeleteRoundedIcon />} + > + Deletar + </Button> + }, + ] + } + /> + <div style={{ height: "0.5em" }} /> + </> + ) + )} + </> + ); + } + else { + return ( + <> + <SnackBar + severity={snackInfo.icon} + text={snackInfo.message} + snackbarOpen={snackInfo.open} + color={snackInfo.color} + handleClose={() => setSnackInfo({ + message: '', + icon: '', + open: false, + color: '' + })} + /> + + <Paper style={{ padding: '1em' }}> + <Grid container spacing={3} direction="row" alignItems="center"> + <Grid item xs={6}> + <Typography variant="h4"> + Lista de permissões de usuário </Typography> - </Grid> - <Grid - item - xs={6} - > - <Grid container justify="flex-end" spacing={3}> - <Grid item> - <Button - variant="contained" - color="secondary" - disabled={isUpdating} - onClick={() => { - currPage = 0 - transformListToAsc = false - UpdateHandler(Url('roles', '', `${currPage}`, 'DESC')) - }} - startIcon={<UpdateRoundedIcon />} - > - { - isUpdating ? <CircularProgress size={24} /> : 'Atualizar' - } - </Button> - </Grid> - <Grid item> - - <Link style={{ textDecoration: 'none' }} to={'/admin/CreateRole'}> - <Button - variant="contained" - color="secondary" - startIcon={<AddRoundedIcon />} - onClick={() => { currPage = 0 }} - > - Novo - </Button> - </Link> - </Grid> - </Grid> - </Grid> - </Grid> - </Paper> - - <div style={{ height: '2em' }}></div> - - <TableData - top={TOP_LABELS} - onIconPressed={InvertList} + </Grid> + <Grid + item + xs={6} + > + <Grid container justify="flex-end" spacing={3}> + <Grid item> + <Button + variant="contained" + color="secondary" + disabled={isUpdating} + onClick={() => { + setCurrPage(0) + }} + startIcon={<UpdateRoundedIcon />} > - <TableBody> - {items.map((row, index) => ( - index === items.length - 1 ? - <StyledTableRow key={index}> - {/* Button to load more data */} - <StyledTableCell> - <Button - color='primary' - variant='text' - // disabled={isLoadingMoreItems} - startIcon={<AddRoundedIcon />} - disabled={isLoadingMoreItems} - onClick={() => { - currPage++ - if (transformListToAsc) { - LoadMoreItens(Url('roles', '', `${currPage}`, 'ASC')) - } else { - LoadMoreItens(Url('roles', '', `${currPage}`, 'DESC')) - } - }} - > - { - isLoadingMoreItems ? <CircularProgress size={24} /> : 'Carregar mais itens' - } + { + isUpdating ? <CircularProgress size={24} /> : 'Atualizar' + } + </Button> + </Grid> + <Grid item> + + <Link style={{ textDecoration: 'none' }} to={'/admin/CreateRole'}> + <Button + variant="contained" + color="secondary" + startIcon={<AddRoundedIcon />} + > + Novo </Button> - </StyledTableCell> - </StyledTableRow> - - : - - <StyledTableRow key={index}> - <StyledTableCell component="th" scope="row">{row.id}</StyledTableCell> - <StyledTableCell align="right">{row.name}</StyledTableCell> - <StyledTableCell align="right">{row.description}</StyledTableCell> - <StyledTableCell align="right"> - <Link to={`/admin/EditPermissions/${row.id}`}> - <Button - style={{ width: "100%", marginBottom: "0.5em" }} - variant="contained" - color="primary" - onClick={() => { currPage = 0 }} - startIcon={<EditRoundedIcon />} - > - Editar - </Button> - </Link> - - {isLoadingToDelete === index ? ( - <CircularProgress size={24} color="primary" /> - ) : ( - <Button - style={{ width: "100%" }} - variant="contained" - color="secondary" - onClick={() => { - HandleStateAlertDialog(index) - HandleStateCircularProgress(index) - }} - startIcon={<DeleteRoundedIcon />} - > - Deletar - </Button> - )} - - </StyledTableCell> - </StyledTableRow> - ))} - </TableBody> - </TableData> - - {/* This alert will be displayed if the user click to delete an institution */} - <AlertDialog - open={openAlertDialog} - OnDelete={DeleteHandler} - deleteItem={deleteItem} - HandleClose={() => { - setOpenAlertDialog(false); - HandleStateCircularProgress(null); + </Link> + </Grid> + </Grid> + </Grid> + </Grid> + </Paper> + + <div style={{ height: '2em' }}></div> + + <TableData + top={TOP_LABELS} + > + <TableBody> + {items.map((row, index) => ( + index === items.length - 1 ? + <StyledTableRow key="Load more"> + {/* Button to load more data */} + <StyledTableCell> + <Button + color='primary' + variant='text' + // disabled={isLoadingMoreItems} + startIcon={<AddRoundedIcon />} + disabled={isLoadingMoreItems} + onClick={() => { + setCurrPage(currPage + 1) }} - /> - </> - ); - } + > + { + isLoadingMoreItems ? <CircularProgress size={24} /> : 'Carregar mais itens' + } + </Button> + </StyledTableCell> + </StyledTableRow> + + : + + <StyledTableRow key={row.created_at}> + <StyledTableCell component="th" scope="row">{row.id}</StyledTableCell> + <StyledTableCell align="right">{row.name}</StyledTableCell> + <StyledTableCell align="right">{row.description}</StyledTableCell> + <StyledTableCell align="right"> + <Link to={`/admin/EditPermissions/${row.id}`}> + <Button + style={{ width: "100%", marginBottom: "0.5em" }} + variant="contained" + color="primary" + startIcon={<EditRoundedIcon />} + > + Editar + </Button> + </Link> + + {isLoadingToDelete === index ? ( + <CircularProgress size={24} color="primary" /> + ) : ( + <Button + style={{ width: "100%" }} + variant="contained" + color="secondary" + onClick={() => { + HandleStateAlertDialog(index) + HandleStateCircularProgress(index) + }} + startIcon={<DeleteRoundedIcon />} + > + Deletar + </Button> + )} + + </StyledTableCell> + </StyledTableRow> + ))} + </TableBody> + </TableData> + + {/* This alert will be displayed if the user click to delete an institution */} + <AlertDialog + open={openAlertDialog} + OnDelete={DeleteHandler} + deleteItem={deleteItem} + HandleClose={() => { + setOpenAlertDialog(false); + HandleStateCircularProgress(null); + }} + /> + </> + ); } + } } export default UserPermissions; diff --git a/src/Admin/Pages/Pages/SubPages/Questions.js b/src/Admin/Pages/Pages/SubPages/Questions.js index 8118ec31..70674a9a 100644 --- a/src/Admin/Pages/Pages/SubPages/Questions.js +++ b/src/Admin/Pages/Pages/SubPages/Questions.js @@ -44,525 +44,451 @@ import styled from "styled-components" import MobileList from "../../../Components/Components/MobileComponents/SimpleList" import HelpRoundedIcon from "@material-ui/icons/HelpRounded"; -let currPage = 0; -let transformListToAsc = false; - const StyledTableCell = withStyles((theme) => ({ - head: { - backgroundColor: theme.palette.common.black, - color: theme.palette.common.white, - }, - body: { - fontSize: 14, - }, + head: { + backgroundColor: theme.palette.common.black, + color: theme.palette.common.white, + }, + body: { + fontSize: 14, + }, }))(TableCell); const StyledTableRow = withStyles((theme) => ({ - root: { - '&:nth-of-type(odd)': { - backgroundColor: theme.palette.action.hover, - }, + root: { + '&:nth-of-type(odd)': { + backgroundColor: theme.palette.action.hover, }, + }, }))(TableRow); const Questions = () => { - const { state } = useContext(Store); - - const ADD_ONE_LENGHT = [""]; - const WINDOW_WIDTH = window.innerWidth - const TOP_LABELS = ['ID', 'CRIAÇÃO EM', 'DESCRIÇÃO', 'STATUS', 'ATUALIZAÇÃO EM'] //Labels from Table - - const [error, setError] = useState(null); //Necessary to consult the API, catch errors - const [isLoaded, setIsLoaded] = useState(false); //Necessary to consult the API, wait until complete - const [items, setItems] = useState([]); //Necessary to consult the API, data - - const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false) //controlls the state of loadind more data - const [isUpdating, setIsUpdating] = useState(false); //controlls the state of updating data - - const [snackInfo, setSnackInfo] = useState({ - message: '', - icon: '', - open: false, - color: '', + const { state } = useContext(Store); + + const ADD_ONE_LENGHT = [""]; + const WINDOW_WIDTH = window.innerWidth + const TOP_LABELS = ['ID', 'CRIAÇÃO EM', 'DESCRIÇÃO', 'STATUS', 'ATUALIZAÇÃO EM'] //Labels from Table + + const [error, setError] = useState(null); //Necessary to consult the API, catch errors + const [isLoaded, setIsLoaded] = useState(false); //Necessary to consult the API, wait until complete + const [items, setItems] = useState([]); //Necessary to consult the API, data + const [currPage, setCurrPage] = useState(0) + const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false) //controlls the state of loadind more data + const [isUpdating, setIsUpdating] = useState(false); //controlls the state of updating data + + const [snackInfo, setSnackInfo] = useState({ + message: '', + icon: '', + open: false, + color: '', + }) + + //handle snack info + const HandleSnack = (message, state, icon, color) => { + setSnackInfo({ + message: message, + icon: icon, + open: state, + color: color }) + } - //handle snack info - const HandleSnack = (message, state, icon, color) => { - setSnackInfo({ - message: message, - icon: icon, - open: state, - color: color - }) - } - - const CheckUserPermission = () => { - let canUserEdit = false; + const CheckUserPermission = () => { + let canUserEdit = false; - if (state.userIsLoggedIn) { - const roles = [...state.currentUser.roles]; - for (let i = 0; i < roles.length; i++) - if (roles[i].name === 'admin') - canUserEdit = true; - } - else { - canUserEdit = false; - } - - return canUserEdit; + if (state.userIsLoggedIn) { + const roles = [...state.currentUser.roles]; + for (let i = 0; i < roles.length; i++) + if (roles[i].name === 'admin') + canUserEdit = true; } - - //handle load more items - const LoadMoreItens = async (api) => { - setIsLoadingMoreItems(true) - getRequest( - api, - (data, header) => { - const arrData = [...data] - if (arrData.length === 0) { - HandleSnack('Não há mais dados para serem carregados', true, 'warning', '#FFC125') - } else { - const arrItems = [...items] - arrItems.pop(); //Deleting the last position, that was used to display the button of load more items - const arrResult = arrItems.concat(arrData) - setItems(arrResult.concat(ADD_ONE_LENGHT)) - } - setIsLoadingMoreItems(false) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - setIsLoadingMoreItems(false) - } - ) + else { + canUserEdit = false; } - // handle update list data - const UpdateHandler = async (api) => { - setIsUpdating(true) - getRequest( - api, - (data, header) => { - HandleSnack('A lista de dados foi atualizada', true, 'success', '#228B22') - const arrData = [...data] - setItems(arrData.concat(ADD_ONE_LENGHT)) - setIsUpdating(false) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - setIsUpdating(false) - } - ) - } - - const InvertList = async () => { - transformListToAsc = !transformListToAsc - currPage = 0 - if (transformListToAsc) { - getRequest( - Url('questions', '', `${currPage}`, 'ASC'), - (data, header) => { - const arrData = [...data] - setItems(arrData.concat(ADD_ONE_LENGHT)) - }, - () => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - } - ) - } else { - getRequest( - Url('questions', '', `${currPage}`, 'DESC'), - (data, header) => { - const arrData = [...data] - setItems(arrData.concat(ADD_ONE_LENGHT)) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - } - ) + return canUserEdit; + } + + const handleChange = async (index, status) => { + const id = items[index].id; + const description = items[index].description; + if (status === 'active') { + const body = { + "question": { + "description": description, + "status": "inactive" } + } + putRequest( + EditFilter('questions', id), + body, + (data) => { + if (data.errors) + HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') + else { + setCurrPage(0) + } + }, + (error) => { + HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') + } + ) + } else { + const body = { + "question": { + "description": description, + "status": "active" + } + } + putRequest( + EditFilter('questions', id), + body, + (data) => { + if (data.errors) + HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') + else { + setCurrPage(0) + } + }, + (error) => { + HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') + } + ) } - - const handleChange = async (index, status) => { - const id = items[index].id; - const description = items[index].description; - if (status === 'active') { - const body = { - "question": { - "description": description, - "status": "inactive" - } - } - putRequest( - EditFilter('questions', id), - body, - (data) => { - if (data.errors) - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - else { - currPage = 0 - transformListToAsc = false - UpdateHandler(Url('questions', '', `${currPage}`, 'DESC')) - } - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - } - ) + } + + const DisplayDate = (date) => { + const convertedData = moment.utc(date); + return moment(convertedData) + .format("LLL") + .toString(); + }; + + useEffect(() => { + if (currPage === 0) + setIsLoaded(false) + else + setIsLoadingMoreItems(true) + getRequest( + Url("questions", "", currPage, "DESC"), + (data, header) => { + const arrData = [...data] + if (arrData.length === 0) { + HandleSnack('Não há mais dados para serem carregados', true, 'warning', '#FFC125') } else { - const body = { - "question": { - "description": description, - "status": "active" - } - } - putRequest( - EditFilter('questions', id), - body, - (data) => { - if (data.errors) - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - else { - currPage = 0 - transformListToAsc = false - UpdateHandler(Url('questions', '', `${currPage}`, 'DESC')) - } - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - } - ) + const arrItems = [...items] + if (currPage === 0) { + setItems(arrData.concat(ADD_ONE_LENGHT)) + } + else { + arrItems.pop(); //Deleting the last position, that was used to display the button of load more items + const arrResult = arrItems.concat(arrData) + setItems(arrResult.concat(ADD_ONE_LENGHT)) + } } - } - - const DisplayDate = (date) => { - const convertedData = moment.utc(date); - return moment(convertedData) - .format("LLL") - .toString(); - }; - - //getting data from server - useEffect(() => { - getRequest( - Url('questions', '', `${currPage}`, 'DESC'), - (data, header) => { - setIsLoaded(true); - setItems(data.concat(ADD_ONE_LENGHT)); - }, - (error) => { - setError(true) - } - ) - }, []); - - - if (error) { - return <div>Error: {error.message}</div>; - } else if (!isLoaded) { - return <LoadingSpinner text="Carregando..." /> - } else if (CheckUserPermission()) { - if (WINDOW_WIDTH <= 761) { - return ( - <> - <SnackBar - severity={snackInfo.icon} - text={snackInfo.message} - snackbarOpen={snackInfo.open} - color={snackInfo.color} - handleClose={() => setSnackInfo({ - message: '', - icon: '', - open: false, - color: '' - })} - /> - - <Paper style={{ padding: '1em' }}> - <Grid container spacing={3} direction="row" alignItems="center"> - <Grid item xs={12}> - <Typography variant="h4"> - Perguntas da curadoria + setIsLoaded(true) + setIsLoadingMoreItems(false) + }, + (error) => { + HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') + setIsLoadingMoreItems(false) + setIsLoaded(true) + setError(true) + } + ) + }, [currPage]) + + + if (error) { + return <div>Error: {error.message}</div>; + } else if (!isLoaded) { + return <LoadingSpinner text="Carregando..." /> + } else if (CheckUserPermission()) { + if (WINDOW_WIDTH <= 800) { + return ( + <> + <SnackBar + severity={snackInfo.icon} + text={snackInfo.message} + snackbarOpen={snackInfo.open} + color={snackInfo.color} + handleClose={() => setSnackInfo({ + message: '', + icon: '', + open: false, + color: '' + })} + /> + + <Paper style={{ padding: '1em' }}> + <Grid container spacing={3} direction="row" alignItems="center"> + <Grid item xs={12}> + <Typography variant="h4"> + Perguntas da curadoria </Typography> - </Grid> - <Grid - item - xs={12} - > - <Grid container justify="flex-start" spacing={3}> - <Grid item> - <Button - variant="contained" - color="secondary" - disabled={isUpdating} - onClick={() => { - currPage = 0 - transformListToAsc = false - UpdateHandler(Url('questions', '', `${currPage}`, 'DESC')) - }} - startIcon={<UpdateRoundedIcon />} - > - { - isUpdating ? <CircularProgress size={24} /> : 'Atualizar' - } - </Button> - </Grid> - <Grid item> - - <Link style={{ textDecoration: 'none' }} to={'/admin/CreateQuestion'}> - <Button - variant="contained" - color="secondary" - startIcon={<AddRoundedIcon />} - onClick={() => { currPage = 0 }} - > - Novo + </Grid> + <Grid + item + xs={12} + > + <Grid container justify="flex-start" spacing={3}> + <Grid item> + <Button + variant="contained" + color="secondary" + disabled={isUpdating} + onClick={() => { + setCurrPage(0) + }} + startIcon={<UpdateRoundedIcon />} + > + { + isUpdating ? <CircularProgress size={24} /> : 'Atualizar' + } + </Button> + </Grid> + <Grid item> + + <Link style={{ textDecoration: 'none' }} to={'/admin/CreateQuestion'}> + <Button + variant="contained" + color="secondary" + startIcon={<AddRoundedIcon />} + > + Novo </Button> - </Link> - </Grid> + </Link> + </Grid> + </Grid> + </Grid> + </Grid> + </Paper> + + <div style={{ height: '2em' }}></div> + + {items.map((row, index) => + index === items.length - 1 ? ( + <StyledDivButton + key="Load" + > + <Button + color="primary" + variant="text" + // disabled={isLoadingMoreItems} + startIcon={<AddRoundedIcon />} + disabled={isLoadingMoreItems} + onClick={() => { + setCurrPage(currPage + 1) + }} + > + {isLoadingMoreItems ? ( + <CircularProgress size={24} /> + ) : ( + "Carregar mais itens" + )} + </Button> + </StyledDivButton> + ) : ( + <> + <MobileList + key={row.created_at} + title={row.id} + subtitle={DisplayDate(row.created_at)} + backColor={"#673ab7"} + avatar={<HelpRoundedIcon />} + reset={() => { + }} + data={ + [ + { + title: "Descrição", + subtitle: row.description + }, + { + title: "Status", + subtitle: + row.status === 'active' ? + <Grid container direction='row'> + <Grid item> + <CheckCircleRoundedIcon style={{ fill: '#3CB371' }} /> + + <Switch + checked={true} + onChange={() => handleChange(index, row.status)} + name="checkedB" + color="primary" + /> </Grid> - </Grid> - </Grid> - </Paper> + </Grid> - <div style={{ height: '2em' }}></div> + : - {items.map((row, index) => - index === items.length - 1 ? ( - <StyledDivButton> - <Button - key={index} + <Grid container justify='flex-end' alignItems='center' direction='row'> + <Grid item> + <CancelRoundedIcon style={{ fill: '#FA8072' }} /> + </Grid> + + <Grid item> + <Switch + checked={false} + onChange={() => handleChange(index, row.status)} + name="checkedB" color="primary" - variant="text" - // disabled={isLoadingMoreItems} - startIcon={<AddRoundedIcon />} - disabled={isLoadingMoreItems} - onClick={() => { - currPage++ - if (transformListToAsc) { - LoadMoreItens(Url('questions', '', `${currPage}`, 'ASC')) - } else { - LoadMoreItens(Url('questions', '', `${currPage}`, 'DESC')) - } - }} - > - {isLoadingMoreItems ? ( - <CircularProgress size={24} /> - ) : ( - "Carregar mais itens" - )} - </Button> - </StyledDivButton> - ) : ( - <> - <MobileList - key={index} - title={row.id} - subtitle={DisplayDate(row.created_at)} - backColor={"#673ab7"} - avatar={<HelpRoundedIcon />} - reset={() => { - currPage = 0; transformListToAsc = false - }} - data={ - [ - { - title: "Descrição", - subtitle: row.description - }, - { - title: "Status", - subtitle: - row.status === 'active' ? - <Grid container direction='row'> - <Grid item> - <CheckCircleRoundedIcon style={{ fill: '#3CB371' }} /> - - <Switch - checked={true} - onChange={() => handleChange(index, row.status)} - name="checkedB" - color="primary" - /> - </Grid> - </Grid> - - : - - <Grid container justify='flex-end' alignItems='center' direction='row'> - <Grid item> - <CancelRoundedIcon style={{ fill: '#FA8072' }} /> - </Grid> - - <Grid item> - <Switch - checked={false} - onChange={() => handleChange(index, row.status)} - name="checkedB" - color="primary" - /> - </Grid> - </Grid> - }, - { - title : "Atualizado em", - subtitle : DisplayDate(row.updated_at) - } - ] - } - /> - <div style={{ height: "0.5em" }} /> - </> - ) - )} + /> + </Grid> + </Grid> + }, + { + title: "Atualizado em", + subtitle: DisplayDate(row.updated_at) + } + ] + } + /> + <div style={{ height: "0.5em" }} /> </> - ); - } - else { - return ( - <> - <SnackBar - severity={snackInfo.icon} - text={snackInfo.message} - snackbarOpen={snackInfo.open} - color={snackInfo.color} - handleClose={() => setSnackInfo({ - message: '', - icon: '', - open: false, - color: '' - })} - /> - - <Paper style={{ padding: '1em' }}> - <Grid container spacing={3} direction="row" alignItems="center"> - <Grid item xs={6}> - <Typography variant="h4"> - Perguntas da curadoria + ) + )} + </> + ); + } + else { + return ( + <> + <SnackBar + severity={snackInfo.icon} + text={snackInfo.message} + snackbarOpen={snackInfo.open} + color={snackInfo.color} + handleClose={() => setSnackInfo({ + message: '', + icon: '', + open: false, + color: '' + })} + /> + + <Paper style={{ padding: '1em' }}> + <Grid container spacing={3} direction="row" alignItems="center"> + <Grid item xs={6}> + <Typography variant="h4"> + Perguntas da curadoria </Typography> - </Grid> - <Grid - item - xs={6} - > - <Grid container justify="flex-end" spacing={3}> - <Grid item> - <Button - variant="contained" - color="secondary" - disabled={isUpdating} - onClick={() => { - currPage = 0 - transformListToAsc = false - UpdateHandler(Url('questions', '', `${currPage}`, 'DESC')) - }} - startIcon={<UpdateRoundedIcon />} - > - { - isUpdating ? <CircularProgress size={24} /> : 'Atualizar' - } - </Button> - </Grid> - <Grid item> - - <Link style={{ textDecoration: 'none' }} to={'/admin/CreateQuestion'}> - <Button - variant="contained" - color="secondary" - startIcon={<AddRoundedIcon />} - onClick={() => { currPage = 0; transformListToAsc = false }} - > - Novo + </Grid> + <Grid + item + xs={6} + > + <Grid container justify="flex-end" spacing={3}> + <Grid item> + <Button + variant="contained" + color="secondary" + disabled={isUpdating} + onClick={() => { + setCurrPage(0) + }} + startIcon={<UpdateRoundedIcon />} + > + { + isUpdating ? <CircularProgress size={24} /> : 'Atualizar' + } + </Button> + </Grid> + <Grid item> + + <Link style={{ textDecoration: 'none' }} to={'/admin/CreateQuestion'}> + <Button + variant="contained" + color="secondary" + startIcon={<AddRoundedIcon />} + > + Novo </Button> - </Link> - </Grid> - </Grid> + </Link> + </Grid> + </Grid> + </Grid> + </Grid> + </Paper> + + <div style={{ height: '2em' }}></div> + + <TableData + top={TOP_LABELS} + > + <TableBody> + {items.map((row, index) => ( + index === items.length - 1 ? + <StyledTableRow key="Load more"> + {/* Button to load more data */} + <StyledTableCell> + <Button + color='primary' + variant='text' + // disabled={isLoadingMoreItems} + startIcon={<AddRoundedIcon />} + disabled={isLoadingMoreItems} + onClick={() => { + setCurrPage(currPage + 1) + }} + > + { + isLoadingMoreItems ? <CircularProgress size={24} /> : 'Carregar mais itens' + } + </Button> + </StyledTableCell> + </StyledTableRow> + + : + + <StyledTableRow key={row.created_at}> + <StyledTableCell component="th" scope="row">{row.id}</StyledTableCell> + <StyledTableCell align="right">{DisplayDate(row.created_at)}</StyledTableCell> + <StyledTableCell align="right">{row.description}</StyledTableCell> + <StyledTableCell align="right"> + { + row.status === 'active' ? + <Grid container direction='row'> + <Grid item> + <CheckCircleRoundedIcon style={{ fill: '#3CB371' }} /> + + <Switch + checked={true} + onChange={() => handleChange(index, row.status)} + name="checkedB" + color="primary" + /> </Grid> - </Grid> - </Paper> + </Grid> - <div style={{ height: '2em' }}></div> + : - <TableData - top={TOP_LABELS} - onIconPressed={InvertList} - > - <TableBody> - {items.map((row, index) => ( - index === items.length - 1 ? - <StyledTableRow key={index}> - {/* Button to load more data */} - <StyledTableCell> - <Button - color='primary' - variant='text' - // disabled={isLoadingMoreItems} - startIcon={<AddRoundedIcon />} - disabled={isLoadingMoreItems} - onClick={() => { - currPage++ - if (transformListToAsc) { - LoadMoreItens(Url('questions', '', `${currPage}`, 'ASC')) - } else { - LoadMoreItens(Url('questions', '', `${currPage}`, 'DESC')) - } - }} - > - { - isLoadingMoreItems ? <CircularProgress size={24} /> : 'Carregar mais itens' - } - </Button> - </StyledTableCell> - </StyledTableRow> - - : - - <StyledTableRow key={index}> - <StyledTableCell component="th" scope="row">{row.id}</StyledTableCell> - <StyledTableCell align="right">{DisplayDate(row.created_at)}</StyledTableCell> - <StyledTableCell align="right">{row.description}</StyledTableCell> - <StyledTableCell align="right"> - { - row.status === 'active' ? - <Grid container direction='row'> - <Grid item> - <CheckCircleRoundedIcon style={{ fill: '#3CB371' }} /> - - <Switch - checked={true} - onChange={() => handleChange(index, row.status)} - name="checkedB" - color="primary" - /> - </Grid> - </Grid> - - : - - <Grid container justify='flex-end' alignItems='center' direction='row'> - <Grid item> - <CancelRoundedIcon style={{ fill: '#FA8072' }} /> - </Grid> - - <Grid item> - <Switch - checked={false} - onChange={() => handleChange(index, row.status)} - name="checkedB" - color="primary" - /> - </Grid> - </Grid> - } - </StyledTableCell> - <StyledTableCell align="right">{DisplayDate(row.updated_at)}</StyledTableCell> - </StyledTableRow> - ))} - </TableBody> - </TableData> - </> - ); - } - } else return <Unauthorized /> + <Grid container justify='flex-end' alignItems='center' direction='row'> + <Grid item> + <CancelRoundedIcon style={{ fill: '#FA8072' }} /> + </Grid> + + <Grid item> + <Switch + checked={false} + onChange={() => handleChange(index, row.status)} + name="checkedB" + color="primary" + /> + </Grid> + </Grid> + } + </StyledTableCell> + <StyledTableCell align="right">{DisplayDate(row.updated_at)}</StyledTableCell> + </StyledTableRow> + ))} + </TableBody> + </TableData> + </> + ); + } + } else return <Unauthorized /> } export default Questions; diff --git a/src/Admin/Pages/Pages/SubPages/Rating.js b/src/Admin/Pages/Pages/SubPages/Rating.js index 547e140d..b59d1d61 100644 --- a/src/Admin/Pages/Pages/SubPages/Rating.js +++ b/src/Admin/Pages/Pages/SubPages/Rating.js @@ -46,450 +46,376 @@ import StarRoundedIcon from "@material-ui/icons/StarRounded"; import styled from "styled-components" import MobileList from "../../../Components/Components/MobileComponents/SimpleList" -let currPage = 0; //var that controlls the current page that we are -let transformListToAsc = false; - const StyledTableCell = withStyles((theme) => ({ - head: { - backgroundColor: theme.palette.common.black, - color: theme.palette.common.white, - }, - body: { - fontSize: 14, - }, + head: { + backgroundColor: theme.palette.common.black, + color: theme.palette.common.white, + }, + body: { + fontSize: 14, + }, }))(TableCell); const StyledTableRow = withStyles((theme) => ({ - root: { - '&:nth-of-type(odd)': { - backgroundColor: theme.palette.action.hover, - }, + root: { + '&:nth-of-type(odd)': { + backgroundColor: theme.palette.action.hover, }, + }, }))(TableRow); const Ratings = () => { - const WINDOW_WIDTH = window.innerWidth - const AddOneLenght = ['']; - const [error, setError] = useState(null); //Necessary to consult the API, catch errors - const [isLoaded, setIsLoaded] = useState(false); //Necessary to consult the API, wait until complete - const [items, setItems] = useState([]); //Necessary to consult the API, data - const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false) - const [isUpdating, setIsUpdating] = useState(false) - - const [openAlertDialog, setOpenAlertDialog] = useState(false); //controlls the state od alert dialog - const [deleteItem, setDeleteItem] = useState({}); //Delete Item - const [isLoadingToDelete, setIsLoadingToDelete] = useState(null); - - const [snackInfo, setSnackInfo] = useState({ - message: '', - icon: '', - open: false, - color: '', + const WINDOW_WIDTH = window.innerWidth + const ADD_ONE_LENGHT = [""]; + + const [error, setError] = useState(null); //Necessary to consult the API, catch errors + const [isLoaded, setIsLoaded] = useState(false); //Necessary to consult the API, wait until complete + const [items, setItems] = useState([]); //Necessary to consult the API, data + const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false) + const [isUpdating, setIsUpdating] = useState(false) + const [currPage, setCurrPage] = useState(0) + const [openAlertDialog, setOpenAlertDialog] = useState(false); //controlls the state od alert dialog + const [deleteItem, setDeleteItem] = useState({}); //Delete Item + const [isLoadingToDelete, setIsLoadingToDelete] = useState(null); + + const [snackInfo, setSnackInfo] = useState({ + message: '', + icon: '', + open: false, + color: '', + }) + + // Handle snack infos + const HandleSnack = (message, state, icon, color) => { + setSnackInfo({ + message: message, + icon: icon, + open: state, + color: color }) - - // Handle snack infos - const HandleSnack = (message, state, icon, color) => { - setSnackInfo({ - message: message, - icon: icon, - open: state, - color: color - }) - } - - const LoadMoreItens = async (api) => { - setIsLoadingMoreItems(true) - getRequest( - api, - (data, header) => { - const arrData = [...data] - if (arrData.length === 0) { - HandleSnack('Não há mais dados para serem carregados', true, 'warning', '#FFC125') - } else { - const arrItems = [...items] - arrItems.pop(); //Deleting the last position, that was used to display the button of load more items - const arrResult = arrItems.concat(arrData) - setItems(arrResult.concat(AddOneLenght)) - } - setIsLoadingMoreItems(false) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - setIsLoadingMoreItems(false) - } - ) - } - - const InvertList = async () => { - transformListToAsc = !transformListToAsc - currPage = 0 - if (transformListToAsc) { - getRequest( - Url('ratings', '', `${currPage}`, 'ASC'), - (data, header) => { - const arrData = [...data] - setItems(arrData.concat(AddOneLenght)) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - } - ) + } + + //handle Delete + async function DeleteHandler() { + const id = deleteItem.id; + HandleStateAlertDialog(null); + deleteRequest( + DeleteFilter("ratings", id), + (data) => { + if (data.errors) + HandleSnack("Ocorreu algum erro", true, "warning", "#FA8072"); + else { + HandleSnack( + "O rating foi deletada com sucesso", + true, + "success", + "#228B22" + ); + setCurrPage(0) + HandleStateCircularProgress(null); + } + }, + (error) => { + HandleSnack("Ocorreu algum erro", true, "warning", "#FA8072"); + HandleStateCircularProgress(null); + } + ) + } + + const HandleStateCircularProgress = (i) => { + setIsLoadingToDelete(i); + }; + + const HandleStateAlertDialog = (i) => { + const obj = { ...items[i] }; + setDeleteItem(obj); + setOpenAlertDialog(!openAlertDialog); + }; + + + useEffect(() => { + if (currPage === 0) + setIsLoaded(false) + else + setIsLoadingMoreItems(true) + getRequest( + Url("ratings", "", currPage, "DESC"), + (data, header) => { + const arrData = [...data] + if (arrData.length === 0) { + HandleSnack('Não há mais dados para serem carregados', true, 'warning', '#FFC125') } else { - getRequest( - Url('ratings', '', `${currPage}`, 'DESC'), - (data, header) => { - const arrData = [...data] - setItems(arrData.concat(AddOneLenght)) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - } - ) + const arrItems = [...items] + if (currPage === 0) { + setItems(arrData.concat(ADD_ONE_LENGHT)) + } + else { + arrItems.pop(); //Deleting the last position, that was used to display the button of load more items + const arrResult = arrItems.concat(arrData) + setItems(arrResult.concat(ADD_ONE_LENGHT)) + } } - } - - const UpdateHandler = async (api) => { - setIsUpdating(true) - getRequest( - api, - (data, header) => { - HandleSnack('A lista de dados foi atualizada', true, 'success', '#228B22') - const arrData = [...data] - setItems(arrData.concat(AddOneLenght)) - setIsUpdating(false) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - setIsUpdating(false) - } - ) - } - - //handle Delete - async function DeleteHandler() { - const id = deleteItem.id; - HandleStateAlertDialog(null); - deleteRequest( - DeleteFilter("ratings", id), - (data) => { - if (data.errors) - HandleSnack("Ocorreu algum erro", true, "warning", "#FA8072"); - else { - HandleSnack( - "O rating foi deletada com sucesso", - true, - "success", - "#228B22" - ); - currPage = 0; - transformListToAsc = false - UpdateHandler(Url("ratings", "", `${currPage}`, "DESC")); - HandleStateCircularProgress(null); - } - }, - (error) => { - HandleSnack("Ocorreu algum erro", true, "warning", "#FA8072"); - HandleStateCircularProgress(null); - } - ) - } - - const HandleStateCircularProgress = (i) => { - setIsLoadingToDelete(i); - }; - - const HandleStateAlertDialog = (i) => { - const obj = { ...items[i] }; - setDeleteItem(obj); - setOpenAlertDialog(!openAlertDialog); - }; - - - useEffect(() => { - getRequest( - Url('ratings', '', currPage, 'DESC'), - (data, header) => { - setIsLoaded(true); - setItems(data.concat(AddOneLenght)); - }, - (error) => { - setError(true) - } - ) - }, []); - - - if (error) { - return <div>Error: {error.message}</div>; - } else if (!isLoaded) { - return <LoadingSpinner text="Carregando..." /> - } else { - - //Words in the top part of the table - const topTable = ['ID', 'NOME', 'DESCRIÇÃO', 'VISUALIZAR', 'DELETAR']; - if (WINDOW_WIDTH <= 760) { - return ( - <div> - <SnackBar - severity={snackInfo.icon} - text={snackInfo.message} - snackbarOpen={snackInfo.open} - color={snackInfo.color} - handleClose={() => setSnackInfo({ - message: '', - icon: '', - open: false, - color: '' - })} - /> - <Paper style={{ padding: '1em' }}> - <Grid container spacing={3} direction="row" alignItems="center"> - <Grid item xs={12}> - <Typography variant="h4"> - Lista de ratings + setIsLoaded(true) + setIsLoadingMoreItems(false) + }, + (error) => { + HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') + setIsLoadingMoreItems(false) + setIsLoaded(true) + setError(true) + } + ) + }, [currPage]) + + + if (error) { + return <div>Error: {error.message}</div>; + } else if (!isLoaded) { + return <LoadingSpinner text="Carregando..." /> + } else { + + //Words in the top part of the table + const topTable = ['ID', 'NOME', 'DESCRIÇÃO', 'VISUALIZAR', 'DELETAR']; + if (WINDOW_WIDTH <= 800) { + return ( + <div> + <SnackBar + severity={snackInfo.icon} + text={snackInfo.message} + snackbarOpen={snackInfo.open} + color={snackInfo.color} + handleClose={() => setSnackInfo({ + message: '', + icon: '', + open: false, + color: '' + })} + /> + <Paper style={{ padding: '1em' }}> + <Grid container spacing={3} direction="row" alignItems="center"> + <Grid item xs={12}> + <Typography variant="h4"> + Lista de ratings </Typography> - </Grid> - <Grid - item - xs={12} - > - <Grid container justify="flex-start" spacing={3}> - <Grid item> - <Button - variant="contained" - color="secondary" - disabled={isUpdating} - onClick={() => { - currPage = 0 - transformListToAsc = false - UpdateHandler(Url('ratings', '', `${currPage}`, 'DESC')) - }} - startIcon={<UpdateRoundedIcon />} - > - { - isUpdating ? <CircularProgress size={24} /> : 'Atualizar' - } - </Button> - </Grid> - <Grid item> - <Link style={{ textDecoration: 'none' }} to={'/admin/CreateRating'}> - <Button - variant="contained" - color="secondary" - startIcon={<AddRoundedIcon style={{ fill: "white" }} />} - onClick={() => { - currPage = 0 - transformListToAsc = false - }} - > - Novo + </Grid> + <Grid + item + xs={12} + > + <Grid container justify="flex-start" spacing={3}> + <Grid item> + <Button + variant="contained" + color="secondary" + disabled={isUpdating} + onClick={() => { + setCurrPage(0) + }} + startIcon={<UpdateRoundedIcon />} + > + { + isUpdating ? <CircularProgress size={24} /> : 'Atualizar' + } + </Button> + </Grid> + <Grid item> + <Link style={{ textDecoration: 'none' }} to={'/admin/CreateRating'}> + <Button + variant="contained" + color="secondary" + startIcon={<AddRoundedIcon style={{ fill: "white" }} />} + > + Novo </Button> - </Link> - </Grid> - </Grid> - </Grid> - </Grid> - </Paper> - - <div style={{ height: '2em' }}></div> - - {items.map((row, index) => - index === items.length - 1 ? ( - <StyledDivButton> - <Button - key={index} - color="primary" - variant="text" - // disabled={isLoadingMoreItems} - startIcon={<AddRoundedIcon />} - disabled={isLoadingMoreItems} - onClick={() => { - currPage++ - if (transformListToAsc) { - LoadMoreItens(Url('ratings', '', `${currPage}`, 'ASC')) - } else { - LoadMoreItens(Url('ratings', '', `${currPage}`, 'DESC')) - } - }} - > - {isLoadingMoreItems ? ( - <CircularProgress size={24} /> - ) : ( - "Carregar mais itens" - )} - </Button> - </StyledDivButton> - ) : ( - <> - <MobileList - key={index} - title={row.name} - subtitle={row.id} - backColor={"#00bcd4"} - avatar={<StarRoundedIcon />} - href={`/admin/Rating/${row.id}`} - reset={() => { - currPage = 0; - }} - data={ - [ - { - title: "Descrição", - subtitle: row.description - } - ] - } - /> - <div style={{ height: "0.5em" }} /> - </> - ) + </Link> + </Grid> + </Grid> + </Grid> + </Grid> + </Paper> + + <div style={{ height: '2em' }}></div> + + {items.map((row, index) => + index === items.length - 1 ? ( + <StyledDivButton key="Load"> + <Button + key={index} + color="primary" + variant="text" + // disabled={isLoadingMoreItems} + startIcon={<AddRoundedIcon />} + disabled={isLoadingMoreItems} + onClick={() => { + setCurrPage(currPage + 1) + }} + > + {isLoadingMoreItems ? ( + <CircularProgress size={24} /> + ) : ( + "Carregar mais itens" )} - </div> - ) - } - else { - return ( - <div> - <SnackBar - severity={snackInfo.icon} - text={snackInfo.message} - snackbarOpen={snackInfo.open} - color={snackInfo.color} - handleClose={() => setSnackInfo({ - message: '', - icon: '', - open: false, - color: '' - })} - /> - <Paper style={{ padding: '1em' }}> - <Grid container spacing={3} direction="row" alignItems="center"> - <Grid item xs={6}> - <Typography variant="h4"> - Lista de ratings + </Button> + </StyledDivButton> + ) : ( + <> + <MobileList + key={row.created_at} + title={row.name} + subtitle={row.id} + backColor={"#00bcd4"} + avatar={<StarRoundedIcon />} + href={`/admin/Rating/${row.id}`} + reset={() => { + + }} + data={ + [ + { + title: "Descrição", + subtitle: row.description + } + ] + } + /> + <div style={{ height: "0.5em" }} /> + </> + ) + )} + </div> + ) + } + else { + return ( + <div> + <SnackBar + severity={snackInfo.icon} + text={snackInfo.message} + snackbarOpen={snackInfo.open} + color={snackInfo.color} + handleClose={() => setSnackInfo({ + message: '', + icon: '', + open: false, + color: '' + })} + /> + <Paper style={{ padding: '1em' }}> + <Grid container spacing={3} direction="row" alignItems="center"> + <Grid item xs={6}> + <Typography variant="h4"> + Lista de ratings </Typography> - </Grid> - <Grid - item - xs={6} - > - <Grid container justify="flex-end" spacing={3}> - <Grid item> - <Button - variant="contained" - color="secondary" - disabled={isUpdating} - onClick={() => { - currPage = 0 - transformListToAsc = false - UpdateHandler(Url('ratings', '', `${currPage}`, 'DESC')) - }} - startIcon={<UpdateRoundedIcon />} - > - { - isUpdating ? <CircularProgress size={24} /> : 'Atualizar' - } - </Button> - </Grid> - <Grid item> - <Link style={{ textDecoration: 'none' }} to={'/admin/CreateRating'}> - <Button - variant="contained" - color="secondary" - startIcon={<AddRoundedIcon style={{ fill: "white" }} />} - onClick={() => { - currPage = 0 - transformListToAsc = false - }} - > - Novo - </Button> - </Link> - </Grid> - </Grid> - </Grid> - </Grid> - </Paper> - - <div style={{ height: '2em' }}></div> - - <TableData - top={topTable} - onIconPressed={InvertList} + </Grid> + <Grid + item + xs={6} + > + <Grid container justify="flex-end" spacing={3}> + <Grid item> + <Button + variant="contained" + color="secondary" + disabled={isUpdating} + onClick={() => { + setCurrPage(0) + }} + startIcon={<UpdateRoundedIcon />} > - <TableBody> - {items.map((row, index) => ( - index === items.length - 1 ? - <StyledTableRow key={index}> - {/* Button to load more data */} - <StyledTableCell> - <Button - color='primary' - variant='text' - disabled={isLoadingMoreItems} - startIcon={<AddRoundedIcon />} - onClick={() => { - currPage++ - if (transformListToAsc) { - LoadMoreItens(Url('ratings', '', `${currPage}`, 'ASC')) - } else { - LoadMoreItens(Url('ratings', '', `${currPage}`, 'DESC')) - } - }} - > - { - isLoadingMoreItems ? <CircularProgress size={24} /> : 'Carregar mais itens' - } + { + isUpdating ? <CircularProgress size={24} /> : 'Atualizar' + } + </Button> + </Grid> + <Grid item> + <Link style={{ textDecoration: 'none' }} to={'/admin/CreateRating'}> + <Button + variant="contained" + color="secondary" + startIcon={<AddRoundedIcon style={{ fill: "white" }} />} + > + Novo </Button> - </StyledTableCell> - </StyledTableRow> - - : - - <StyledTableRow key={index}> - <StyledTableCell component="th" scope="row">{row.id}</StyledTableCell> - <StyledTableCell align="right">{row.name}</StyledTableCell> - <StyledTableCell align="right">{row.description}</StyledTableCell> - <StyledTableCell align="right"> - <Link to={`/admin/Rating/${row.id}`}> - <IconButton onClick={() => { currPage = 0 }}> - <VisibilityIcon style={{ fill: '#00bcd4' }} /> - </IconButton> - </Link> - </StyledTableCell> - <StyledTableCell align="right"> - {isLoadingToDelete === index ? ( - <CircularProgress size={24} color="primary" /> - ) : ( - <IconButton - onClick={() => { - HandleStateAlertDialog(index); - HandleStateCircularProgress(index); - }} - > - <DeleteRoundedIcon style={{ fill: "#FF0000" }} /> - </IconButton> - )} - </StyledTableCell> - </StyledTableRow> - ))} - </TableBody> - </TableData> - - {/* This alert will be displayed if the user click to delete an institution */} - <AlertDialog - open={openAlertDialog} - OnDelete={DeleteHandler} - deleteItem={deleteItem} - HandleClose={() => { - setOpenAlertDialog(false); - HandleStateCircularProgress(null); + </Link> + </Grid> + </Grid> + </Grid> + </Grid> + </Paper> + + <div style={{ height: '2em' }}></div> + + <TableData + top={topTable} + > + <TableBody> + {items.map((row, index) => ( + index === items.length - 1 ? + <StyledTableRow key={row.created_at}> + {/* Button to load more data */} + <StyledTableCell> + <Button + color='primary' + variant='text' + disabled={isLoadingMoreItems} + startIcon={<AddRoundedIcon />} + onClick={() => { + setCurrPage(currPage + 1) }} - /> - </div> - ) - } + > + { + isLoadingMoreItems ? <CircularProgress size={24} /> : 'Carregar mais itens' + } + </Button> + </StyledTableCell> + </StyledTableRow> + + : + + <StyledTableRow key={row.created_at}> + <StyledTableCell component="th" scope="row">{row.id}</StyledTableCell> + <StyledTableCell align="right">{row.name}</StyledTableCell> + <StyledTableCell align="right">{row.description}</StyledTableCell> + <StyledTableCell align="right"> + <Link to={`/admin/Rating/${row.id}`}> + <IconButton> + <VisibilityIcon style={{ fill: '#00bcd4' }} /> + </IconButton> + </Link> + </StyledTableCell> + <StyledTableCell align="right"> + {isLoadingToDelete === index ? ( + <CircularProgress size={24} color="primary" /> + ) : ( + <IconButton + onClick={() => { + HandleStateAlertDialog(index); + HandleStateCircularProgress(index); + }} + > + <DeleteRoundedIcon style={{ fill: "#FF0000" }} /> + </IconButton> + )} + </StyledTableCell> + </StyledTableRow> + ))} + </TableBody> + </TableData> + + {/* This alert will be displayed if the user click to delete an institution */} + <AlertDialog + open={openAlertDialog} + OnDelete={DeleteHandler} + deleteItem={deleteItem} + HandleClose={() => { + setOpenAlertDialog(false); + HandleStateCircularProgress(null); + }} + /> + </div> + ) } + } } diff --git a/src/Admin/Pages/Pages/SubPages/Users.js b/src/Admin/Pages/Pages/SubPages/Users.js index fe3524c9..94214712 100644 --- a/src/Admin/Pages/Pages/SubPages/Users.js +++ b/src/Admin/Pages/Pages/SubPages/Users.js @@ -46,603 +46,528 @@ import EmailRoundedIcon from '@material-ui/icons/EmailRounded'; import { apiDomain } from '../../../../env'; import noAvatar from "../../../../img/default_profile.png"; -let currPage = 0; //var that controlls the current page that we are -let transformListToAsc = false; -let nameFilter = ""; -let emailFilter = ""; const StyledTableCell = withStyles((theme) => ({ - head: { - backgroundColor: theme.palette.common.black, - color: theme.palette.common.white, - }, - body: { - fontSize: 14, - }, + head: { + backgroundColor: theme.palette.common.black, + color: theme.palette.common.white, + }, + body: { + fontSize: 14, + }, }))(TableCell); const StyledTableRow = withStyles((theme) => ({ - root: { - '&:nth-of-type(odd)': { - backgroundColor: theme.palette.action.hover, - }, + root: { + '&:nth-of-type(odd)': { + backgroundColor: theme.palette.action.hover, }, + }, }))(TableRow); const Users = () => { - const AddOneLenght = ['']; - const WINDOW_WIDTH = window.innerWidth - const [error, setError] = useState(null); //Necessary to consult the API, catch errors - const [isLoaded, setIsLoaded] = useState(false); //Necessary to consult the API, wait until complete - const [items, setItems] = useState([]); //Necessary to consult the API, data - const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false) - const [isUpdating, setIsUpdating] = useState(false) - const [showFilter, setShowFilter] = useState(false) - - const [name, setName] = useState(""); - const [email, setEmail] = useState(""); - - const [snackInfo, setSnackInfo] = useState({ - message: '', - icon: '', - open: false, - color: '', + const ADD_ONE_LENGHT = ['']; + const WINDOW_WIDTH = window.innerWidth + const [error, setError] = useState(null); //Necessary to consult the API, catch errors + const [isLoaded, setIsLoaded] = useState(false); //Necessary to consult the API, wait until complete + const [items, setItems] = useState([]); //Necessary to consult the API, data + const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false) + const [isUpdating, setIsUpdating] = useState(false) + const [showFilter, setShowFilter] = useState(false) + const [currPage, setCurrPage] = useState(0) + + const [name, setName] = useState(""); + const [nameValue, setNameValue] = useState("") + const [email, setEmail] = useState(""); + const [emailValue, setEmailValue] = useState("") + + const [snackInfo, setSnackInfo] = useState({ + message: '', + icon: '', + open: false, + color: '', + }) + + // Handle snack infos + const HandleSnack = (message, state, icon, color) => { + setSnackInfo({ + message: message, + icon: icon, + open: state, + color: color }) - - // Handle snack infos - const HandleSnack = (message, state, icon, color) => { - setSnackInfo({ - message: message, - icon: icon, - open: state, - color: color - }) + } + + const NameHandler = (event) => { + setNameValue(event.target.value) + } + + const EmailHandler = (event) => { + setEmailValue(event.target.value) + } + + const DisplayDate = (date) => { + const convertedData = moment.utc(date); + return moment(convertedData) + .format("LLL") + .toString(); + }; + + const isUserPublisher = (userRoles) => { + for (let index = 0; index < userRoles.length; index++) { + if (userRoles[index].id === 10) + return true; } - - const NameHandler = (event) => { - currPage = 0 - setName(event.target.value) - nameFilter = event.target.value - getRequest( - Url('users', `"name" : "${nameFilter}", "email" : "${emailFilter}"`, `${currPage}`, 'DESC'), - (data, header) => { - const arrData = [...data] - setItems(arrData.concat(AddOneLenght)) - HandleSnack('Filtro aplicado com sucesso', true, 'success', '#228B22') - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - } - ) - + return false; + } + + const turnUserPublisher = (userRoles, userId) => { + let roles_ids = []; + userRoles.map((role) => ( + roles_ids.push(role.id) + )) + roles_ids.push(10); + const body = { + "user": { + "role_ids": roles_ids + } } - - const EmailHandler = (event) => { - currPage = 0 - setEmail(event.target.value) - emailFilter = event.target.value - getRequest( - Url('users', `"name" : "${nameFilter}", "email" : "${emailFilter}"`, `${currPage}`, 'DESC'), - (data, header) => { - const arrData = [...data] - setItems(arrData.concat(AddOneLenght)) - HandleSnack('Filtro aplicado com sucesso', true, 'success', '#228B22') - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - } - ) - } - - const LoadMoreItens = async (api) => { - setIsLoadingMoreItems(true) - getRequest( - api, - (data, header) => { - const arrData = [...data] - if (arrData.length === 0) { - HandleSnack('Não há mais dados para serem carregados', true, 'warning', '#FFC125') - } else { - const arrItems = [...items] - arrItems.pop(); //Deleting the last position, that was used to display the button of load more items - const arrResult = arrItems.concat(arrData) - setItems(arrResult.concat(AddOneLenght)) - } - setIsLoadingMoreItems(false) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - setIsLoadingMoreItems(false) - } - ) - } - - const InvertList = async () => { - transformListToAsc = !transformListToAsc - currPage = 0 - if (transformListToAsc) { - getRequest( - Url('users', `"name" : "${nameFilter}", "email" : "${emailFilter}"`, `${currPage}`, 'ASC'), - (data, header) => { - const arrData = [...data] - setItems(arrData.concat(AddOneLenght)) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - } - ) - } else { - getRequest( - Url('users', `"name" : "${nameFilter}", "email" : "${emailFilter}"`, `${currPage}`, 'DESC'), - (data, header) => { - const arrData = [...data] - setItems(arrData.concat(AddOneLenght)) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - } - ) + putRequest( + `/users/${userId}`, + body, + (data) => { + if (data.errors) { + HandleSnack('Ocorreu algum erro', true, 'warning', '#FA8072') } - } - - const DisplayDate = (date) => { - const convertedData = moment.utc(date); - return moment(convertedData) - .format("LLL") - .toString(); - }; - - const UpdateHandler = async (api) => { - setIsUpdating(true) - getRequest( - api, - (data, header) => { - HandleSnack('A lista de dados foi atualizada', true, 'success', '#228B22') - const arrData = [...data] - setItems(arrData.concat(AddOneLenght)) - setIsUpdating(false) - }, - (error) => { - HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') - setIsUpdating(false) - } - ) - } - - const isUserPublisher = (userRoles) => { - for (let index = 0; index < userRoles.length; index++) { - if (userRoles[index].id === 10) - return true; + else { + HandleSnack(`O usuário ${userId}, agora é publicador`, true, 'success', '#228B22') + setCurrPage(0) } - return false; - } - - const turnUserPublisher = (userRoles, userId) => { - let roles_ids = []; - userRoles.map((role) => ( - roles_ids.push(role.id) - )) - roles_ids.push(10); - const body = { - "user": { - "role_ids": roles_ids - } + }, + (error) => { + HandleSnack('Ocorreu algum erro', true, 'warning', '#FA8072') + } + ) + } + + const buildUrl = (email, name) => { + if (email && name) + return Url("/users", `"email" : "${email}", "name" : "${name}"`, currPage, "DESC") + if (email) + return Url("/users", `"email" : "${email}"`, currPage, "DESC") + if (name) + return Url("/users", `"name" : "${name}"`, currPage, "DESC") + else + return Url("/users", "", currPage, "DESC") + } + + useEffect(() => { + if (currPage === 0) + setIsLoaded(false) + else + setIsLoadingMoreItems(true) + getRequest( + buildUrl(email, name), + (data, header) => { + const arrData = [...data] + if (arrData.length === 0) { + HandleSnack('Não há mais dados para serem carregados', true, 'warning', '#FFC125') + } else { + const arrItems = [...items] + if (currPage === 0) { + setItems(arrData.concat(ADD_ONE_LENGHT)) + } + else { + arrItems.pop(); //Deleting the last position, that was used to display the button of load more items + const arrResult = arrItems.concat(arrData) + setItems(arrResult.concat(ADD_ONE_LENGHT)) + } } - putRequest( - `/users/${userId}`, - body, - (data) => { - if (data.errors) { - HandleSnack('Ocorreu algum erro', true, 'warning', '#FA8072') - } - else { - currPage = 0; - HandleSnack(`O usuário ${userId}, agora é publicador`, true, 'success', '#228B22') - UpdateHandler(Url('users', `"name" : "${nameFilter}", "email" : "${emailFilter}"`, `${currPage}`, 'DESC')) - } - }, - (error) => { - HandleSnack('Ocorreu algum erro', true, 'warning', '#FA8072') - } - ) - } - - useEffect(() => { - getRequest( - Url('users', `"name" : "${nameFilter}", "email" : "${emailFilter}"`, '0', 'DESC'), - (data, header) => { - setIsLoaded(true); - setItems(data.concat(AddOneLenght)); - }, - (error) => { - setError(true); - } - ) - }, []); - - - if (error) { - return <div>Error: {error.message}</div>; - } else if (!isLoaded) { - return <LoadingSpinner text="Carregando..." /> - } else { - - //Words in the top part of the table - const topTable = ['ID', 'NOME', 'EMAIL', 'CRIADO EM', 'SCORE', 'PERMISSÃO', 'AÇÃO', "VISUALIZAR"]; - if (WINDOW_WIDTH <= 1150) { - return ( - <div> - <SnackBar - severity={snackInfo.icon} - text={snackInfo.message} - snackbarOpen={snackInfo.open} - color={snackInfo.color} - handleClose={() => setSnackInfo({ - message: '', - icon: '', - open: false, - color: '' - })} - /> - <Paper style={{ padding: '1em' }}> - <Grid container spacing={3} direction="row" alignItems="center"> - <Grid item xs={12}> - <Typography variant="h4"> - Lista de usuários + setIsLoaded(true) + setIsLoadingMoreItems(false) + }, + (error) => { + HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072') + setIsLoaded(true) + setError(true) + setIsLoadingMoreItems(false) + } + ) + }, [currPage, email, name]) + + useEffect(() => { + setNameValue("") + setName("") + setEmailValue("") + setEmail("") + }, [showFilter]) + + + if (error) { + return <div>Error: {error.message}</div>; + } else if (!isLoaded) { + return <LoadingSpinner text="Carregando..." /> + } else { + + //Words in the top part of the table + const topTable = ['ID', 'NOME', 'EMAIL', 'CRIADO EM', 'SCORE', 'PERMISSÃO', 'AÇÃO', "VISUALIZAR"]; + if (WINDOW_WIDTH <= 1150) { + return ( + <div> + <SnackBar + severity={snackInfo.icon} + text={snackInfo.message} + snackbarOpen={snackInfo.open} + color={snackInfo.color} + handleClose={() => setSnackInfo({ + message: '', + icon: '', + open: false, + color: '' + })} + /> + <Paper style={{ padding: '1em' }}> + <Grid container spacing={3} direction="row" alignItems="center"> + <Grid item xs={12}> + <Typography variant="h4"> + Lista de usuários </Typography> - </Grid> - <Grid - item - xs={12} - > - <Grid container justify="flex-start" spacing={3}> - <Grid item> - <Button - variant="contained" - color="secondary" - disabled={isUpdating} - onClick={() => { - currPage = 0 - transformListToAsc = false - UpdateHandler(Url('users', `"name" : "${nameFilter}", "email" : "${emailFilter}"`, `${currPage}`, 'DESC')) - }} - startIcon={<UpdateRoundedIcon />} - > - { - isUpdating ? <CircularProgress size={24} /> : 'Atualizar' - } - </Button> - </Grid> - <Grid item> - <Button - variant="contained" - color="secondary" - onClick={() => { - setShowFilter(!showFilter) - }} - startIcon={<UpdateRoundedIcon />} - > - filtrar + </Grid> + <Grid + item + xs={12} + > + <Grid container justify="flex-start" spacing={3}> + <Grid item> + <Button + variant="contained" + color="secondary" + disabled={isUpdating} + onClick={() => { + setCurrPage(0) + }} + startIcon={<UpdateRoundedIcon />} + > + { + isUpdating ? <CircularProgress size={24} /> : 'Atualizar' + } + </Button> + </Grid> + <Grid item> + <Button + variant="contained" + color="secondary" + onClick={() => { + setShowFilter(!showFilter) + }} + startIcon={<UpdateRoundedIcon />} + > + filtrar </Button> - </Grid> - <Grid item> - <Link to="/admin/EditUser/-1"> - <Button - variant="contained" - color="secondary" - startIcon={<AddRoundedIcon />} - > - Novo + </Grid> + <Grid item> + <Link to="/admin/EditUser/-1"> + <Button + variant="contained" + color="secondary" + startIcon={<AddRoundedIcon />} + > + Novo </Button> - </Link> - </Grid> - </Grid> - </Grid> - </Grid> - { - showFilter ? ( - <Grid container direction="row" justify="space-between" alignItems="center"> - <Grid item> - <TextField - label="Name" - value={name} - onChange={(e) => { NameHandler(e) }} - /> - </Grid> - <Grid item> - <TextField - label="Email" - value={email} - onChange={(e) => { EmailHandler(e) }} - /> - </Grid> - </Grid> - ) : null - } - </Paper> - - <div style={{ height: '2em' }}></div> - - {items.map((row, index) => - index === items.length - 1 ? ( - <StyledDivButton> - <Button - key={index} - color="primary" - variant="text" - // disabled={isLoadingMoreItems} - startIcon={<AddRoundedIcon />} - disabled={isLoadingMoreItems} - onClick={() => { - currPage++ - if (transformListToAsc) { - LoadMoreItens(Url('users', `"name" : "${nameFilter}", "email" : "${emailFilter}"`, `${currPage}`, 'ASC')) - } else { - LoadMoreItens(Url('users', `"name" : "${nameFilter}", "email" : "${emailFilter}"`, `${currPage}`, 'DESC')) - } - }} - > - {isLoadingMoreItems ? ( - <CircularProgress size={24} /> - ) : ( - "Carregar mais itens" - )} - </Button> - </StyledDivButton> - ) : ( - <> - <MobileList - key={index} - title={row.name} - subtitle={row.id} - backColor={"#00bcd4"} - avatar={ - <img - src={row.avatar ? apiDomain + row.avatar : noAvatar} - alt="user avatar" - style={{ - height: "100%", - width: "100%", - borderRadius: "50%", - }} - /> - } - href={`/admin/user/${row.id}`} - reset={() => { - currPage = 0; - transformListToAsc = false - nameFilter = "" - emailFilter = "" - }} - data={[ - { - title: "Email", - subtitle: row.email ? - <Link to={`/admin/sendEmail/${row.email}`} style={{ textDecoration: 'none' }}> - <Button - variant='text' - color='primary' - startIcon={<EmailRoundedIcon />} - > - {row.email} - </Button> - </Link> : null - }, - { - title: "Criado em", - subtitle: DisplayDate(row.created_at) - }, - { - title: "Score", - subtitle: row.score - }, - { - title: "Permissão", - subtitle: row.roles.map((chip) => ( - <ChipDiv> - <Chip label={chip.name} key={chip.id} /> - </ChipDiv> - )) - }, - { - title: "Score", - subtitle: row.score - }, - { - title: "Ações rápidas", - subtitle: <Button - variant="contained" - color="primary" - disabled={isUserPublisher(row.roles)} - onClick={() => { turnUserPublisher(row.roles, row.id) }} - > - Tornar publicador - </Button> - } - - ]} - /> - <div style={{ height: "0.5em" }} /> - </> - ) - )} - </div> - ) - } - else { - return ( - <div> - <SnackBar - severity={snackInfo.icon} - text={snackInfo.message} - snackbarOpen={snackInfo.open} - color={snackInfo.color} - handleClose={() => setSnackInfo({ - message: '', - icon: '', - open: false, - color: '' - })} + </Link> + </Grid> + </Grid> + </Grid> + </Grid> + { + showFilter ? ( + <Grid container direction="row" justify="space-between" alignItems="center"> + <Grid item> + <TextField + label="Name" + value={nameValue} + onChange={(e) => { NameHandler(e) }} + onBlur={(e) => { setEmail(e.target.value) }} + helperText="Ao digitar, retire o foco do campo" /> - <Paper style={{ padding: '1em' }}> - <Grid container spacing={3} direction="row" alignItems="center"> - <Grid item xs={6}> - <Typography variant="h4"> - Lista de usuários - </Typography> - </Grid> - <Grid - item - xs={6} + </Grid> + <Grid item> + <TextField + label="Email" + value={emailValue} + onChange={(e) => { EmailHandler(e) }} + onBlur={(e) => { setEmail(e.target.value) }} + helperText="Ao digitar, retire o foco do campo" + /> + </Grid> + </Grid> + ) : null + } + </Paper> + + <div style={{ height: '2em' }}></div> + + {items.map((row, index) => + index === items.length - 1 ? ( + <StyledDivButton> + <Button + key={index} + color="primary" + variant="text" + // disabled={isLoadingMoreItems} + startIcon={<AddRoundedIcon />} + disabled={isLoadingMoreItems} + onClick={() => { + setCurrPage(currPage + 1) + }} + > + {isLoadingMoreItems ? ( + <CircularProgress size={24} /> + ) : ( + "Carregar mais itens" + )} + </Button> + </StyledDivButton> + ) : ( + <> + <MobileList + key={index} + title={row.name} + subtitle={row.id} + backColor={"#00bcd4"} + avatar={ + <img + src={row.avatar ? apiDomain + row.avatar : noAvatar} + alt="user avatar" + style={{ + height: "100%", + width: "100%", + borderRadius: "50%", + }} + /> + } + href={`/admin/user/${row.id}`} + reset={() => { + }} + data={[ + { + title: "Email", + subtitle: row.email ? + <Link to={`/admin/sendEmail/${row.email}`} style={{ textDecoration: 'none' }}> + <Button + variant='text' + color='primary' + startIcon={<EmailRoundedIcon />} > - <Grid container justify="flex-end" spacing={3}> - <Grid item> - <Button - variant="contained" - color="secondary" - disabled={isUpdating} - onClick={() => { - currPage = 0 - transformListToAsc = false - UpdateHandler(Url('users', `"name" : "${nameFilter}", "email" : "${emailFilter}"`, `${currPage}`, 'DESC')) - }} - startIcon={<UpdateRoundedIcon />} - > - { - isUpdating ? <CircularProgress size={24} /> : 'Atualizar' - } - </Button> - </Grid> - <Grid item> - <Button - variant="contained" - color="secondary" - onClick={() => { - setShowFilter(!showFilter) - }} - startIcon={<UpdateRoundedIcon />} - > - filtrar + {row.email} + </Button> + </Link> : null + }, + { + title: "Criado em", + subtitle: DisplayDate(row.created_at) + }, + { + title: "Score", + subtitle: row.score + }, + { + title: "Permissão", + subtitle: row.roles.map((chip) => ( + <ChipDiv> + <Chip label={chip.name} key={chip.id} /> + </ChipDiv> + )) + }, + { + title: "Score", + subtitle: row.score + }, + { + title: "Ações rápidas", + subtitle: <Button + variant="contained" + color="primary" + disabled={isUserPublisher(row.roles)} + onClick={() => { turnUserPublisher(row.roles, row.id) }} + > + Tornar publicador + </Button> + } + + ]} + /> + <div style={{ height: "0.5em" }} /> + </> + ) + )} + </div> + ) + } + else { + return ( + <div> + <SnackBar + severity={snackInfo.icon} + text={snackInfo.message} + snackbarOpen={snackInfo.open} + color={snackInfo.color} + handleClose={() => setSnackInfo({ + message: '', + icon: '', + open: false, + color: '' + })} + /> + <Paper style={{ padding: '1em' }}> + <Grid container spacing={3} direction="row" alignItems="center"> + <Grid item xs={6}> + <Typography variant="h4"> + Lista de usuários + </Typography> + </Grid> + <Grid + item + xs={6} + > + <Grid container justify="flex-end" spacing={3}> + <Grid item> + <Button + variant="contained" + color="secondary" + disabled={isUpdating} + onClick={() => { + setCurrPage(0) + }} + startIcon={<UpdateRoundedIcon />} + > + { + isUpdating ? <CircularProgress size={24} /> : 'Atualizar' + } + </Button> + </Grid> + <Grid item> + <Button + variant="contained" + color="secondary" + onClick={() => { + setShowFilter(!showFilter) + }} + startIcon={<UpdateRoundedIcon />} + > + filtrar </Button> - </Grid> - <Grid item> - <Link to="/admin/EditUser/-1"> - <Button - variant="contained" - color="secondary" - startIcon={<AddRoundedIcon />} - > - Novo + </Grid> + <Grid item> + <Link to="/admin/EditUser/-1"> + <Button + variant="contained" + color="secondary" + startIcon={<AddRoundedIcon />} + > + Novo </Button> - </Link> - </Grid> - </Grid> - </Grid> - </Grid> + </Link> + </Grid> + </Grid> + </Grid> + </Grid> + { + showFilter ? ( + <Grid container direction="row" justify="space-between" alignItems="center"> + <Grid item> + <TextField + label="Name" + value={nameValue} + onChange={(e) => { NameHandler(e) }} + onBlur={(e) => { setEmail(e.target.value) }} + helperText="Ao digitar, retire o foco do campo" + /> + </Grid> + <Grid item> + <TextField + label="Email" + value={emailValue} + onChange={(e) => { EmailHandler(e) }} + onBlur={(e) => { setEmail(e.target.value) }} + helperText="Ao digitar, retire o foco do campo" + /> + </Grid> + </Grid> + ) : null + } + </Paper> + + <div style={{ height: '2em' }}></div> + + <TableData + top={topTable} + > + <TableBody> + {items.map((row, index) => ( + index === items.length - 1 ? + <StyledTableRow key={index}> + {/* Button to load more data */} + <StyledTableCell> + <Button + color='primary' + variant='text' + disabled={isLoadingMoreItems} + startIcon={<AddRoundedIcon />} + onClick={() => { + setCurrPage(currPage + 1) + }} + > { - showFilter ? ( - <Grid container direction="row" justify="space-between" alignItems="center"> - <Grid item> - <TextField - label="Name" - value={name} - onChange={(e) => { NameHandler(e) }} - /> - </Grid> - <Grid item> - <TextField - label="Email" - value={email} - onChange={(e) => { EmailHandler(e) }} - /> - </Grid> - </Grid> - ) : null + isLoadingMoreItems ? <CircularProgress size={24} /> : 'Carregar mais itens' } - </Paper> - - <div style={{ height: '2em' }}></div> - - <TableData - top={topTable} - onIconPressed={InvertList} - > - <TableBody> - {items.map((row, index) => ( - index === items.length - 1 ? - <StyledTableRow key={index}> - {/* Button to load more data */} - <StyledTableCell> - <Button - color='primary' - variant='text' - disabled={isLoadingMoreItems} - startIcon={<AddRoundedIcon />} - onClick={() => { - currPage++ - if (transformListToAsc) { - LoadMoreItens(Url('users', `"name" : "${nameFilter}", "email" : "${emailFilter}"`, `${currPage}`, 'ASC')) - } else { - LoadMoreItens(Url('users', `"name" : "${nameFilter}", "email" : "${emailFilter}"`, `${currPage}`, 'DESC')) - } - }} - > - { - isLoadingMoreItems ? <CircularProgress size={24} /> : 'Carregar mais itens' - } - </Button> - </StyledTableCell> - </StyledTableRow> - - : - - <StyledTableRow key={index}> - <StyledTableCell component="th" scope="row">{row.id}</StyledTableCell> - <StyledTableCell align="right">{row.name}</StyledTableCell> - <StyledTableCell align="right">{row.email ? row.email : ""}</StyledTableCell> - <StyledTableCell align="right"> - {DisplayDate(row.created_at)} - </StyledTableCell> - <StyledTableCell align="right">{row.score}</StyledTableCell> - <StyledTableCell align="right"> - { - row.roles.map((chip) => ( - <ChipDiv> - <Chip label={chip.name} key={chip.id} /> - </ChipDiv> - )) - } - </StyledTableCell> - <StyledTableCell align="right"> - <Button - variant="contained" - color="primary" - disabled={isUserPublisher(row.roles)} - onClick={() => { turnUserPublisher(row.roles, row.id) }} - > - Tornar publicador + </Button> + </StyledTableCell> + </StyledTableRow> + + : + + <StyledTableRow key={index}> + <StyledTableCell component="th" scope="row">{row.id}</StyledTableCell> + <StyledTableCell align="right">{row.name}</StyledTableCell> + <StyledTableCell align="right">{row.email ? row.email : ""}</StyledTableCell> + <StyledTableCell align="right"> + {DisplayDate(row.created_at)} + </StyledTableCell> + <StyledTableCell align="right">{row.score}</StyledTableCell> + <StyledTableCell align="right"> + { + row.roles.map((chip) => ( + <ChipDiv> + <Chip label={chip.name} key={chip.id} /> + </ChipDiv> + )) + } + </StyledTableCell> + <StyledTableCell align="right"> + <Button + variant="contained" + color="primary" + disabled={isUserPublisher(row.roles)} + onClick={() => { turnUserPublisher(row.roles, row.id) }} + > + Tornar publicador </Button> - </StyledTableCell> - <StyledTableCell align="right"> - <Link to={`/admin/user/${row.id}`}> - <IconButton onClick={() => { - currPage = 0; - transformListToAsc = false - nameFilter = "" - emailFilter = "" - } - }> - <VisibilityIcon style={{ fill: '#00bcd4' }} /> - </IconButton> - </Link> - </StyledTableCell> - </StyledTableRow> - ))} - </TableBody> - </TableData> - </div> - ) - } + </StyledTableCell> + <StyledTableCell align="right"> + <Link to={`/admin/user/${row.id}`}> + <IconButton> + <VisibilityIcon style={{ fill: '#00bcd4' }} /> + </IconButton> + </Link> + </StyledTableCell> + </StyledTableRow> + ))} + </TableBody> + </TableData> + </div> + ) } + } } export default Users; -- GitLab