import React, { useState, useEffect, useContext } from "react"; import * as Yup from "yup"; import { Formik, Form, Field } from "formik"; import { toast } from "react-toastify"; import { Button, Dialog, DialogActions, DialogContent, DialogTitle, CircularProgress, Select, InputLabel, MenuItem, FormControl, TextField, InputAdornment, IconButton } from '@material-ui/core'; import { Visibility, VisibilityOff } from '@material-ui/icons'; import { makeStyles } from "@material-ui/core/styles"; import { green } from "@material-ui/core/colors"; import { i18n } from "../../translate/i18n"; import api from "../../services/api"; import toastError from "../../errors/toastError"; import QueueSelect from "../QueueSelect"; import { AuthContext } from "../../context/Auth/AuthContext"; import { Can } from "../Can"; const useStyles = makeStyles(theme => ({ root: { display: "flex", flexWrap: "wrap", }, multFieldLine: { display: "flex", "& > *:not(:last-child)": { marginRight: theme.spacing(1), }, }, btnWrapper: { position: "relative", }, buttonProgress: { color: green[500], position: "absolute", top: "50%", left: "50%", marginTop: -12, marginLeft: -12, }, formControl: { margin: theme.spacing(1), minWidth: 120, }, })); const UserSchema = Yup.object().shape({ name: Yup.string() .min(2, "Too Short!") .max(50, "Too Long!") .required("Required"), password: Yup.string().min(5, "Too Short!").max(50, "Too Long!"), email: Yup.string().email("Invalid email").required("Required"), }); const UserModal = ({ open, onClose, userId }) => { const classes = useStyles(); const initialState = { name: "", email: "", password: "", profile: "user", }; const { user: loggedInUser } = useContext(AuthContext); const [user, setUser] = useState(initialState); const [selectedQueueIds, setSelectedQueueIds] = useState([]); const [showPassword, setShowPassword] = useState(false); useEffect(() => { const fetchUser = async () => { if (!userId) return; try { const { data } = await api.get(`/users/${userId}`); setUser(prevState => { return { ...prevState, ...data }; }); const userQueueIds = data.queues?.map(queue => queue.id); setSelectedQueueIds(userQueueIds); } catch (err) { toastError(err); } }; fetchUser(); }, [userId, open]); const handleClose = () => { onClose(); setUser(initialState); }; const handleSaveUser = async values => { const userData = { ...values, queueIds: selectedQueueIds }; try { if (userId) { await api.put(`/users/${userId}`, userData); } else { await api.post("/users", userData); } toast.success(i18n.t("userModal.success")); } catch (err) { toastError(err); } handleClose(); }; return (