From 2dea894cdd61dec41321db297d24ea510b195b39 Mon Sep 17 00:00:00 2001
From: Luis Felipe Risch <lfr20@inf.ufpr.br>
Date: Tue, 2 Mar 2021 13:03:59 -0300
Subject: [PATCH] Trying to fix problems with requests

---
 .../Components/DataCards/UserCard.js          |  49 +--
 .../Components/Components/Inputs/EditUser.js  | 336 ++++++++++++------
 src/Admin/Pages/Pages/SubPages/Users.js       |  83 ++---
 3 files changed, 293 insertions(+), 175 deletions(-)

diff --git a/src/Admin/Components/Components/DataCards/UserCard.js b/src/Admin/Components/Components/DataCards/UserCard.js
index 71142353..23d8abea 100644
--- a/src/Admin/Components/Components/DataCards/UserCard.js
+++ b/src/Admin/Components/Components/DataCards/UserCard.js
@@ -35,22 +35,20 @@ import CheckRoundedIcon from "@material-ui/icons/CheckRounded";
 import CloseRoundedIcon from "@material-ui/icons/CloseRounded";
 //imports from local files
 import { GetAData, DeleteFilter } from "../../../Filters";
-import { apiDomain} from '../../../../env';
+import { apiDomain } from '../../../../env';
 import noAvatar from "../../../../img/default_profile.png";
 import { Link } from "react-router-dom";
 import LoadingSpinner from '../../../../Components/LoadingSpinner';
 import SnackBar from '../../../../Components/SnackbarComponent';
 import { getRequest, postRequest, deleteRequest } from '../../../../Components/HelperFunctions/getAxiosConfig'
+import { useHistory } from "react-router-dom";
 //styles
 import styled from 'styled-components';
 
-const CollectionCard = ({ match }) => {
+const CollectionCard = ({ match }, props) => {
+    console.log(match); 
+    console.log(props);
     const classes = useStyles();
-
-    const roles = [
-        "", "professor", "aluno", "admin", "curador", "moderador", "supervisor", "editor", "parceiro", "publicador", "submetedor",
-    ];
-
     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 [item, setItem] = useState({});
@@ -138,6 +136,20 @@ const CollectionCard = ({ match }) => {
         })
     }
 
+    const reloadData = () => {
+        getRequest(
+            GetAData("users", match.params.id),
+            (data, header) => {
+                setItem(data)
+                setIsLoaded(true);
+                setError(false);
+            },
+            (error) => {
+                setError(true);
+            }
+        )
+    }
+
     const handleAprove = (userId, userName) => {
         const url = `/users/${userId}/add_teacher`
         const body = {
@@ -148,6 +160,7 @@ const CollectionCard = ({ match }) => {
             body,
             (data) => {
                 HandleSnack(`${userName} aceito como professor!`, true, "success", "#228B22");
+                reloadData()
             },
             (error) => {
                 HandleSnack("Erro!", true, "warning", "#FA8072");
@@ -158,15 +171,14 @@ const CollectionCard = ({ match }) => {
     const handleReject = (userId, userName) => {
         const url = `/users/${userId}/add_teacher`
         const body = {
-            "user": {
-                "approves": false
-            }
+            "approves": false
         }
         postRequest(
             url,
             body,
             (data) => {
                 HandleSnack(`${userName} rejeitado como professor!`, true, "success", "#228B22");
+                reloadData()
             },
             (error) => {
                 HandleSnack("Erro!", true, "warning", "#FA8072");
@@ -174,20 +186,16 @@ const CollectionCard = ({ match }) => {
         )
     }
 
-    const displayUserRole = (rolID) => {
-        if (rolID >= 9)
-            return roles[rolID - 1];
-        return roles[rolID];
-    }
-
     const deleteUser = (userId) => {
         deleteRequest(
-            DeleteFilter(`/users/${userId}`),
+            `/users/${userId}`,
             (data) => {
+                console.log(data);
                 HandleSnack(`${item.name} deletado com sucesso!`, true, "success", "#228B22");
             },
             (error) => {
                 HandleSnack("Erro!", true, "warning", "#FA8072");
+                console.log(error);
             }
         )
     }
@@ -197,7 +205,6 @@ const CollectionCard = ({ match }) => {
             GetAData("users", match.params.id),
             (data, header) => {
                 setItem(data)
-                console.log(data);
                 setIsLoaded(true);
                 setError(false);
             },
@@ -250,7 +257,7 @@ const CollectionCard = ({ match }) => {
                                     <Grid item>
                                         <Link
                                             style={{ textDecoration: "none" }}
-                                            to={`/admin/users/teacher_requests`}
+                                            to={`/admin/usersList`}
                                         >
                                             <Button
                                                 startIcon={<ListRoundedIcon />}
@@ -425,10 +432,10 @@ const CollectionCard = ({ match }) => {
                                             </Typography>
                                             <Grid container direction="row">
                                                 {
-                                                    item.role_ids.map((tag, index) => {
+                                                    item.roles.map((tag, index) => {
                                                         return (
                                                             <ChipDiv key={index}>
-                                                                <Chip label={displayUserRole(tag)} />
+                                                                <Chip label={tag.name} />
                                                             </ChipDiv>
                                                         )
                                                     })
diff --git a/src/Admin/Components/Components/Inputs/EditUser.js b/src/Admin/Components/Components/Inputs/EditUser.js
index 67d0521b..49118cd5 100644
--- a/src/Admin/Components/Components/Inputs/EditUser.js
+++ b/src/Admin/Components/Components/Inputs/EditUser.js
@@ -28,13 +28,16 @@ import Chip from '@material-ui/core/Chip';
 import { makeStyles } from '@material-ui/core/styles';
 import SaveIcon from '@material-ui/icons/Save';
 import DeleteRoundedIcon from '@material-ui/icons/DeleteRounded';
+import FormControlLabel from '@material-ui/core/FormControlLabel';
+import Switch from '@material-ui/core/Switch';
+import AddRoundedIcon from '@material-ui/icons/AddRounded';
 import MenuItem from '@material-ui/core/MenuItem';
 //imports local files
 import SnackBar from '../../../../Components/SnackbarComponent';
 import { Store } from '../../../../Store';
 import LoadingSpinner from '../../../../Components/LoadingSpinner';
 //imports services 
-import { getRequest, putRequest, deleteRequest } from '../../../../Components/HelperFunctions/getAxiosConfig'
+import { getRequest, putRequest, deleteRequest, postRequest } from '../../../../Components/HelperFunctions/getAxiosConfig'
 import { EditFilter, GetAData, DeleteFilter } from '../../../Filters';
 //routers
 import { Link } from 'react-router-dom';
@@ -57,14 +60,15 @@ const useStyles = makeStyles((theme) => ({
 
 const EditUser = ({ match }) => {
     const classes = useStyles();
-    const { state, dispatch } = useContext(Store);
+    const { state, dispatch } = useContext(Store)
+    const id = match.params.id
 
-    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 [error, setError] = useState(id !== "-1" ? null : false); //Necessary to consult the API, catch errors
+    const [isLoaded, setIsLoaded] = useState(id === "-1" ? true : false); //Necessary to consult the API, wait until complete
 
+    const [switchState, setSwitchState] = useState(id !== "-1" ? false : false)
     const [isLoading, setIsLoading] = useState(false);
-    const id = match.params.id
-    const [name, setName] = useState("")
+    const [name, setName] = useState(id !== "-1" ? "" : "Novo usuário")
     const [email, setEmail] = useState("")
     const [description, setDescription] = useState("")
     const [pass, setPass] = useState("")
@@ -238,7 +242,7 @@ const EditUser = ({ match }) => {
             error: errorInPass.error,
             errorMessage: errorInPass.message,
             onChange: (event) => PassHandler(event),
-            default: false,
+            default: id !== "-1" ? true : false,
             type: 'text'
         },
         {
@@ -247,7 +251,7 @@ const EditUser = ({ match }) => {
             error: errorInConfirmPass.error,
             errorMessage: errorInConfirmPass.message,
             onChange: (event) => ConfirmPassHandler(event),
-            default: false,
+            default: id !== "-1" ? true : false,
             type: 'text'
         },
     ]
@@ -290,7 +294,7 @@ const EditUser = ({ match }) => {
 
     const deleteUser = (userId) => {
         deleteRequest(
-            DeleteFilter(`/users/${userId}`),
+            `/users/${userId}`,
             (data) => {
                 HandleSnack(`${name} deletado com sucesso!`, true, "success", "#228B22");
             },
@@ -301,51 +305,125 @@ const EditUser = ({ match }) => {
     }
 
     const onSubmit = async () => {
-        // setIsLoading(true)
+        setIsLoading(true)
         let userRolesID = [];
-        if (!isEmpty(name) && !isEmpty(email)) {
-            const api = EditFilter('user', id)
-            userRoles.map((role) => {
-                userRolesID.push(role.id);
-            })
-            const body = {
-                "user": {
-                    "name": name,
-                    "subjects" : [],
-                    "role_ids": userRolesID,
-                    "institution_ids" : []
-                }
+        const api = EditFilter('users', id)
+        userRoles.map((role) => (
+            userRolesID.push(role.id)
+        ))
+        const body = {
+            "user": {
+                "name": name,
+                "email": email,
+                "description": description,
+                "role_ids": userRolesID,
+                "terms_of_service": switchState
             }
-            console.log(body);
-            putRequest(
-                api,
-                body,
-                (data) => {
-                    HandleSnack('A linguagem foi alterada com sucesso', true, 'success', '#228B22')
-                    setIsLoading(false)
-                },
-                (error) => {
-                    HandleSnack('Ocorreu algum erro', true, 'warning', '#FA8072')
-                    setIsLoading(false)
-                }
-            )
         }
-        else {
-            HandleSnack('Você precisa preencher algumas informações obrigatórias', true, 'warning', '#FFC125')
-            if (isEmpty(name)) {
-                setErrorInName({
-                    error: true,
-                    message: 'Este campo precisa ser preenchido'
-                })
+        putRequest(
+            api,
+            body,
+            (data) => {
+                setIsLoading(false)
+                if (data.id)
+                    HandleSnack(`O usuário: ${name} foi atualizado`, true, 'success', '#228B22')
+                else {
+                    if (data.email) {
+                        let emailError = "";
+                        data.email.map((msg) => (
+                            emailError = emailError + msg + " e "
+                        ))
+                        setErrorInEmail({
+                            error: true,
+                            message: emailError
+                        })
+                    }
+                    if (data.terms_of_service) {
+                        let termsError = "termos de serviço ";
+                        data.terms_of_service.map((msg) => (
+                            termsError = termsError + msg + " e "
+                        ))
+                        HandleSnack(termsError, true, 'warning', '#FFC125')
+                    }
+                }
+            },
+            (error) => {
+                HandleSnack('Ocorreu algum erro', true, 'warning', '#FA8072')
+                setIsLoading(false)
             }
-            if (isEmpty(email)) {
-                setErrorInEmail({
-                    error: true,
-                    message: 'Este campo precisa ser preenchido'
-                })
+        )
+    }
+
+    const onCreate = () => {
+        setIsLoading(true)
+        let userRolesID = [];
+        const api = "/users"
+        userRoles.map((role) => (
+            userRolesID.push(role.id)
+        ))
+        const body = {
+            "user": {
+                "name": name,
+                "email": email,
+                "description": description,
+                "role_ids": userRolesID,
+                "password": pass,
+                "password_confirmation": confirmPass,
+                "terms_of_service": switchState
             }
-            setIsLoading(false)
         }
+        postRequest(
+            api,
+            body,
+            (data) => {
+                setIsLoading(false)
+                if (data.id)
+                    HandleSnack(`O usuário: ${name} foi criado`, true, 'success', '#228B22')
+                else {
+                    if (data.password) {
+                        let passError = "";
+                        data.password.map((msg) => (
+                            passError = passError + msg + " e "
+                        ))
+                        setErrorInPass({
+                            error: true,
+                            message: passError
+                        })
+                    }
+                    if (data.email) {
+                        let emailError = "";
+                        data.email.map((msg) => (
+                            emailError = emailError + msg + " e "
+                        ))
+                        setErrorInEmail({
+                            error: true,
+                            message: emailError
+                        })
+                    }
+                    if (data.terms_of_service) {
+                        let termsError = "";
+                        data.terms_of_service.map((msg) => (
+                            termsError = termsError + msg + " e "
+                        ))
+                        HandleSnack(termsError, true, 'warning', '#FFC125')
+                    }
+                    if (data.password_confirmation) {
+                        let confirmError = "";
+                        data.password_confirmation.map((msg) => (
+                            confirmError = confirmError + msg + " e "
+                        ))
+                        setErrorInConfirmPass({
+                            error: true,
+                            message: confirmError
+                        })
+                    }
+                }
+            },
+            (error) => {
+                HandleSnack('Ocorreu algum erro', true, 'warning', '#FA8072')
+                setIsLoading(false)
+            }
+        )
     }
 
     const handleChange = (id, value) => {
@@ -361,29 +439,33 @@ const EditUser = ({ match }) => {
     };
 
     useEffect(() => {
-        getRequest(
-            GetAData("users", match.params.id),
-            (data, header) => {
-                const currRolesList = [...rolesList];
-                const auxiliarRolesId = [
-                    1, 2, 3, 4, 5, 6, 7, 9, 10, 11
-                ]
-                data.role_ids.map((data) => {
-                    const index = auxiliarRolesId.indexOf(data);
-                    currRolesList.splice(index, 1);
-                })
-                setRolesList(currRolesList);
-                setName(data.name)
-                setEmail(data.email)
-                setDescription(data.description)
-                setUserRoles(data.roles)
-                setIsLoaded(true);
-            },
-            (error) => {
-                setIsLoaded(true);
-                setError(error);
-            }
-        )
+        if (id !== "-1") {
+            getRequest(
+                GetAData("users", id),
+                (data, header) => {
+                    const currRolesList = [...rolesList];
+                    const auxiliarRolesId = [
+                        1, 2, 3, 4, 5, 6, 7, 9, 10, 11
+                    ]
+                    data.roles.map((data) => {
+                        const index = auxiliarRolesId.indexOf(data.id);
+                        currRolesList.splice(index, 1);
+                        auxiliarRolesId.splice(index, 1);
+                    })
+                    setRolesList(currRolesList);
+                    setName(data.name)
+                    setEmail(data.email)
+                    setDescription(data.description)
+                    setUserRoles(data.roles)
+                    setSwitchState(data.terms_accepted_at ? true : false)
+                    setIsLoaded(true);
+                },
+                (error) => {
+                    setIsLoaded(true);
+                    setError(error);
+                }
+            )
+        }
     }, []);
 
     if (error) {
@@ -415,45 +497,49 @@ const EditUser = ({ match }) => {
                         <Grid item>
                             <Grid container direction="row">
                                 <Grid item>
-                                    <Link style={{ textDecoration: 'none' }} to={'/admin/users/teacher_requests'}>
+                                    <Link style={{ textDecoration: 'none' }} to={'/admin/usersList'}>
                                         <Button
                                             startIcon={<ListRoundedIcon />}
                                             variant='outlined'
                                             color='primary'
                                         >
                                             Listar
-                                    </Button>
+                                        </Button>
                                     </Link>
                                 </Grid>
-                                <Grid item>
-                                    <Button
-                                        startIcon={<DeleteRoundedIcon />}
-                                        color="secondary"
-                                        variant="outlined"
-                                        onClick={() => { deleteUser(id) }}
-                                    >
-                                        Deletar
-                                </Button>
-                                </Grid>
+                                {
+                                    id !== "-1" ?
+                                        <Grid item>
+                                            <Button
+                                                startIcon={<DeleteRoundedIcon />}
+                                                color="secondary"
+                                                variant="outlined"
+                                                onClick={() => { deleteUser(id) }}
+                                            >
+                                                Deletar
+                                            </Button>
+                                        </Grid> : null
+                                }
                             </Grid>
                         </Grid>
                     </Grid>
                     <div style={{ height: '1em' }}></div>
                     <form style={{ display: 'flex', flexDirection: 'column' }}>
                         {fields.map((field, index) => (
-                            <TextField
-                                key={index}
-                                required={field.required}
-                                disabled={field.default}
-                                error={field.error}
-                                helperText={field.error ? field.errorMessage : ''}
-                                style={{ width: '250px', marginBottom: '1em' }}
-                                label={field.label}
-                                value={field.value}
-                                onChange={field.onChange}
-                                type="search"
-                                multiline={true}
-                            />
+                            field.value !== "-1" ?
+                                <TextField
+                                    key={index}
+                                    required={field.required}
+                                    disabled={field.default}
+                                    error={field.error}
+                                    helperText={field.error ? field.errorMessage : ''}
+                                    style={{ width: '250px', marginBottom: '1em' }}
+                                    label={field.label}
+                                    value={field.value}
+                                    onChange={field.onChange}
+                                    type="search"
+                                    multiline={true}
+                                /> : null
                         ))}
                         {userRoles.map((data) => {
                             return (
@@ -478,22 +564,50 @@ const EditUser = ({ match }) => {
                                 </MenuItem>
                             ))}
                         </TextField>
+                        <FormControlLabel
+                            control={
+                                <Switch
+                                    checked={switchState}
+                                    onChange={() => { setSwitchState(!switchState) }}
+                                    name="checkedB"
+                                    color="primary"
+                                />
+                            }
+                            label="Concorda com os termos de serviço?"
+                        />
                     </form>
                 </CardContent>
                 <CardAction>
-                    <Button
-                        onClick={() => {
-                            onSubmit();
-                        }}
-                        variant="contained"
-                        color="primary"
-                        disabled={isLoading}
-                        startIcon={isLoading ? null : <SaveIcon />}
-                    >
-                        {
-                            isLoading ? <CircularProgress size={24} /> : 'Salvar'
-                        }
-                    </Button>
+                    {
+                        id !== "-1" ?
+                            <Button
+                                onClick={() => {
+                                    onSubmit();
+                                }}
+                                variant="contained"
+                                color="primary"
+                                disabled={isLoading}
+                                startIcon={isLoading ? null : <SaveIcon />}
+                            >
+                                {
+                                    isLoading ? <CircularProgress size={24} /> : 'Salvar'
+                                }
+                            </Button>
+                            :
+                            <Button
+                                onClick={() => {
+                                    onCreate();
+                                }}
+                                variant="contained"
+                                color="primary"
+                                disabled={isLoading}
+                                startIcon={isLoading ? null : <AddRoundedIcon />}
+                            >
+                                {
+                                    isLoading ? <CircularProgress size={24} /> : 'Criar'
+                                }
+                            </Button>
+                    }
                 </CardAction>
             </Card>
         )
@@ -501,7 +615,3 @@ const EditUser = ({ match }) => {
 }
 
 export default EditUser;
-
-const SizedBox = styled.div`
-    height : 3em;
-`
\ No newline at end of file
diff --git a/src/Admin/Pages/Pages/SubPages/Users.js b/src/Admin/Pages/Pages/SubPages/Users.js
index d26d0347..cc753454 100644
--- a/src/Admin/Pages/Pages/SubPages/Users.js
+++ b/src/Admin/Pages/Pages/SubPages/Users.js
@@ -73,6 +73,10 @@ const Users = () => {
     const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false)
     const [isUpdating, setIsUpdating] = useState(false)
     const [showFilter, setShowFilter] = useState(false)
+    const [loadingUserPublisher, setLoadingUserPublisher] = useState({
+        id : null, 
+        loading : false
+    })
 
     const [name, setName] = useState("");
     const [email, setEmail] = useState("");
@@ -187,14 +191,6 @@ const Users = () => {
             .toString();
     };
 
-    const IsUserSubmitter = (userRolesId) => {
-        const index = userRolesId.indexOf(11);
-
-        if (index > -1)
-            return <Chip label="submitter" />
-        return
-    }
-
     const UpdateHandler = async (api) => {
         setIsUpdating(true)
         getRequest(
@@ -212,35 +208,38 @@ const Users = () => {
         )
     }
 
-    const isUserPublisher = (userRolesId) => {
-        const index = userRolesId.indexOf(10)
-        if(index > -1)  
-            return true; 
+    const isUserPublisher = (userRoles) => {
+        for (let index = 0; index < userRoles.length; index++) {
+            if (userRoles[index].id === 10)
+                return true;
+        }
         return false;
     }
 
-    const turnUserPublisher = (userRolesId, userId) => {
-        userRolesId.push(10); 
+    const turnUserPublisher = (userRoles, userId) => {
+        let roles_ids = []; 
+        userRoles.map((role) => (
+            roles_ids.push(role.id)
+        ))
+        roles_ids.push(10);
         const body = {
             "user": {
-                "user": {
-                    "role_ids": userRolesId
-                },
+                "role_ids": roles_ids
             }
         }
         putRequest(
-                `/users/${userId}`,
-                body,
-                (data) => {
-                    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')
-                }
-            )
-    }  
+            `/users/${userId}`,
+            body,
+            (data) => {
+                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(
@@ -283,8 +282,8 @@ const Users = () => {
                     <Grid container spacing={3} direction="row" alignItems="center">
                         <Grid item xs={6}>
                             <Typography variant="h4">
-                                Variáveis de nota
-                                </Typography>
+                                Lista de usuários
+                            </Typography>
                         </Grid>
                         <Grid
                             item
@@ -321,13 +320,15 @@ const Users = () => {
                                     </Button>
                                 </Grid>
                                 <Grid item>
-                                    <Button
-                                        variant="contained"
-                                        color="secondary"
-                                        startIcon={<AddRoundedIcon />}
-                                    >
-                                        Novo
+                                    <Link to="/admin/EditUser/-1">
+                                        <Button
+                                            variant="contained"
+                                            color="secondary"
+                                            startIcon={<AddRoundedIcon />}
+                                        >
+                                            Novo
                                     </Button>
+                                    </Link>
                                 </Grid>
                             </Grid>
                         </Grid>
@@ -401,7 +402,7 @@ const Users = () => {
                                         {
                                             row.roles.map((chip) => (
                                                 <ChipDiv>
-                                                    <Chip label={chip.name} key={chip.id}/>
+                                                    <Chip label={chip.name} key={chip.id} />
                                                 </ChipDiv>
                                             ))
                                         }
@@ -410,15 +411,15 @@ const Users = () => {
                                         <Button
                                             variant="contained"
                                             color="primary"
-                                            disabled={isUserPublisher(row.role_ids)}
-                                            onClick={() => {turnUserPublisher(row.role_ids, row.id)}}
+                                            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}}>
+                                            <IconButton onClick={() => { currPage = 0; transformListToAsc = false }}>
                                                 <VisibilityIcon style={{ fill: '#00bcd4' }} />
                                             </IconButton>
                                         </Link>
-- 
GitLab