| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387 |
- import * as React from 'react';
- import {
- Button, Dialog, DialogActions, DialogContent,
- FormControlLabel, Checkbox, Stack,
- TextField, CircularProgress, Divider, Typography
- } from '@mui/material'
- import { AddCircle } from '@mui/icons-material/';
- import { MailTable } from './Steps/MailTable';
- import { Col, Row } from 'react-bootstrap'
- import toast, { Toaster } from 'react-hot-toast';
- import * as Yup from 'yup';
- import { yupResolver } from '@hookform/resolvers/yup';
- import { useQueryClient } from 'react-query'
- import { useForm, Controller } from "react-hook-form";
- import { Service } from '../../Utils/HTTP.js'
- import { useSelector } from 'react-redux'
- import { useFormik, Form, FormikProvider } from 'formik';
- import { AdapterDateFns as DateFnsUtils } from '@mui/x-date-pickers/AdapterDateFns';
- import { DesktopDatePicker } from '@mui/x-date-pickers/DesktopDatePicker';
- import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
- function Candidatos(props) {
- const CandidatoSchema = Yup.object().shape({
- nombres:
- Yup.string()
- .min(2, 'Demasiado corto!')
- .max(50, 'Demasiado largo!')
- .required('Ingresa un nombre válido'),
- apellidos:
- Yup.string()
- .min(2, 'Demasiado corto!')
- .max(50, 'Demasiado Largo!')
- .required('Ingresa un apellido válido'),
- mail:
- Yup.string()
- .required('Ingresa un email válido')
- .email("Correo no valido")
- });
- let { candidatos, add, remove } = props
- const formik = useFormik({
- initialValues: {
- nombres: "",
- apellidos: "",
- mail: "",
- },
- onSubmit: () => {
- if (!values.nombres || !values.apellidos || !values.mail) {
- return toast.error("Completa la informacion del candidato")
- }
- if (!isValid) {
- return toast.error("Completa la informacion del candidato")
- }
- let user = {
- 'id': -1,
- 'nombres': values.nombres,
- 'apellidos': values.apellidos,
- 'mail': values.mail,
- }
- add(user)
- resetForm();
- },
- validationSchema: CandidatoSchema,
- });
- var { errors, touched, handleSubmit, getFieldProps, values, resetForm, isValid } = formik;
- return (
- <FormikProvider style={{ padding: 25 }} value={formik}>
- <Typography style={{ padding: 5, marginBottom: 15 }}>Ingresa la informacion del candidato</Typography>
- <Divider />
- <Form autoComplete="off" noValidate onSubmit={handleSubmit}>
- <Stack spacing={3}>
- <Stack style={{ paddingTop: 15 }} direction={{ xs: 'column', sm: 'row' }} spacing={2}>
- <TextField
- label="Nombre"
- {...getFieldProps('nombres')}
- error={Boolean(touched.nombres && errors.nombres)}
- helperText={touched.nombres && errors.nombres}
- />
- <TextField
- label="Apellidos"
- {...getFieldProps('apellidos')}
- error={Boolean(touched.apellidos && errors.apellidos)}
- helperText={touched.apellidos && errors.apellidos}
- />
- </Stack>
- <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
- <TextField
- fullWidth
- type="email"
- label="Correo Electronico"
- {...getFieldProps('mail')}
- error={Boolean(touched.mail && errors.mail)}
- helperText={touched.mail && errors.mail}
- />
- <Button type="submit">
- <AddCircle style={{ color: 'var(--main)' }} />
- </Button>
- </Stack>
- <MailTable
- remove={remove}
- users={candidatos}
- />
- </Stack>
- </Form>
- </FormikProvider>
- );
- }
- export function ModalEdit(props) {
- const auth = useSelector((state) => state.token)
- let { password, open, handleOpen } = props
- let { pwd, plz } = password
- return (
- <Dialog
- fullWidth="md"
- maxWidth="md"
- open={open}
- onClose={() => handleOpen(false)}
- aria-labelledby="alert-dialog-title"
- aria-describedby="alert-dialog-description"
- >
- <DialogContent>
- <ModalForm
- pwdinfo={{ pwd, plz }}
- closeModal={handleOpen}
- token={auth.token}
- />
- </DialogContent>
- </Dialog>
- )
- }
- export function Loading() {
- return (
- <CircularProgress style={{ color: 'var(--main)' }} />
- )
- }
- function ModalForm(props) {
- let { pwdinfo, closeModal } = props
- const auth = useSelector((state) => state.token)
- let [candidatos, setCandidatos] = React.useState([]);
- let [password, setPassword] = React.useState();
- const queryClient = useQueryClient()
- const pwdSchema = Yup.object().shape({
- pwd: Yup.string(),
- deadpwd: Yup.date('Escoge una fecha valida').required("Escoge una fecha valida"),
- state: Yup.boolean(),
- dateToActived: Yup.date('Escoge una fecha valida').required("Escoge una fecha valida"),
- })
- const { reset, control, register, handleSubmit, formState: { errors } } = useForm({
- resolver: yupResolver(pwdSchema),
- defaultValues: {
- pwd: 0,
- deadpwd: 0,
- state: false,
- dateToActived: 0,
- }
- });
- React.useEffect(() => {
- let { pwd, plz } = pwdinfo;
- let rest = new Service(`/contrasenia/${btoa(pwd)}/${plz}`)
- rest.getQuery(auth.token)
- .then(resp => {
- let json_data = resp;
- let mapCandi = resp.data.candidatospwds.map(pwd => {
- let { apellidos, nombre, mail,id } = pwd.candi
- return { nombres: nombre, apellidos, mail, id }
- })
- json_data.data['candidatospwds'] = mapCandi;
- let password = json_data.data
- setPassword(password)
- setCandidatos(password.candidatospwds)
- reset({
- pwd: password.pwd,
- deadpwd: password.deadpwd,
- state: parseInt(password.state) === 1,
- dateToActived: password.dateToActived,
- })
- })
- .catch(error => console.log(error))
- }, [auth.token, pwdinfo, reset])
- const saveCandidato = async (body) => {
- let rest = new Service('/passwordcandidato/candidato')
- return await rest.postQuery(body, auth.token)
- }
- function onSubmit(fields) {
- let candi_body = candidatos.map( c => {
- return {...c,
- 'nombrepuesto': 'test',
- 'nombreEmpresa' : 'dit',
- "idContrasenia" : password.id,
- "sendmail": 1,
- }
- })
- let rest = new Service('/contrasenia/create');
- let { deadpwd, dateToActived, pwd, state } = fields
- fields['pwd'] = pwd;
- fields['deadpwd'] = new Date(deadpwd).toISOString();
- fields['dateToActived'] = new Date(dateToActived).toISOString();
- fields['link'] = 'www.psicoadmin.ditaca.org'
- fields['state'] = state ? 1 : 0
- delete password['candidato_id'];
- delete password['tokensecurity'];
- delete password['candidatospwds'];
- let body_req = {
- ...password, ...fields
- }
- rest.putQuery(body_req, auth.token)
- .then( async result => {
- queryClient.invalidateQueries('passwords')
- //TODO: insert into passwordcanidato/candidato
- await saveCandidato(candi_body)
- setTimeout(() => {
- closeModal(false)
- }, 1000)
- toast.success("Contraseña Actualizada")
- })
- .catch(bad => {
- console.log('ERROR', bad)
- toast.error("Ocurrio un error")
- })
- }
- function removeCandidato(umail) {
- let without = candidatos.filter(user => user.mail !== umail)
- setCandidatos(without)
- }
- function addCandidato(candidato) {
- let temp = [...candidatos, candidato]
- setCandidatos(temp)
- }
- return (
- <Row>
- <Col>
- <form style={{ padding: 20, maxWidth: 950 }} onSubmit={handleSubmit(onSubmit)}>
- <Stack spacing={4}>
- <TextField
- {...register('pwd')}
- variant="filled"
- disabled
- type="text"
- label="Contraseña Cifrada"
- />
- <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
- <TextField
- label="Nombre de la Contraseña"
- fullWidth
- variant="filled"
- value={password ? atob(password.pwd) : ""}
- type="text"
- disabled
- />
- <FormControlLabel
- label="Activo?"
- control={
- <Controller
- name="state"
- control={control}
- render={({ field: props }) =>
- <Checkbox
- style={{ color: 'var(--main)' }}
- checked={props.value}
- onChange={(e) => props.onChange(e.target.checked)}
- />
- }
- />
- }
- />
- </Stack>
- <LocalizationProvider dateAdapter={DateFnsUtils}>
- <Controller
- name="dateToActived"
- control={control}
- render={({ field }) =>
- <DesktopDatePicker
- {...field}
- label="Fecha de Activación"
- inputFormat="dd/MM/yyyy"
- fullWidth
- error={Boolean(errors?.dateToActived)}
- renderInput={(params) =>
- <TextField
- {...params}
- helperText={errors?.dateToActived?.message}
- />}
- />
- }
- >
- </Controller>
- </LocalizationProvider>
- <LocalizationProvider dateAdapter={DateFnsUtils}>
- <Controller
- name="deadpwd"
- control={control}
- render={({ field }) =>
- <DesktopDatePicker
- {...field}
- label="Fecha de Vencimiento"
- error={Boolean(errors?.deadpwd)}
- inputFormat="dd/MM/yyyy"
- renderInput={(params) =>
- <TextField
- {...params}
- helperText={errors?.deadpwd?.message}
- label="Fecha de Vencimiento"
- />}
- />
- }
- >
- </Controller>
- </LocalizationProvider>
- <DialogActions style={{ paddingTop: 25, 'justifyContent': "flex-start" }}>
- <Button onClick={() => closeModal(false)}>
- Cerrar
- </Button>
- <Button type="submit" style={{ color: 'white', background: 'var(--main)' }} >
- Guardar
- </Button>
- </DialogActions>
- </Stack>
- </form>
- <Toaster position="bottom-right" />
- </Col>
- <Col>
- <Candidatos
- add={addCandidato}
- remove={removeCandidato}
- candidatos={candidatos}
- />
- </Col>
- </Row>
- )
- }
|