EditPlaza.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import React, { memo, useCallback, useMemo, useEffect } from 'react';
  2. import * as Yup from 'yup';
  3. import { useFormik, Form, FormikProvider } from 'formik';
  4. import { Modal } from 'react-bootstrap'
  5. import toast, { Toaster } from 'react-hot-toast';
  6. import DateFnsUtils from '@date-io/date-fns';
  7. import { DesktopDatePicker, LocalizationProvider } from '@mui/lab';
  8. import {
  9. Button, Stack, TextField, MenuItem, FormControl, InputLabel, Select,
  10. Backdrop, CircularProgress
  11. } from '@mui/material';
  12. import { Service } from '../../Utils/HTTP';
  13. import useAuth from '../../Auth/useAuth';
  14. import { useQuery, useMutation, useQueryClient } from 'react-query'
  15. const NewPlazaSchema = Yup.object().shape({
  16. id: Yup.number(),
  17. nombrepuesto:
  18. Yup.string().required('El nombre es requerido')
  19. .min(5, "El nombre del puesto debe ser mayor a 5 caracteres")
  20. .max(100),
  21. puestosuperior: Yup.number("El puesto superior debe ser un número").required("El puesto es requerido"),
  22. aredepto: Yup.number().required('Escoge alguna área'),
  23. fecha: Yup.date("Ingresa una fecha válida"),
  24. notas: Yup.string("Ingresa una nota válida").min(5).max(150),
  25. })
  26. function Edit(props) {
  27. const now = useMemo(() => new Date(), [])
  28. const auth = useAuth();
  29. const token = auth.getToken();
  30. const queryClient = useQueryClient()
  31. let { visible, toggle, puesto } = props
  32. const [departamento, setDepartamento] = React.useState('');
  33. const [open, setOpen] = React.useState(false);
  34. const changeDepartamento = useCallback((event) => {
  35. setDepartamento(event.target.value);
  36. }, []);
  37. const [date, setDate] = React.useState(now);
  38. const getCategories = async () => {
  39. let rest = new Service("/categoria/getAll")
  40. return await rest.getQuery(token)
  41. }
  42. const updatePuesto = async (fields) => {
  43. let rest = new Service('/plaza/edit');
  44. return rest.putQuery(fields, token)
  45. }
  46. const puestoMutation = useMutation(updatePuesto)
  47. const close = () => toggle("EDIT");
  48. const { data } = useQuery('categories', getCategories);
  49. const formik = useFormik({
  50. initialValues: {
  51. id: 1,
  52. nombrepuesto: "",
  53. puestosuperior: 1,
  54. aredepto: 1,
  55. fecha: now,
  56. notas: ""
  57. },
  58. onSubmit: (fields, { resetForm }) => {
  59. setOpen(true);
  60. fields['fecha'] = new Date(fields.fecha).toISOString();
  61. puestoMutation.mutate(fields, {
  62. onSuccess: () => {
  63. close();
  64. setOpen(false)
  65. toast.success("Puesto Actualizado!!")
  66. queryClient.invalidateQueries('puestos')
  67. },
  68. onError:() => {
  69. close();
  70. setOpen(false)
  71. toast.error("Lo sentimos ocurrió error inténtalo más tarde")
  72. }
  73. })
  74. resetForm();
  75. },
  76. validationSchema: NewPlazaSchema,
  77. });
  78. const { errors, touched, handleSubmit, getFieldProps, setValues } = formik;
  79. useEffect(() => {
  80. console.log("PUESTO :: ", puesto)
  81. if (puesto) {
  82. setValues({
  83. id: puesto.id,
  84. nombrepuesto: puesto.nombrepuesto,
  85. puestosuperior: puesto.puestosuperior,
  86. aredepto: puesto.areadeptoplz_id,
  87. fecha: new Date(puesto.create_day),
  88. notas: puesto.notas
  89. })
  90. }
  91. }, [puesto, now, setValues])
  92. return (
  93. <Modal size="lg" aria-labelledby="contained-modal-title-vcenter" centered show={visible} onHide={close}>
  94. <Modal.Header>
  95. <button onClick={close} type="button" className="close" data-dismiss="modal">&times;</button>
  96. <h4 className="modal-title" style={{ color: '#252525' }}>Editar puesto</h4>
  97. </Modal.Header>
  98. <Modal.Body className="modal-body">
  99. <FormikProvider style={{ padding: 25 }} value={formik}>
  100. <Form autoComplete="off" noValidate onSubmit={handleSubmit}>
  101. <Stack spacing={3}>
  102. <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
  103. <TextField
  104. label="Nombre"
  105. fullWidth
  106. {...getFieldProps('nombrepuesto')}
  107. error={Boolean(touched.nombrepuesto && errors.nombrepuesto)}
  108. helperText={touched.nombrepuesto && errors.nombrepuesto}
  109. />
  110. <TextField
  111. label="Puesto Superior"
  112. fullWidth
  113. {...getFieldProps('puestosuperior')}
  114. error={Boolean(touched.puestosuperior && errors.puestosuperior)}
  115. helperText={touched.puestosuperior && errors.puestosuperior}
  116. />
  117. </Stack>
  118. <Stack direction={{ xs: 'column', sm: 'row' }} spacing={2}>
  119. <FormControl fullWidth>
  120. <InputLabel id="demo-simple-select-label">Departamento</InputLabel>
  121. <Select
  122. labelId="demo-simple-select-label"
  123. value={departamento}
  124. label="Departamento"
  125. onChange={changeDepartamento}
  126. {...getFieldProps('aredepto')}
  127. error={Boolean(touched.aredepto && errors.aredepto)} >
  128. {
  129. data ?
  130. data.data.map(cate => {
  131. return (
  132. <MenuItem key={cate.id} value={cate.id}>{cate.nombre}</MenuItem>
  133. )
  134. })
  135. : <MenuItem>Null</MenuItem>
  136. }
  137. </Select>
  138. </FormControl>
  139. <LocalizationProvider
  140. dateAdapter={DateFnsUtils}>
  141. <DesktopDatePicker
  142. label="Fecha Creación"
  143. fullWidth
  144. inputFormat="dd/MM/yyyy"
  145. {...getFieldProps('fecha')}
  146. xd
  147. value={date}
  148. onChange={setDate}
  149. renderInput={(params) =>
  150. <TextField
  151. disabled={true}
  152. label="Fecha Creación"
  153. fullWidth
  154. {...params}
  155. />}
  156. />
  157. </LocalizationProvider>
  158. </Stack>
  159. <Stack direction={{ xs: 'column', sm: 'row' }} spacing={1}>
  160. <TextField
  161. id="filled-multiline-static"
  162. multiline
  163. rows={4}
  164. variant="filled"
  165. label="Notas"
  166. fullWidth
  167. type="text"
  168. {...getFieldProps('notas')}
  169. error={Boolean(touched.notas && errors.notas)}
  170. helperText={touched.notas && errors.notas}
  171. />
  172. </Stack>
  173. </Stack>
  174. <Modal.Footer>
  175. <Button
  176. type="submit"
  177. className="registerBtn"
  178. variant="contained"
  179. sx={{ mt: 1, mr: 1 }} >
  180. {'Actualizar'}
  181. </Button>
  182. </Modal.Footer>
  183. </Form>
  184. </FormikProvider>
  185. </Modal.Body>
  186. <Backdrop
  187. sx={{ color: '#fd4b4b', zIndex: (theme) => theme.zIndex.drawer + 1 }}
  188. open={open}
  189. onClick={() => console.log('backdrop')} >
  190. <CircularProgress color="inherit" />
  191. </Backdrop>
  192. <Toaster position="top-right" />
  193. </Modal>
  194. )
  195. }
  196. export default memo(Edit);